qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
40,122,633
I want to check `if`/`else` condition in my blade file. I want to check the condition `$user->status =='waiting'` as the code given below. Output returns correctly as I expected. But along with my output I caught curly braces {} printed. I want to remove curly braces in result. Is there anything wrong in my `if` condition ? ``` @if($user->status =='waiting') { <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td> } @else{ <td>{{ $user->status }}</td> } @endif ```
2016/10/19
[ "https://Stackoverflow.com/questions/40122633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3386779/" ]
No curly braces required you can directly write ``` @if($user->status =='waiting') <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td> @else <td>{{ $user->status }}</td> @endif ```
You don't have to use braces in blade conditions, so your code would be like this: ``` @if($user->status =='waiting') <td> <a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal"> Approve/Reject <a> </td> @else <td> {{ $user->status }} </td> @endif ```
13,088,766
In C#, it seems the following method works which will allow you to call Streamreader.readline() and then access that very same line in the next loop. ``` string line; double score = 0; count = 0; while ((line = sr.ReadLine()) != null) { score += double.Parse (line); count++; } averageScore = (double)inValue / count; ``` This does not work in vb.net though, even with all the converters which I tried. this one completely bombs out and throws "page not found" <http://converter.telerik.com/> this one: <http://www.developerfusion.com/tools/convert/csharp-to-vb/?batchId=3356dd81-818a-43d1-8c23-be584e40d15e> results in : ``` Dim line As String Dim score As Double = 0 count = 0 While (InlineAssignHelper(line, sr.ReadLine())) IsNot Nothing score += Double.Parse(line) count += 1 End While averageScore = CDbl(inValue) / count ``` where InlineAssignHelper is something I dont have.
2012/10/26
[ "https://Stackoverflow.com/questions/13088766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477816/" ]
If you have the filename, instead of just a stream, you can use `System.IO.File.ReadLines` for the neatest way: ``` Dim score As Double = 0 count = 0 For Each line In File.ReadLines(filename) score += Double.Parse(sr.ReadLine()) count += 1 Next averageScore = CDbl(inValue) / count ``` Or use LINQ: ``` Dim averageScore = File.ReadLines(filename).Average(AddressOf Double.Parse) ```
Use a Do-Loop with an exit statement, like this: ``` Do Dim line = sr.ReadLine() If line Is Nothing Then Exit Do score += Double.Parse(line) count += 1 Loop ``` Do note the advantage of doing it this way over the accepted answer, it is very lean on memory usage and doesn't require the entire file to fit in memory.
3,357,553
If I didn't need localStorage, my code would look like this: ``` var names=new Array(); names[0]=prompt("New member name?"); ``` This works. However, I need to store this variable in localStorage and it's proving quite stubborn. I've tried: ``` var localStorage[names] = new Array(); localStorage.names[0] = prompt("New member name?"); ``` Where am I going wrong?
2010/07/28
[ "https://Stackoverflow.com/questions/3357553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/385815/" ]
`localStorage` only supports strings. Use `JSON.stringify()` and `JSON.parse()`. ``` var names = []; names[0] = prompt("New member name?"); localStorage.setItem("names", JSON.stringify(names)); //... var storedNames = JSON.parse(localStorage.getItem("names")); ``` You can also use direct access to set/get item: ``` localStorage.names = JSON.stringify(names); var storedNames = JSON.parse(localStorage.names); ```
Just created this: <https://gist.github.com/3854049> ``` //Setter Storage.setObj('users.albums.sexPistols',"blah"); Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" }); Storage.setObj('users.albums.sexPistols.sid',"Other songs"); //Getters Storage.getObj('users'); Storage.getObj('users.albums'); Storage.getObj('users.albums.sexPistols'); Storage.getObj('users.albums.sexPistols.sid'); Storage.getObj('users.albums.sexPistols.nancy'); ```
448,136
Могут ли быть слова “кисть - кидать” и “пасть - падать” однокоренными? По аналогии с: весть ведать; страсть страдать; власть обладать; сласть сладость; прясть прядь; красть обкрадывать; зависть завидывать; класть клад; вывести вывод; соблюсти соблюдать; ясти ядь.
2019/02/04
[ "https://rus.stackexchange.com/questions/448136", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/187289/" ]
Кисть-кидать никак не родственны, согласна с Aer♦, а вот пасть и падать всё-таки этимологические родственники, судя по этимол. словарям: Фасмер о происхождении слова пасть: > > Пасть - про́пасть, чеш. раst᾽ ж. «ловушка». Первично, по-видимому, > знач. «пропасть», от паду́. Ср. знач. в.-луж. khlama «морда, пасть» из > нем. Klamme «овраг» (Штрекель, AfslPh 14, 527) см. паду́. > > > У Шанского: > > Пасть (зев). Общеслав. Суф. производное (суф. -tь) от \*padti (> > пасть). Первоначально — «впадина» (такое значение в диалектах еще > отмечается). См. падать. Пасть (глагол). Общеслав., имеющее > соответствия в др. индоевроп. языках. Соврем. пасть из \*padti после > изменения dt > ст и отпадения конечного безударного и. Ср. падать. > > > <https://lexicography.online/etymology/%D0%BF/%D0%BF%D0%B0%D1%81%D1%82%D1%8C> А вот у Г.Цыганенко: > > ПАДАТЬ - <лететь сверху вниз>, <валиться на землю>, <идти, выпадать> > (об атмосферных осадках). Древн. слав. слово. Праслав. \*padati > <падать>, форма повторяющегося действия, как и соответствующая ей > форма некратного действия \*padti, давшая после изменения dt > tt > cm > и падения конечного безударного -и соврем, форму пасть2, происходит от > и.-е. \*podti <пасть>, собств. <свалиться вниз>. От падти с пом. суф. > -еж-ь образовано сущ. падежь > падёж (скота); с суф. -енщ-е - сущ. падение <отвлеч. действие пасть> (ср. от падать - падание). В глаг. > *padti и.-е. корень*pod-/\*ped- <низ> (изменение б > а). От и.-е. \*pod- с кратк. гласи. 6 (6 > о) в рус. яз. сущ. под1 <низ> (печи) и вторичн. > под2 - предл. См. падеж. пасть'1, педаль, пехота, подошва, почва. > > > <http://moyslovar.ru/slovari/etimolog_slovar/slovo/%D0%9F%D0%90%D0%94%D0%90%D0%A2%D0%AC> > > ПАСТЬ 1 - <зев, рот зверя, рыбы>. В рус. словарях фиксируется с I пол. > XVIII в. Образовано с пом. предметного суф. -ть (как горсть} от корня > пад- <низ, дол> - того же, что в глаг. \*падти (см. падать). > Предполагаемое \*падть претерпело изменение дт > mm > cm. Слово пасть! > < \*падть первонач. значило <впадина>, <провал>, <пропасть> (см. > Словарь Даля), а затем - <глубина рта, зев живота.>. От пасть1 > <провал> с прист. про-(по типу приставочных глаг.) - сущ. пропасть > <очень глубокая расщелина>, <беспредельная глубина>. См. пасть2 > > > ПАСТЬ 2 - паду <погибнуть на поле боя> (книжн.). Общеслав. Имеет > соответствия D других и.-е. языках. Соврем, слово развилось из > др.-рус. пасти <упасть, умереть> вследствие утраты конечного > безударного -и (ср. укр. вмети <упасть>, где -и сохраняется). Др.-рус. > пасти восходит к праслав. \*padti <пасть>. В нем **dt > tt > st**. > Праслав. \*padti представляет собой застывший дат. п. сущ. \*padtb <низ, > провал, впадина>. Следоват., пасть 2 буквально значит <падать вниз, > проваливаться> > <падать на землю>, <валиться на землю> > <погибнуть>. > От \*padti > пасть2 с прист. pro- > про- образован глаг. \*propadti > > пропасть <потеряться>, <исчезнуть>, а от него с суф. -а- - глаг. > несоверш. вида пропадать. > > > <http://moyslovar.ru/slovari/etimolog_slovar/slovo/%D0%9F%D0%90%D0%A1%D0%A2%D0%AC> В связи с этим ещё интересный факт в словаре Г.Цыганенко: > > ГОРСТЬ - <ладонь и пальцы руки, сложенные так, чтобы зачерпнуть, > захватить что-либо>. По корню праслав, Развилось из \*gorttb > <горсть> вследствие расподобления (диссимиляции) tt > st. **Сущ. \*gorttb > образовано с пом. суф. -t-ь (как пасть) от \*gort- с и.-е. корнем > \*gor-/\*ger- <собирать>. Ср. с этим корнем глаг. gortati > рус. диал. гортать <сгребать>, укр. пригортати <пригребать>, <прижимать>, горнути > <грести>, <обнимать>. Горсть - <то, чем пригребают, хватают что-либо>,** > <ладонь и пальцы руки> (ср. укр. урменя, от жму), далее - <то, что > можно захватить ладонью с пальцами>, напр., горсть зерна и т. п. Ср. > лтш. gurste <связка льна>;укр. горстка <пучок?, <небольшой сноп>. См. > грабить, грести. > > > <http://moyslovar.ru/slovari/etimolog_slovar/slovo/%D0%B3%D0%BE%D1%80%D1%81%D1%82%D1%8C> Так что кисть не то, чем кидают, а вот горсть - то, чем "гортают".
Слова "кисть" и слово "кидать" не однокоренные.Слова "пасть" (если не имеется ввиду ""челюсти", "рот" и т.п.) и "падать" - однокоренные.
11,953,087
I work with FORTRAN a lot, but I never had formal instruction in the proper way to write source code. I currently use modules to store global variables, but I understand you could also use them to store subroutines and functions. The codes I work with have many subroutines, as they are very large and complex. Should all functions and subroutines be in modules? If so, why?
2012/08/14
[ "https://Stackoverflow.com/questions/11953087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1046429/" ]
One of the major benefits of using modules is that your compiler will automatically perform interface checking on any functions or subroutines you `use` from a module to ensure that your are calling the routine with the appropriate parameter types. A good article on this topic is [Doctor Fortran Gets Explicit - Again!](http://software.intel.com/en-us/blogs/2012/01/05/doctor-fortran-gets-explicit-again/). From this article: > > There are several ways to provide an explicit interface. The simplest and best way is to put the procedure in a module, or make it a CONTAINed procedure of the calling program or procedure. This has the advantage of not requiring you to write the information twice and thus increasing the chances of getting it wrong in one of the places. When you have a module procedure, or a contained procedure, its interface is automatically visible to everything else in the module or in the parent scope. Assuming the name hasn't been declared PRIVATE, the interface is also available to places where you USE a module containing a module procedure. > > > I would recommend putting all *related* routines in the same module. Modules are, to me, the equivalent of classes in other languages. Modules are a way to group related data and routines (which may operate on that data). So modules offer a way of making your code easier to navigate, if your routines are grouped logically into modules, and add type checking to your function and subroutine calls.
Modules help the Fortran program by automatically providing the explicit interfaces, as already described in some of the other answers. This allows the compiler to check for consistency between arguments in procedure calls and the procedure declarations, which catches a lot of mistakes -- here are some Stackoverflow answer that show this benefit of modules: [Computing the cross product of two vectors in Fortran 90](https://stackoverflow.com/questions/6511711/computing-the-cross-product-of-two-vectors-in-fortran-90/6512578), [FORTRAN functions](https://stackoverflow.com/questions/11816351/fortran-functions/11818298) and [Fortran segmentation fault in pointer array](https://stackoverflow.com/questions/11876134/fortran-segmentation-fault-in-pointer-array)
27,807,018
I'm having a hard time copying files over to my Google Compute Engine. I am using an Ubuntu server on Google Compute Engine. I'm doing this from my OS X terminal and I am already authorized using `gcloud`. ``` local:$ gcloud compute copy-files /Users/Bryan/Documents/Websites/gce/index.php example-instance:/var/www/html --zone us-central1-a Warning: Permanently added '<IP>' (RSA) to the list of known hosts. scp: /var/www/html/index.php: Permission denied ERROR: (gcloud.compute.copy-files) [/usr/bin/scp] exited with return code [1]. ```
2015/01/06
[ "https://Stackoverflow.com/questions/27807018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2761425/" ]
The reason this doesn't work is that your username does not have permissions on the GCE VM instance and so cannot write to `/var/www/html/`. **Note** that since this question is about Google Compute Engine VMs, you cannot SSH directly to a VM as `root`, nor can you copy files directly as `root`, for the same reason: [`gcloud compute scp`](https://cloud.google.com/sdk/gcloud/reference/compute/scp) uses `scp` which relies on `ssh` for authentication. Possible solutions: 1. (also suggested by [Faizan](https://stackoverflow.com/users/3688301/faizan) in the comments) this solution will require two steps every time 1. use [`gcloud compute scp --recurse`](https://cloud.google.com/sdk/gcloud/reference/compute/scp) to transfer files/directories where your user can write to, e.g., `/tmp` or `/home/$USER` 2. login to the GCE VM via [`gcloud compute ssh`](https://cloud.google.com/sdk/gcloud/reference/compute/ssh) or via the *SSH* button on the console and copy using `sudo` to get proper permissions: ``` # note: sample command; adjust paths appropriately sudo cp -r $HOME/html/* /var/www/html ``` 2. this solution is one step with some prior prep work: 1. one-time setup: give your username write access to `/var/www/html` directly; this can be done in several ways; here's one approach: ``` # make the HTML directory owned by current user, recursively` sudo chown -R $USER /var/www/html ``` 2. now you can run the copy in one step: ``` gcloud compute scp --recurse \ --zone us-central1-a \ /Users/Bryan/Documents/Websites/gce/index.php \ example-instance:/var/www/html ```
I had the same problem and didn't get it to work using the methods suggested in the other answers. What finally worked was to explicitly send in my "user" when copying the file as indicated in the official [documentation](https://cloud.google.com/sdk/gcloud/reference/compute/scp). The important part being the "USER@" in ``` gcloud compute scp [[USER@]INSTANCE:]SRC [[[USER@]INSTANCE:]SRC …] [[USER@]INSTANCE:]DEST ``` In my case I could initially transfer files by typing: ``` gcloud compute scp instance_name:~/file_to_copy /local_dir ``` but after I got the permission denied I got it working by instead typing: ``` gcloud compute scp my_user_name@instance_name:~/file_to_copy /local_dir ``` where the username in my case was the one I was logged in to Google Cloud with.
16,298,527
I've got a doubt: Is this a good practice to find a parent which it's two levels above the matched element. The html structure looks like this: ``` <div class="cli_visitas left cli_bar hand" title="Control de las visitas del cliente"> <a href="/fidelizacion/visitas/nueva/id/<?php echo $cliente->getId();?>"> <span id="cli_visitas<?php echo $cliente->getId();?>" class="cli_bar_msg">La última visita <span class="lastvisit" ><?php echo $this->estados()->getUltimaVisita($cliente->getId());?></span></span> </a> </div> ``` '.lastvisit' fire the event, and I want to get the parent '.cli\_visitas' div I'm doing this: ``` $(this).parent().parent().parent().css({boxShadow : '0px 0px 5px #DF0101',backgroundColor:'#F89494'}); ``` Is this a good practice? I don't want to use .parents() method and iterate over each element and find the parent I'd like access it directly. I have tried with .get() but I think this method is not good for my propouse Is there another way to do it? Thank you very much. Greetings.
2013/04/30
[ "https://Stackoverflow.com/questions/16298527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913266/" ]
How about using: ``` $(this).closest('.cli_visitas').css(... ```
Why dont you want to use [`.parents()`](http://api.jquery.com/parents/)? You can do this chaining with the [`eq()`](http://api.jquery.com/eq/): ``` $(this).parents().eq(1); ```
63,548,783
I have several exports of telegram data and I would like to calculate the md5 and sha256 hash of all files but it only calculates those in the root directory `$ md5sum `ls` > hash.md5` ``` md5sum: chats: Is a directory md5sum: css: Is a directory md5sum: images: Is a directory md5sum: js: Is a directory md5sum: lists: Is a directory md5sum: profile_pictures: Is a directory ``` This is in the output file ``` 7e315ce28aa2f6474e69a7b7da2b5886 export_results.html 66281ec07a2c942f50938f93b47ad404 hash.md5 da5e2fde21c3e7bbbdb08a4686c3d936 ID.txt ``` There is a way to get something like this out? ``` 5750125fe13943f6b265505b25828400 js/script.js ``` *Sorry for my english*
2020/08/23
[ "https://Stackoverflow.com/questions/63548783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14152758/" ]
A tool which helps, but might not be installed by default, is `hashdeep`. `hashdeep` does it directly and has some more advantages, e.g. binary is available for Windows, too. Your question would be answered using `hashdeep` with this command: ``` hashdeep -c md5,sha256 -r -o f -l . > hash.md5 ``` This calculates md5 and sha256 of all files in all subdirs with one command. Creating md5 and sha256 together might be faster due to caching effects of the files. Additionally the command has an option to use multiple threads, which could fasten up the task with multi-core CPUs and fast disks.
Alternatively, you can use `find` with `-exec` option: ``` find topdir -type f -exec md5sum {} + > MD5SUMS ``` Replace the `topdir` with the actual directory name, or drop it if you want to work on the current directory (and its subdirectories, if any). This will only compute the checksums of regular files (so, no "*md5sum: something: Is a directory*" errors), and won't suffer from the "*argument list too long*" problem.
62,983,990
I am new to kotlin. And I got a problem. I have this code: ``` val sdf = SimpleDateFormat("dd.MM.yyyy") val currentDate = sdf.format(Date()) println(currentDate) val stringDate = "12.03.2015" val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH) val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter) .atStartOfDay(ZoneOffset.UTC) .toInstant() .toEpochMilli() println(millisecondsSinceEpoch) val time = currentDate - millisecondsSinceEpoch val Datee = sdf.format(time) println(Datee) ``` But on the line: ``` val time = currentDate - millisecondsSinceEpoch val Datee = sdf.format(time) println(Datee) ``` I get the error: ``` java.lang.IllegalArgumentException: Cannot format given Object as a Date ``` Please help me how you can fix this. I need to subtract the current date from the date that is in string. **UPDATE:** How to subtract one date from another correctly and get the difference in days?
2020/07/19
[ "https://Stackoverflow.com/questions/62983990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13829933/" ]
Following is the corrected version of your initial program. However as others pointed out it is advisable to use new java Time API. There is nice article highlighting problem with old Java Date and Calendar API <https://programminghints.com/2017/05/still-using-java-util-date-dont/> ``` import java.util.Date import java.util.Locale import java.time.Instant import java.time.LocalDateTime import java.time.LocalDate import java.time.ZoneOffset import java.text.SimpleDateFormat import java.time.format.DateTimeFormatter fun main(args: Array<String>) { val sdf = SimpleDateFormat("dd.MM.yyyy") val currentDate = Date() val currentFormattedDate = sdf.format(currentDate) println(currentFormattedDate) val now = currentDate.getTime(); val stringDate = "12.03.2015" val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH) val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter) .atStartOfDay(ZoneOffset.UTC) .toInstant() .toEpochMilli() println(millisecondsSinceEpoch) val time = now - millisecondsSinceEpoch val Datee = sdf.format(time) println(Datee) } ```
Get your required Date and then can do this: ``` val sdf = SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH) val theDate = sdf.parse(selectedDate) val selectedDate = theDate!!.time/86400000 //.time gives milliseconds val currentDate = sdf.parse(sdf.format(System.currentTimeMillis())) val currentDate = currentDate!!.time/86400000 //86400000 milliseconds in a day val diff = currentDate - selectedDate println(diffInMinutes.toString()) //set it to any view or use as needed ```
27,731,614
I am trying to check if the NSMutableArray has a specific object, before adding the object to it, if exists then don't add. i looked over many posts explaining how to do this, managed to implement it like this, but it always gives me that the object "doesn't exist", though i already added it ! ``` //get row details into FieldLables Object AllItemsFieldNames *FieldLabels = feedItems[row]; // object to hold single row detailes AllItemsFieldNames *SelectedRowDetails = [[AllItemsFieldNames alloc] init]; SelectedRowDetails.item_name = FieldLabels.item_name; //SelectedRowDetails.item_img = FieldLabels.item_img; SelectedRowDetails.item_price = FieldLabels.item_price; //NSLog(@"item has been added %@", SelectedRowDetails.item_name); //NSLog(@"shopcartLength %lu", (unsigned long)SelectedFieldsNames.count); if([SelectedFieldsNames containsObject:SelectedRowDetails]) { NSLog(@"Already Exists!"); } else { NSLog(@"Doesn't Exist!"); [SelectedFieldsNames addObject:SelectedRowDetails]; } ``` I can display all object from the NSMutableArray into a table, what i need to do in the above code is stop the addition of duplicate objects.
2015/01/01
[ "https://Stackoverflow.com/questions/27731614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4380614/" ]
The first method listed on the NSArray documentation under the section "querying an array" is `containsObject:`. If it's not working, that suggests that your implementation of `isEqual:` is not correct. Make sure you follow the note in the documentation: > > If two objects are equal, they must have the same hash value. This > last point is particularly important if you define isEqual: in a > subclass and intend to put instances of that subclass into a > collection. Make sure you also define hash in your subclass. > > > You might also consider using an `NSSet` since you can't add duplicates to that. Of course, this would also require a working version of `isEqual:`.
Sets are composed of unique elements, so this serves as a convenient way to remove all duplicates in an array. here some sample, ``` NSMutableArray*array=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil]; [array addObject:@"4"]; NSMutableSet*chk=[[NSMutableSet alloc ]initWithArray:array]; //finally initialize NSMutableArray to NSMutableSet array= [[NSMutableArray alloc] initWithArray:[[chk allObjects] sortedArrayUsingSelector:@selector(compare:)]]; //after assign NSMutableSet to your NSMutableArray and sort your array,because sets are unordered. NSLog(@"%@",array);//1,2,3,4 ```
16,735,092
Want to grep file and export the row like separated vars and the last two to be in one var. After that to create loop and export the vars in html tags. File view: ``` 1.1.1.1 host red 70% / 1.1.1.1 host green 0% /dev/shm 1.1.1.1 host green 63% /staging/om_campaign_files 1.1.1.1 host red 71% /mnt/OBCDir ``` Expected view after export the vars: ``` <tr><td>1.1.1.1<td/><td>host<td/><td color=red>/mnt/OBCDir<td/></tr> ```
2013/05/24
[ "https://Stackoverflow.com/questions/16735092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1716704/" ]
If you're looking for something usable in a program, rather than a one-liner at the command prompt: ``` #!/usr/bin/env perl use strict; use warnings; use 5.010; while (my $line = <DATA>) { chomp $line; my ($ip, $hostname, $color, undef, $mount) = split ' ', $line; say "<tr><td>$ip</td><td>$hostname</td><td color=$color>$mount</td></tr>"; } __DATA__ 1.1.1.1 host red 70% / 1.1.1.1 host green 0% /dev/shm 1.1.1.1 host green 63% /staging/om_campaign_files 1.1.1.1 host red 71% /mnt/OBCDir ``` Output: ``` <tr><td>1.1.1.1</td><td>host</td><td color=red>/</td></tr> <tr><td>1.1.1.1</td><td>host</td><td color=green>/dev/shm</td></tr> <tr><td>1.1.1.1</td><td>host</td><td color=green>/staging/om_campaign_files</td></tr> <tr><td>1.1.1.1</td><td>host</td><td color=red>/mnt/OBCDir</td></tr> ```
``` perl -anE 'say "<tr><td>$F[0]<td/><td>$F[1]<td/><td color=$F[2]>$F[4]<td/></tr>"' file ```
40,892,156
I'm learning to write scripts with PowerShell, and I found this code that will help me with a project The example comes from [Is there a one-liner for using default values with Read-Host?](https://stackoverflow.com/questions/26386267/is-there-a-one-liner-for-using-default-values-with-read-host). ``` $defaultValue = 'default' $prompt = Read-Host "Press enter to accept the default [$($defaultValue)]" $prompt = ($defaultValue,$prompt)[[bool]$prompt] ``` I think I understand that `$prompt = ($defaultValue,$prompt)` is creating a two-element array and that the `[bool]` part is forcing the `$prompt` data type to Boolean, but I don’t understand what this third line of code does as a whole.
2016/11/30
[ "https://Stackoverflow.com/questions/40892156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7231560/" ]
This is a common programming pattern: ``` if (user entered a price) { price = user entered value } else { price = default value } ``` and because that is quite common, and also long winded, some languages have a special `ternary operator` to write all that code much more concisely and assign a variable to "this value or that value" in one move. e.g. in C# you can write: ``` price = (user entered a price) ? (user entered value) : (default value) # var = IF [boolean test] ? THEN (x) ELSE (y) ``` and the `?` assigns `(x)` if the test is true, and `(y)` if the test is false. In Python, it's written: ``` price = (user entered value) if (user entered a price) else (default value) ``` And in PowerShell, it's written: ``` # you can't have a ternary operator in PowerShell, because reasons. ``` Yeah. No nice short code pattern allowed. But what you can do, is abuse array-indexing (`@('x', 'y')[0] is 'x'` and `@('x', 'y')[1] is 'y'` and ) and write that ugly and confusing code-golf line: ``` $price = ($defaultValue,$userValue)[[bool]$UserEnteredPrice] # var (x,y) is an array $array[ ] is array indexing (0,1) are the array indexes of the two values [bool]$UserEnteredPrice casts the 'test' part to a True/False value [True/False] used as indexes into an array indexing makes no sense so they implicitly cast to integers, and become 0/1 # so if the test is true, the $UserValue is assigned to $price, and if the test fails, the $DefaultValue is assigned to price. ``` And it behaves like a ternary operator, except it's confusing and ugly and in some situations it will trip you up if you're not careful by evaluating both array expressions regardless of which one is chosen (unlike real `?` operators). --- **Edit**: What I should really add is a PowerShell form I prefer - you can assign the result of an `if` test directly in PowerShell and do: ``` $price = if ($userValue) { $userValue } else { $DefaultValue } # -> $prompt = if ($prompt) { $prompt } else { $DefaultValue } ```
To *complement* the great answers given [by Ansgar Wiechers](https://stackoverflow.com/a/40892322/45375) and [by TessellatingHeckler](https://stackoverflow.com/a/40892457/45375): It *would* be great *if* PowerShell had operators for [ternary conditionals](https://en.wikipedia.org/wiki/%3F:) and [null-coalescing](https://en.wikipedia.org/wiki/Null_coalescing_operator), such as follows (applied to the example in the question): ``` # Ternary conditional # Note: does NOT work in PowerShell as of PSv5.1 $prompt = $prompt ? $prompt : $defaultValue # Or, more succinctly, with null coalescence: # Note: does NOT work in PowerShell as of PSv5.1 # (Note: This example assumes that $prompt will be $null in the default # case, whereas the code in the question actually assigns the # empty string to $prompt if the user just presses Enter.) $prompt = $prompt ?? $defaultValue ``` Unfortunately, these expressive constructs are (still) not part of PowerShell, and it seems that the PowerShell team has entered an extended period of disappointment that has lasted almost ten years as of this writing: > > At Microsoft, “to ship is to choose”.  One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator. > > > From a [PowerShell Team blog post](https://blogs.msdn.microsoft.com/powershell/2006/12/29/diy-ternary-operator/) dated 29 December 2006. That same blog post offers stopgaps in the form of *functions* that (imperfectly) *emulate* these operators. Trying to "fix" a language is always tricky business, however, so let's hope for a proper implementation some day. Below are adapted versions of the functions from the blog post with associated alias definitions, whose use then allows the following solution: ``` # Ternary conditional - note how the alias must come *first* # Note: Requires the function and alias defined below. $prompt = ?: $prompt $prompt $defaultValue # Or, more succinctly, with null coalescence - note how the alias must come *first* # Note: Requires the function and alias defined below. $prompt = ?? $prompt $defaultValue ``` --- **Source code**: Note that the actual functions are quite short; it is the comment-based help that makes this listing lengthy. ``` Set-Alias ?: Invoke-Ternary -Option AllScope <# .SYNOPSIS Emulation of a ternary conditional operator. .DESCRIPTION An emulation of the still-missing-from-the-PS-language ternary conditional, such as the C-style <predicate> ? <if-true> : <if-false> Because a function is used for emulation, however, the function name must come first in the invocation. If you define a succinct alias, e.g., set-alias ?: Invoke-Ternary, concise in-line conditionals become possible. To specify something other than a literal or a variable reference, pass a script block for any of the tree operands. A predicate script block is of necessity always evaluated, but a script block passed to the true or false branch is only evaluated on demand. .EXAMPLE > Invoke-Ternary { 2 -lt 3 } 'yes' 'no' Evaluates the predicate script block, which outputs $true, and therefore selects and outputs the true-case expression, string 'yes'. .EXAMPLE > Invoke-Ternary $false { $global:foo = 'bar' } { Get-Date } Outputs the result of executing Get-Date. Note that the true-case script block is NOT evaluated in this case. .NOTES Gratefully adapted from http://blogs.msdn.com/powershell/archive/2006/12/29/dyi-ternary-operator.aspx #> function Invoke-Ternary { [CmdletBinding()] param($Predicate, $Then, $Otherwise = $null) if ($(if ($Predicate -is [scriptblock]) { & $Predicate } else { $Predicate })) { if ($Then -is [ScriptBlock]) { & $Then } else { $Then } } else { if ($Otherwise -is [ScriptBlock]) { & $Otherwise } else { $Otherwise } } } Set-Alias ?? Invoke-NullCoalescence -Option AllScope <# .SYNOPSIS Emulation of a null-coalescence operator. .DESCRIPTION An emulation of a null-coalescence operator such as the following: <expr> ?? <alternative-expr-if-expr-is-null> Because a function is used for emulation, however, the function name must come first in the invocation. If you define a succinct alias, e.g., set-alias ?? Invoke-NullCoalescence, concise in-line null-coalescing becomes possible. To specify something other than a literal or a variable reference, pass a script block for any of the two operands. A first-operand script block is of necessity always evaluated, but a second-operand script block is only evaluated on demand. Note that only a true $null value in the first operand causes the second operand to be returned. .EXAMPLE > Invoke-NullCoalescence $null '(empty)' Since the first operand is $null, the second operand, string '(empty)', is output. .EXAMPLE > Invoke-NullCoalescence '' { $global:foo = 'bar' } Outputs the first operand, the empty string, because it is not $null. Note that the second-operand script block is NOT evaluated in this case. .NOTES Gratefully adapted from http://blogs.msdn.com/powershell/archive/2006/12/29/dyi-ternary-operator.aspx #> function Invoke-NullCoalescence { [CmdletBinding()] param($Value, $Alternative) if ($Value -is [scriptblock]) { $Value = & $Value } if ($null -ne $Value) { $Value } else { if ($Alternative -is [ScriptBlock]) { & $Alternative } else { $Alternative } } } ```
44,181,725
I have been trying to run tomcat container on port 5000 on cluster using kubernetes. But when i am using kubectl create -f tmocat\_pod.yaml , it creates pod but docker ps does not give any output. Why is it so? Ideally, when it is running a pod, it means it is running a container inside that pod and that container is defined in yaml file. Why is that docker ps does not show any containers running? I am following the below URLs: * <http://containertutorials.com/get_started_kubernetes/k8s_example.html> * <https://blog.jetstack.io/blog/k8s-getting-started-part2/> How can I get it running and see tomcat running on browser on port 5000.
2017/05/25
[ "https://Stackoverflow.com/questions/44181725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4661576/" ]
In Kubernetes, Docker contaienrs are run on Pods, and Pods are run on Nodes, and Nodes are run on your machine (minikube/GKE) When you run `kubectl create -f tmocat_pod.yaml` you basically create a pod and it runs the docker container on that pod. The node that holds this pod, is basically a virtual instance, if you could 'SSH' into that node, docker ps would work. What you need is: `kubectl get pods` <-- It is like docker ps, it shows you all the pods (think of it as docker containers) running `kubectl get nodes` <-- view the host machines for your pods. `kubectl describe pods <pod-name>` <-- view *system logs* for your pods. `kubectl logs <pod-name>` <-- Will give you logs for the specific pod.
I'm not sure where you are running the `docker ps` command, but if you are trying to do that from your host machine and the k8s cluster is located elsewhere, i.e. your machine is not a node in the cluster, `docker ps` will not return anything since the containers are not tied to your docker host. Assuming your pod is running, `kubectl get pods` will display all of your running pods. To check further details, you can use `kubectl describe pod <yourpodname>` to check the status of each container (in great detail). To get the pod names, you should be able to use tab-complete with the kubernetes cli. Also, if your pod contains multiple containers, you will need to give the container name as well, which you can use tab-complete for after you've selected your pod. The output will look similar to: ``` kubectl describe pod comparison-api-dply-reborn-6ffb88b46b-s2mtx Name: comparison-api-dply-reborn-6ffb88b46b-s2mtx Namespace: default Node: aks-nodepool1-99697518-0/10.240.0.5 Start Time: Fri, 20 Apr 2018 14:08:21 -0400 Labels: app=comparison-pod-reborn pod-template-hash=2996446026 ... Status: Running IP: *.*.*.* Controlled By: ReplicaSet/comparison-api-dply-reborn-6ffb88b46b Containers: rabbit-mq: ... Port: 5672/TCP State: Running ... ``` If your containers and pods are already running, then you shouldn't need to troubleshoot them too much. To make them accessible from the Public Internet, take a look at Services (<https://kubernetes.io/docs/concepts/services-networking/service/>) to make your API's IP address fixed and easily reachable.
62,399
I joined Facebook in 2008 but don't recall if I used its messaging function at the time. I checked my old deactivated account and the oldest message is from 2009. That's around 5 years ago now, so I'm wondering if Facebook deletes messages/inactive conversations older than 5 years? Being a teenager at the time I said some things I regret when messaging my friends over Facebook, so I'm certainly hoping this is the case. Not that anyone would probably care enough to look, I'd just feel easier if there was no record of anything dumb I said.
2014/06/08
[ "https://webapps.stackexchange.com/questions/62399", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/71984/" ]
Facebook does not delete old messages/conversations that haven't been active in years. (my oldest one: 2007-05-30). Note that at that time people often used to post on walls to discuss even private matters.
It seems they do delete old messages written to you by others, especially if those others are no longer on Facebook. My archived messages look like Swiss cheese, with only my side of conversations saved and even the names of my interlocutors and their messages deleted (redacted) somehow.
312,701
This IC is on a breakout board for a SIM868 chip. It is on the GPS antenna signal line, just before the U.FL connector. It has 5 pins, 3 that are connected to ground, 1 to the signal, and 1 (I think) to power. What is this chip and what does it do? Zoomed-in photo (IC's markings are visible): [![Zoomed in photo](https://i.stack.imgur.com/1yvDu.jpg)](https://i.stack.imgur.com/1yvDu.jpg) Zoomed-out photo (all connections are visible): [![Zoomed out photo](https://i.stack.imgur.com/5Io2u.jpg)](https://i.stack.imgur.com/5Io2u.jpg)
2017/06/23
[ "https://electronics.stackexchange.com/questions/312701", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8139/" ]
it is a saw filter, to remove noise on the gps antenna line 3 gnd pins 1 input 1 output see following for spec <http://www.murata.com/en-eu/products/productdata/8797690593310/DS-SAFEB1G57KE0F00.pdf?1453347007000> Nick
looks something like same package and application as LNA <http://mouser.com/ds/2/302/BGU6104-840139.pdf>
12,542,211
I have an EditText in which the user should input a number including decimals and i want a thousand separator automatically added onto the input number I tried a couple of other methods but some do not allow floating point numbers so i came up with this code which works well only that the string input is not being edited in realtime to one with possible thousand separators and the errors seem to stem from the s.replace(); ``` am2 = new TextWatcher(){ public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) {} public void afterTextChanged(Editable s) { if (s.toString().equals("")) { amount.setText(""); value = 0; }else{ StringBuffer strBuff = new StringBuffer(); char c; for (int i = 0; i < amount2.getText().toString().length() ; i++) { c = amount2.getText().toString().charAt(i); if (Character.isDigit(c)) { strBuff.append(c); } } value = Double.parseDouble(strBuff.toString()); reverse(); NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH); ((DecimalFormat)nf2).applyPattern("###,###.#######"); s.replace(0, s.length(), nf2.format(value)); } } }; ```
2012/09/22
[ "https://Stackoverflow.com/questions/12542211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1552609/" ]
This Class solves the problem, allows decimal input and adds the thousand separators. ``` public class NumberTextWatcher implements TextWatcher { private DecimalFormat df; private DecimalFormat dfnd; private boolean hasFractionalPart; private EditText et; public NumberTextWatcher(EditText et) { df = new DecimalFormat("#,###.##"); df.setDecimalSeparatorAlwaysShown(true); dfnd = new DecimalFormat("#,###"); this.et = et; hasFractionalPart = false; } @SuppressWarnings("unused") private static final String TAG = "NumberTextWatcher"; public void afterTextChanged(Editable s) { et.removeTextChangedListener(this); try { int inilen, endlen; inilen = et.getText().length(); String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), ""); Number n = df.parse(v); int cp = et.getSelectionStart(); if (hasFractionalPart) { et.setText(df.format(n)); } else { et.setText(dfnd.format(n)); } endlen = et.getText().length(); int sel = (cp + (endlen - inilen)); if (sel > 0 && sel <= et.getText().length()) { et.setSelection(sel); } else { // place cursor at the end? et.setSelection(et.getText().length() - 1); } } catch (NumberFormatException nfe) { // do nothing? } catch (ParseException e) { // do nothing? } et.addTextChangedListener(this); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) { hasFractionalPart = true; } else { hasFractionalPart = false; } } } ``` Source: <http://blog.roshka.com/2012/08/android-edittext-with-number-format.html>
I used this way in **Kotlin** for a **Dialog**: ``` val et = dialog.findViewById(R.id.etNumber) as EditText et.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) { et.removeTextChangedListener(this) forChanged(et) et.addTextChangedListener(this) } override fun beforeTextChanged( s: CharSequence, start: Int, count: Int, after: Int ) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } }) ``` then write a method like this: ``` private fun forChanged(alpha: EditText) { val string = alpha.text.toString() val dec = DecimalFormat("#,###") if (!TextUtils.isEmpty(string)) { val textWC = string.replace(",".toRegex(), "") val number = textWC.toDouble() alpha.setText(dec.format(number)) alpha.setSelection(dec.format(number).length) } } ```
4,691,212
I've got my own way of doing this but I'm not convinced its the best, in **C#** Given a `List<DateTime>`, a `DateTime startDate` and an `DateTime endDate`. How would you return a new `List<DateTime>`for every **month** between `startDate` and `endDate` that is **not** included within the original `List<DateTime>` inclusive of the `startDate` and `endDate`. Dates are not guarnteed to be the start of the month, could be any date within the month. `startDate` and `endDate` could span multiple years. The returned list should contain the first day of every month that is missing. Thanks, and I hope it makes sense.
2011/01/14
[ "https://Stackoverflow.com/questions/4691212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192313/" ]
Well, assuming the same month in different years is considered different: ``` private List<DateTime> GetUnincludedMonths(DateTime startDate, DateTime endDate, IEnumerable<DateTime> dates) { var allMonths = new HashSet<Tuple<int, int>>(); //month, year DateTime date = startDate; while (date <= endDate) { allMonths.Add(Tuple.Create(date.Month, date.Year)); date = date.AddMonths(1); } allMonths.Add(Tuple.Create(endDate.Month, endDate.Year)); allMonths.ExceptWith(dates.Select(dt => Tuple.Create(dt.Month, dt.Year))); return allMonths.Select(t => new DateTime(t.Item2, t.Item1, 1)).ToList(); } ```
``` public IList<DateTime> GetMissingMonths(IList<DateTime> currentList, DateTime startDate, DateTime endDate) { // Create a list for the missing months IList<DateTime> missingList = new List<DateTime>(); // Select a startdate DateTime testingDate = startDate; // Begin by the month of startDate and ends with the month of endDate // month of startDate and endDate included while(testingDate <= endDate) { if (currentList.Count(m => m.Month == testingDate.Month && m.Year == testingDate.Year) == 0) { missingList.Add(new DateTime(testingDate.Year, testingDate.Month, 1)); } testingDate = testingDate.AddMonths(1); } return missingList; } ```
11,675,001
My video sites get a very high click rate on video ads. So I'm creating an affiliates program plugin for my php site. To check if my video ads were clicked I need to check for the existence of a cookie. So I have written a php script that basically checks for the existence of a cookie in a loop. I have understood that the user can click on a video ad at any time so I thought using a loop would be a good idea. It turns out that if I have the loop on, the rest of the page wont load until the loop criteria is satisfied. So I imagine having this check done every minute or so but I don't know how to do it.Any way I think I have said enough. Below is the php code the I've written. ``` $cookie1= $_COOKIE['PBCBD2A0PBP3D31B']; $cookie2= $_COOKIE['PBC0622FPBP3D31B']; $cookie3= $_COOKIE['PBC669C9PBP3D31B']; $count= "1"; while ($count >0 ) { if (isset($cookie1) || isset($cookie2) || isset($cookie3)) {$count= "0"; echo "You clicked on an AD";} else{$count= "1";} } ```
2012/07/26
[ "https://Stackoverflow.com/questions/11675001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1544763/" ]
This is a basic issue of PHP vs JavaScript. If you want to check for a cookie every minute using PHP, you'll have to refresh the page every minute. This is obviously very uneconomical for a great variety of reasons, the least of which is that you're checking for something on the client side using server-side code - by compulsory page-refreshing every minute, no less. Based on your description of what you want to do, I suggest [using JavaScript instead to check for cookies](http://sveinbjorn.org/cookiecheck#javascript) (the page in the link shows how to make and check for a test cookie; modify to suit your needs) and running this function using `setInterval()`.
I agree with Matt. You would be better off detecting the cookie only in the instance when a cookie is likely to change (when they click on the video). However, it depends on the exact situation. Are you setting the cookies, or are the cookies being set by an external site when they click the ads? ### EDIT: Your two goals seem to be: 1. Determining what ads to serve based on the cookies attached to the user. 2. Logging which users click on which ads. If you are generating all the ads in PHP and serving them to the user, then before you choose which ads to display, check the user's cookie *once* and go from there. If you are placing the ads in your page with javascript, you should check for the cookies in javascript every time you refresh the ads. In any case, abandon the loops. Simply check for cookies directly before the ads are served up. In oder to determine which users click on which ads, you should detect the clicks in javascript, and log them to your server using an AJAX.
1,565,347
**I got a Wikipedia-Article and I want to fetch the first z lines (or the first x chars, or the first y words, doesn't matter) from the article.** The problem: I can get either the source Wiki-Text (via API) or the parsed HTML (via direct HTTP-Request, eventually on the print-version) but how can I find the first lines displayed? Normaly the source (both html and wikitext) starts with the info-boxes and images and the first real text to display is somewhere down in the code. For example: [Albert Einstein on Wikipedia](http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes) (print Version). Look in the code, the first real-text-line *"Albert Einstein (pronounced /ˈælbərt ˈaɪnstaɪn/; German: [ˈalbɐt ˈaɪ̯nʃtaɪ̯n]; 14 March 1879–18 April 1955) was a theoretical physicist."* is not on the start. The same applies to the [Wiki-Source](http://en.wikipedia.org/w/index.php?title=Albert_Einstein&action=edit), it starts with the same info-box and so on. **So how would you accomplish this task? Programming language is java, but this shouldn't matter.** *A solution which came to my mind was to use an xpath query but this query would be rather complicated to handle all the border-cases. [update]It wasn't that complicated, see my solution below![/update]* Thanks!
2009/10/14
[ "https://Stackoverflow.com/questions/1565347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61855/" ]
You don't need to. The API's `exintro` parameter returns only the first (zeroth) section of the article. **Example:** [api.php?action=query&prop=extracts&exintro&explaintext&titles=Albert%20Einstein](https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&titles=Albert%20Einstein&format=jsonfm) There are other parameters, too: * `exchars` Length of extracts in characters. * `exsentences` Number of sentences to return. * `exintro` Return only zeroth section. * `exsectionformat` What section heading format to use for plaintext extracts: ``` wiki — e.g., == Wikitext == plain — no special decoration raw — this extension's internal representation ``` * `exlimit` Maximum number of extracts to return. Because excerpts generation can be slow, the limit is capped at 20 for intro-only extracts and 1 for whole-page extracts. * `explaintext` Return plain-text extracts. * `excontinue` When more results are available, use this parameter to continue. Source: <https://www.mediawiki.org/wiki/Extension:MobileFrontend#prop.3Dextracts>
You need a parser that can read Wikipedia markup. Try [WikiText](http://wiki.eclipse.org/Mylyn/Incubator/WikiText) or the parsers that come with [XWiki](http://www.xwiki.org/xwiki/bin/view/Main/WebHome). That will allow you to ignore anything you don't want (headlines, tables).
45,679,651
I can't seem to get this script to work. I'm getting the following error: > > Msg 137, Level 16, State 1, Line 14 > Must declare the scalar variable "@TVP\_GLICU". > > > Can anyone tell me what am I missing? ``` Declare @TVP_GLICU TVP_GLICU DECLARE @cmd varchar(500) Declare @TimeStamp as nvarchar(100) = Replace((CONVERT(varchar(25), getdate(), 121)),':','') --Insert Batch numbers in user defined table types Insert Into @TVP_GLICU (ID) Values ('563704') Insert Into @TVP_GLICU (ID) Values ('498721') --select * --From @TVP_GLICU SET @cmd = 'BCP "EXECUTE [F0902].[D365O].[Get-F0911NewRecords]'+@TVP_GLICU+'" QUERYOUT "D:\D365O\DataSource\F0911\'+@TimeStamp+'.csv" -c -t\^, -T -S' + @@SERVERNAME + '' EXECUTE MASTER..xp_cmdshell @cmd ```
2017/08/14
[ "https://Stackoverflow.com/questions/45679651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8327916/" ]
Flexbox: ``` container { display: flex; justify-content: center; } ``` If you want space between the pictures, use: ``` margin-left: ``` or ``` margin-right: ```
**try this** ```css body, html { height: 100%; margin: 0; padding: 0; } .circles-container{ display: table; border-spacing: 40px; } .row { display: flex; } .circle { padding: 40px 30px; border: 1px solid #000; border-radius: 50%; text-align: center; vertical-align: middle; position: relative; } .cell { } .big-circle { padding: 150px; } ``` ```html <div class="circles-container"> <div class="row"> <div class="cell"> <div class="circle"> <span>TEXT</span> </div> </div> <div class="cell"> <div class="circle"> <span>TEXT</span> </div> </div> <div class="cell"> <div class="big-circle circle"> <span>TEXT</span> </div> </div> <div class="cell"> <div class="circle"> <span>TEXT</span> </div> </div> <div class="cell"> <div class="big-circle circle"> <span>TEXT</span> </div> </div> </div> </div> ```
32,193
We have a number of PCs running XP SP2 (and a couple running SP1) already in production, and we're looking to keep the local administrator's password consistent across the OU. The only solutions I can think of would be using pspassword to change all of their passwords, or having a script containing the password run locally on the PCs. Unfortunately, pspasswd won't work on computers that aren't online and a local script containing the password would be insecure. Is there any other viable solution? How can I account for computers that aren't online at the time of the password change?
2009/06/26
[ "https://serverfault.com/questions/32193", "https://serverfault.com", "https://serverfault.com/users/9922/" ]
I'm not sure what you're looking for here since it would be difficult to deploy a local account password change solution that will 'somehow' work for online and offline computer accounts. The process would be if it's an actual script or GP, for them to get the password change at 'some point' when they're online. If you want to deploy this as a one time action on a certain timeframe, you would have to do the offline computers manually. I'm sure you've probably read this, but here are some solutions that were suggested in a previous question related to yours: [**https://serverfault.com/questions/23490/is-there-a-group-policy-that-would-push-a-new-user-name-and-password-to-all-local**](https://serverfault.com/questions/23490/is-there-a-group-policy-that-would-push-a-new-user-name-and-password-to-all-local)
We do this through Group Policy. I don't know the specifics of how the GPO is created, but it is in the section: ``` Computer Configuration / Windows Settings / Security Settings / Local Policies/Security Options / Accounts ``` There are settings to allow disabling of the guest account and renaming of the local admin account. --- EDIT: I misspoke about changing the local password. --- Changing the local admin password is a bit more complicated, at least until Windows Server 2008. This solution works on Server 2003, and is a bit of a kludge as it sends the new password in plain text. If that concerns you, there are other alternatives that encrypt but need additional software. We address the issue by leaving it disabled unless we need to make a change. 1- write a 1 line batch file .. with the command "NET USER Administrator %1" - if you rename the account use the new name. 2- set the batch file to run on logon using the GPO, in the following section ``` Computer Configuration / Windows Settings / Scripts / Startup ``` 3- IN THE GPO entry, press the button to show the files, and copy the batch file into the location opened. Then the batch file (incl .bat) as the script name and the new password as the parameter. ![illustration](https://img23.imageshack.us/img23/6952/image2fkn.png)
32,750,845
I have a code which does something like this: ``` if [ -z "$SOME_VARIABLE" ]; then echo "something something 1" else echo "something something 2" fi ``` I have no clue what "-z" is doing here. Can someone explain please?
2015/09/23
[ "https://Stackoverflow.com/questions/32750845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1148859/" ]
What about ``` cursor.execute("""SELECT pivot_id FROM aud_qty WHERE hshake1 is NULL AND ((strftime('%s', DATETIME('now')) - strftime('%s', sent_to_pivot)) / (60)) > 30; """) ``` ? Using `"""` or `'''` you get the same behaviour as a very long string but you can use newlines just fine. And your database won't mind them either.
how bout ``` from models import AudQty,session update_limit = time.time()-30*60 # 30 minutes ago session.query(AudQty.pivot_id).filter(hshake1=None, sent_to_pivot_lte=update_limit).all() ``` strings can also be multiline without triple quotes, as two quotes strings next to each other automagically concatenate ``` cursor.execute("SELECT pivot_id FROM aud_qty " "WHERE hshake1 is NULL AND " "((strftime('%s', DATETIME('now')) - strftime('%s', sent_to_pivot)) / (60)) > 30;") ```
10,347,678
this is what I'm trying to achieve: ``` config.Name("Foo") .Elements(() => { Element.Name("element1").Height(23); Element.Name("element2").Height(31); }) .Foo(23); ``` or like this: ``` .Elements(e => { e.Name("element1").Height(23); e.Name("element2").Height(31); }) .Foo(3232); ``` this is what I have for the moment: ``` public class Config { private string name; private int foo; private IList<Element> elements = new List<Element>(); public Config Name(string name) { this.name = name; return this; } public Config Foo(int x) { this.foo = x; } ... //add method for adding elements class Element { public string Name { get; set; } public int Height { get; set; } } } ``` anybody knows how to do this ?
2012/04/27
[ "https://Stackoverflow.com/questions/10347678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112100/" ]
Any reason you don't want to use object and collection initializers? ``` public class Config { public string Name { get; set; } public int Foo { get; set; } public IList<Element> Elements { get; private set; } public Config() { Elements = new List<Element>(); } } // I'm assuming an element *always* needs a name and a height class Element { public string Name { get; private set; } public int Height { get; private set; } public Element(string name, int height) { this.Name = name; this.Height = height; } } ``` Then: ``` var config = new Config { Name = "Foo", Elements = { new Element("element1", 23), new Element("element2", 31) }, Foo = 23 }; ``` If you don't want to expose the list of elements directly, you could always turn that into a builder, and copy it into a more private data structure on `Build`: ``` var config = new Config.Builder { Name = "Foo", Elements = { new Element("element1", 23), new Element("element2", 31) }, Foo = 23 }.Build(); ``` This has the additional advantage that you can make `Config` itself immutable. If you always need `Name` to be present, just take that as a constructor parameter instead. While there are times where it's good to have a fluent interface with mutating (or copy-and-change) method calls, in this case I think collection/object initializers are more idiomatic C#. Note that if you're using C# 4 and you want to make your `Element` constructor calls, you can always use named arguments: ``` new Element(name: "element2", height: 31) ```
Here's **method 1** to place inside Config -- "one at a time": ``` public Config Element(Action<Element> a) { Element e = new Element(); a(e); this.elements.Add(e); return this; } ``` And here's how to use it: ``` config.Name("Foo") .Element(e => e.Name("element1").Height(23)) .Element(e => e.Name("element2").Height(31)) .Foo(3232); ``` Here's **method 2** -- "the list": ``` public Config Elements(Func<List<Element>> a) { List<Element> elements = a(); foreach (Element e in elements) { this.elements.Add(e); } return this; } ``` And here's how to use it: ``` config.Name("Foo") .Elements(() => new List<Element>() { new Element().Name("element1").Height(23), new Element().Name("element2").Height(31) }) .Foo(3232); ``` Note that it presumes Element is not nested inside Config (or you'd need `new Config.Element()` in example 2). **Note** that in your "the list" example, you've passed in a single Element object, but you're trying to set it twice. The second line will alter the Element, not create a new one.: ``` .Elements(e => { e.Name("element1").Height(23); // <-- You set it e.Name("element2").Height(31); // <-- You change it }) .Foo(3232); ``` Thus this syntax can't work. **How it works:** `Func<T,U,...>` is an anonymous function delegate that takes in all the parameters but one, and returns the last one. `Action<T,U,...>` is an anonymous function delegate that takes in all parameters. For example: `Func<int,string> f = i => i.ToString();` says "take in an int, return a string". `Action<int> f = i => string c = i.ToString();` says "take in an int, return nothing".
567,130
Einstein’s relativity rejects the notion of a universal ‘now’ moment. It underlines how the concept of ‘now’ is compromised due to time passing at differing rates in differing frames of reference, depending on such things as local gravitation or the acceleration of a body at high speed. Some other reasons I have seen explain why the ‘now’ moment is not consistent for all observers, is due to the differing time it takes for light to travel to each observer. So in effect each observer sees the same event happening at different times. However in my mind these are practical problems that occur when trying to agree and measure a synchronised moment in time. These circumstances of time flowing at varying rates or the time it takes light to travel from an event to different observers, in my view does not stop a theoretical synchronised‘ now’ moment in time. Of course we understand that when we look up at the sky at night we are not looking at the stars as they are now, but as they were many thousands of years ago. As a thought experiment if one could stop time in an instance across the universe, would that not represent a common now moment? A crude analogy would be three water wheels sitting alongside each other. Each wheel is fed by a stream which is running at a different rate. The wheels are turning at different speeds (just as time can flow at differing rates). However when all three wheels are stopped, that is the ‘now’ moment. I understand this is in the same frame of reference, but it is the concept I am interested in. Please can someone explain in a non mathematical way why my perception is wrong.
2020/07/21
[ "https://physics.stackexchange.com/questions/567130", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/105651/" ]
> > It underlines how the notion of ‘now’ is compromised due to time passing at differing rates in differing frames of reference > > > I think your confusion stems mainly from this. The fact is, that logic is reversed to what you are saying. You cannot compare two clocks before you know what it means for two events to be simultaneous. To say that two clocks tick at different rate means you need to start and finish counting the ticks at the same time for both clocks and then you compare the resulting number. So you cannot even compare two clocks before knowing what "now" means. Relativity was born from Einstein's careful analysis of what "now" should mean. The definition he came up with led to the fact, that "now" is different for different observers. From this, STR follows. > > if one could stop time in an instance across the universe, would that not represent a common now moment? > > > You can do this, but this would not represent common now moment. This would be now moment from your viewpoint. From someone else's viewpoint it would not. You can imagine that you send signal with infinite velocity (w.r.t to you) to whole universe which will tell him to stop. But from other viewpoint, this signal would not have infinite velocity, but finite and this observer would see universe stop in different places at different time. For him, this would not represent "now" moment.
This is not really an answer. It’s more of a continuation of your thought experiment. Maybe it will help to think of the question in different ways. Imagine that every particle in the universe had its own personal timer that said “exactly 20 billion years after the big bang, I need to record what I’m doing at that instant. Then when someone asks me what I was doing at that instant, I can tell them.” I’ll refer to this as the “task”. I can see several problems with this task. problem 1: Photons themselves do not experience the flow of time. Photons travel at the speed of light and from their point of view, time does not pass at all while they move from point A to point B. So right off the bat I have to exclude photons from this task. I can’t think of any way to include them. problem 2: Suppose that massive particles could perform this task. This task still makes little sense for individual particles. Maybe it could make slightly more sense for large aggregations of particles. So if I was able to, say, tell all the particles on earth to average their clocks together and use that instead, then maybe that would make more sense. problem 3: Of course, the act of telling all the clocks on earth to average themselves together and synchronize themselves would take about 1/10th of a second to get that message across. Another can of worms. Problem 4: Then you have the problem of a satellite orbiting the earth. Time passes slower on a satellite orbiting earth. 0.01 seconds slower every year. So over the course of 20 billion years, that works out to 6.32 years difference between a clock on earth relative to the space station. Hmm. [https://www.wolframalpha.com/input/?i=20+billion++Years+\*+0.01+seconds+%2F+1+year](https://www.wolframalpha.com/input/?i=20+billion++Years+*+0.01+seconds+%2F+1+year) Problem 5: Once an I record my state at my own 20 billion year mark, then I have to begin the process of going around collecting all that data from everyone else.
54,906,850
I am trying to create a bash script that uses the sed command to replace a pattern by a variable that contains a string or put a space if there is nothing in the variable. I cannot find the good way to write it and make it work. Here is the part where I have issues: ``` a_flag=$(echo $a | wc -w) if [[ $a_flag = 0 ]]; then sed -i -e 's/#b/\\hspace{2cm}/g' source.tex else sed -i -e "s/#b/$a/g" source.tex fi ``` When running this, the condition is always false. I tried [] or (()) for the if statement but I just can't find a way to fix it.
2019/02/27
[ "https://Stackoverflow.com/questions/54906850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11125295/" ]
You only need a single parameter expansion here, to replace the expansion of `$a` with `\hspace{2cm}` if the expansion is empty. ``` sed -i -e "s/#b/${a:-\\\\hspace{2cm}}/g" source.tex ``` You need a stack of `\` because there are two rounds of escaping involved. First, the shell itself reduces each `\\` to a single literal backslash. Then `sed` *also* reduces each pair of `\\` to a single literal backslash.
Counting the number of occurrences of someething seems like a very roundabout way to approach this anyway. ``` case $a in *[A-Za-z0-9_]*) x='\\hspace{2cm}';; *) x=$a;; esac sed -i "s/#b/$x/g" source.tex ```
2,595,013
Theorem - There is a division of $\mathbb{N}$ for $\aleph\_0$ sets so every set has cardinal of $\aleph\_0$. I don't know even where to start in order to prove this theorem.
2018/01/07
[ "https://math.stackexchange.com/questions/2595013", "https://math.stackexchange.com", "https://math.stackexchange.com/users/507015/" ]
For example: Let a natural number $a$ belong to the $n$th set of the partition if $a$ has exactly $n$ prime factors. (And put $0$ and $1$ to any of them, say to the first one.)
Since there are a few different ways here already, here is my personal preference: Put $1$ in the first partition. Put $2$ in the second partition and $3$ in the first partition. Put $4$ in the third partition, $5$ in the second partition and $6$ in the first partition. And so on.
44,187,778
I created a style.css file. To include it in a .html file I tried : ``` <link rel="stylesheet" href="https://github.com/karinakozarova/HealthCalc/blob/master/style.css"> ``` and ``` <base href="/style.css"> ``` and ``` <href="/style.css"> ``` None of them seem to work. Any ideas how to add CSS to my app via external file will be appreciated.
2017/05/25
[ "https://Stackoverflow.com/questions/44187778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946648/" ]
I think you may be missing a "type" attribute within that link. Try the markup below: ``` <link rel="stylesheet" type="text/css" href="https://github.com/karinakozarova/HealthCalc/blob/master/style.css"> ```
The GitHub "blob" urls are webpages showing your file. Not the file itself. So you need to use the "raw" url or something like jsDelivr.
6,651,146
I'd very much like to have some idea of the state of the art of MVC frameworks for **node.js**. Specifically, current commercial practice of the art, not research, with frameworks for front-end web apps. As a PHP programmer might choose Yii Framework—what are the options for node.js programmers and what are the pros and cons for the main contenders?
2011/07/11
[ "https://Stackoverflow.com/questions/6651146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We've been using our MVC framework, [Sails](http://sailsjs.com), in a production environment for several of our clients since March. It's built on Express, Socket.io, and Sequelize. The main distinction is that it routes realtime Socket.io requests the same way as standard HTTP requests: using Express routes. Hope that helps!
I just did a search on twitter for nodejs and mvc - and it pointed to something called matador - <https://github.com/Obvious/matador>. I haven't used it, but would like to see a comparison before I pick one...
42,637
I have a script that pulls a file from an external server, and tries to save it locally (to then be processed). I'm using Varien\_Io\_Ftp() to facilitate this, however, upon saving the file locally, it throws the following exception, despite creating the file that is required which upsets me. ``` Warning: chdir(): Invalid argument (errno 22) in C:\wamp\www\xxxxx\shop\lib\Varien\Io\File.php on line 547 ``` This line in Varien\_Io\_File is the only one in the vacinity that doesn't have error suppression added to it. Is this a bug, or should I be setting \_iwd somewhere within my call? Hopefully some code to explain the call below: ``` $importDir = Mage::getBaseDir() . DS . 'var' . DS . 'import' . DS . 'stock' . DS; $localFile = $importDir . "StockUpdate_" . date("Y-m-d-H-i-s") . ".csv"; $file = new Varien_Io_File(); $file->mkdir($importDir); $pickupFile = new Varien_Io_Ftp(); try { $pickupFile->open( array( 'host' => $host, 'user' => $username, 'password' => $password, 'timeout' => '10' ) ); $pickupFile->cd($remoteDir); $_fileToImportRemoteTmp = $pickupFile->read($remoteFile); $pickupFile->close(); if (!$file->write($localFile, $_fileToImportRemoteTmp)) { die("cannot write local file :/"); } $file->close(); } catch (Exception $e) { var_dump($e); } ``` The exception I being thrown with this line: ``` if (!$file->write($localFile, $_fileToImportRemoteTmp)) { ```
2014/11/05
[ "https://magento.stackexchange.com/questions/42637", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/5408/" ]
For anyone looking at this in the future, RS has provided an example that works, but I wanted to jump in and give a little explanation about WHY his solution works. The exception being thrown at lib\Varien\Io\File.php on line 547 is due to the reference to `$this->_iwd` not being supressed (and inherently, the fact that it isn't set). I'm assuming this *isn't* a bug, despite the fact tht you can clearly call the function directly. I'm guessing that the intention is that you call the `->open()` function prior to making any action upon a file. The `open()` function sets a reference to `_iwd` (if you pass a `path` into it to begin with). i.e. ``` $file->open(array('path' => $importDir)); ``` Grabbing a reference to Varien\_Io\_File, and making a direct call to `cd`, whilst possible, doesn't follow the correct flow, therefore when you `write`, the original reference to `_iwd` isn't in place. It's worth pointing out that you need to call: ``` $file->mkdir($importDir); ``` prior to calling `open()`. Additionally, RS noted that <http://inchoo.net/magento/magento-code-library/> has an example, however, the inital code doesn't mention the limitation above and actually calls `->write()` directly too.
Try ``` $pickupFile = new Varien_Io_Ftp(); $localDir = "/path/to/local/dir"; $remoteFile = "/path/to/remote/dir/text.csv" mkdir($localDir, 0700, true); $localFile = $localDir . '/local.csv' try { $pickupFile->open( array( 'host' => $host, 'user' => $username, 'password' => $password, 'timeout' => '10' ) ); $pickupFile->read($remoteFile, $localFile); } catch (Exception $e) { var_dump($e); } ``` See [Varien\_Io\_Ftp](http://docs.magentocommerce.com/Varien/Varien_Io/Varien_Io_Ftp.html#read) Also for security you way want to use [Varien\_Io\_Sftp](http://docs.magentocommerce.com/Varien/Varien_Io/Varien_Io_Sftp.html)
11,758,696
How to port this code in Objective-C? Anyone please help. ``` return data.length != 0 ? new Byte(data[0]) : null; // In Java ``` I am doing it this way, but this does not show the proper result ``` return datalen!= 0?malloc(sizeof(char) *data[0]) :NULL; //In Objective C it is write java data is byte **In obj C** datalen int datalen = sizeof(data)/sizeof(*data); ``` I am unable to return data value. What is the problem?
2012/08/01
[ "https://Stackoverflow.com/questions/11758696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1425885/" ]
`inline` enables some changes to the *one definition rule*. Specifically, a function (including an explicit specialization of a function template) declared `inline` can be defined in multiple translation units (provided the definitions in different translation units are the same) and *must* be defined in any translation unit where it is *odr-used*. This is the same version of the *odr* rule as applies to function templates (unspecialized). You either have to define your specialization in one translation unit (and declare it before you use it in other translation units), or you can leave the definition in the header file but make it `inline`. A declaration of your specialization would look like this: ``` template<> void f<int>(int p); ```
> > Is there any other way to do this? > > > ``` template <> static void f<int>(int p) { std::cout << "f two" << std::endl; } ``` or have them `inline`, but use special compiler flags (where available) to suppress actual inlining > > What does inline actually do? > > > Best answer(s) are already available :)
25,018,821
I have a C++ plugin for QML that has some properties and I am wondering if there is some documentation regarding what order the functions will be called in the following QML code: ``` MyCustomThing { propertyA: 20 // Will putting this line first guarantee A before B? propertyB: 30 } ``` On my machine things happen in the opposite order I'd expect (in this case B before A, i.e. whatever appears last in the QML is the first thing invoked), but it would be nice to know if this is consistent across platforms - and ideally documented somewhere. Is there any documentation specifying the order of function calls during QML object construction? Thanks!
2014/07/29
[ "https://Stackoverflow.com/questions/25018821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/101645/" ]
You could also load the Flume Configuration file rather than writing it within the Java code.The same configuration could be used while starting your standalone Flume Agent. ``` public static void main(String[] args) { String[] args = new String[] { "agent", "-nAgent", "-fflume.conf" }; Application.main(args); } ``` Where "Agent" is the name of your Flume Agent. "flume.conf" is the configuration file which should be placed in the resources folder of your Java project.
Instead of doing that, try using an embedded agent (a far more elegant and cleaner solution). You create a `Map<String, String>` with the configuration of the Flume agent you wish to run, and then create an agent and configure it. ``` Map<String, String> properties = new HashMap<String, String>(); properties.put("channel.type", "memory"); properties.put("channel.capacity", "200"); properties.put("sinks", "sink1 sink2"); properties.put("sink1.type", "avro"); properties.put("sink2.type", "avro"); properties.put("sink1.hostname", "collector1.apache.org"); properties.put("sink1.port", "5564"); properties.put("sink2.hostname", "collector2.apache.org"); properties.put("sink2.port", "5565"); properties.put("processor.type", "load_balance"); EmbeddedAgent agent = new EmbeddedAgent("myagent"); agent.configure(properties); agent.start(); List<Event> events = Lists.newArrayList(); events.add(event); events.add(event); events.add(event); events.add(event); agent.putAll(events); ... agent.stop(); ``` You can find more information about it [here](http://archive.cloudera.com/cdh4/cdh/4/flume-ng-1.3.0-cdh4.3.0/FlumeDeveloperGuide.html#embedded-agent).
3,638,361
I have a question regarding clearing of the log data in Magento. I have more than 2.3GB of data in Magento 1.4.1, and now I want to optimize the database, because it's too slow due to the size of the data. I checked the log info (URL,Visitors) and it shows more than 1.9 GB. If I directly clear those records, will it affect any functionality in the site? How can I clear the log details? By clearing those data will I have or lose any data on my site?
2010/09/03
[ "https://Stackoverflow.com/questions/3638361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172376/" ]
**Cleaning the Magento Logs using SSH :** login to shell(SSH) panel and go with `root/shell` folder. execute the below command inside the shell folder ``` php -f log.php clean ``` enter this command to view the log data's size > > php -f log.php status > > > This method will help you to clean the log data's very easy way.
After clean the logs using any of the methods described above you can also disable them in your app/etc/local.xml ``` ... <frontend> <events> <frontend> <events> <!-- disable Mage_Log --> <controller_action_predispatch> <observers><log><type>disabled</type></log></observers> </controller_action_predispatch> <controller_action_postdispatch> <observers><log><type>disabled</type></log></observers> </controller_action_postdispatch> <customer_login> <observers> <log> <type>disabled</type> </log> </observers> </customer_login> <customer_logout> <observers> <log> <type>disabled</type> </log> </observers> </customer_logout> <sales_quote_save_after> <observers> <log> <type>disabled</type> </log> </observers> </sales_quote_save_after> <checkout_quote_destroy> <observers> <log> <type>disabled</type> </log> </observers> </checkout_quote_destroy> </events> </frontend> </config> ```
18,316,573
I've written a simple PHP script on shared hosting and wish to implement some rules in the .htaccess file so that every time my script calls, let's say, <http://www.google.com/test1> it will get <http://www.otherwebsite.com/test1> instead. I've used standard URL Rewriting Rules before but didn't need this specific function. Thank you !
2013/08/19
[ "https://Stackoverflow.com/questions/18316573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/927901/" ]
There is no really elegant way to do this in Sybase. Here is one method, though: ``` select mt.MainId, mt.Data, Others = stuff(( max(case when seqnum = 1 then ','+Name+'='+cast(status as varchar(255)) else '' end) + max(case when seqnum = 2 then ','+Name+'='+cast(status as varchar(255)) else '' end) + max(case when seqnum = 3 then ','+Name+'='+cast(status as varchar(255)) else '' end) ), 1, 1, '') from MainTable mt left outer join (select ot.*, row_number() over (partition by MainId order by status desc) as seqnum from OtherTable ot ) ot on mt.MainId = ot.MainId group by mt.MainId, md.Data ``` That is, it enumerates the values in the second table. It then does conditional aggregation to get each value, using the `stuff()` function to handle the extra comma. The above works for the first three values. If you want more, then you need to add more clauses.
Well, here is how I implemented it in Sybase 13.x. This code has the advantage of not being limited to a number of `Name`s. ``` create proc as declare @MainId int, @Name varchar(100), @Status tinyint create table #OtherTable ( MainId int not null, CombStatus varchar(250) not null ) declare OtherCursor cursor for select MainId, Name, Status from Others open OtherCursor fetch OtherCursor into @MainId, @Name, @Status while (@@sqlstatus = 0) begin -- run until there are no more if exists (select 1 from #OtherTable where MainId = @MainId) begin update #OtherTable set CombStatus = CombStatus + ','+@Name+'='+convert(varchar, Status) where MainId = @MainId end else begin insert into #OtherTable (MainId, CombStatus) select MainId = @MainId, CombStatus = @Name+'='+convert(varchar, Status) end fetch OtherCursor into @MainId, @Name, @Status end close OtherCursor select mt.MainId, mt.Data, ot.CombStatus from MainTable mt left join #OtherTable ot on mt.MainId = ot.MainId ``` But it does have the disadvantage of using a cursor and a working table, which can - at least with a lot of data - make the whole process slow.
302,542
We need to get all the instances of objects that implement a given interface - can we do that, and if so how?
2008/11/19
[ "https://Stackoverflow.com/questions/302542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I don't believe there is a way... You would have to either be able to walk the Heap, and examine every object there, or walk the stack of every active thread in the application process space, examining every stack reference variable on every thread... The other way, (I am guessing you can't do) is intercept all Object creation activities (using a container approach) and keep a list of all objects in your application...
If the classes implementing the specified interface are yours then you can implement a list of weak references upon instantiation.
60,384,103
I have a working HTTP POST Request in Angular 7 with HttpClient as below which is returning details of a user profile: ``` const request { firstName: this.firstName, lastName: this.lastName, city: "Dallas" } this.http.post("URL Path", request).subscribe(response => console.log(response); ``` My question is, is it possible to change the value of the payload based on the response body? For example, if the city field is returned blank then change it's value as per below: ``` this.http.post("URL Path", request).subscribe(response => { if (response.toString().includes("Null"){ request.city = "Detroit" //Resubmit POST request } ```
2020/02/24
[ "https://Stackoverflow.com/questions/60384103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10071193/" ]
You can use the `map` method to calculate a value for each item in the `art.fields` array. ```js const art = { 'fields': [ {title:'Title 1'}, {'text': [ {spaces: '1'}, {link: 'This is a link'}, {mouse: 'Yes'} ]}, {title: 'Title 2'}, {title:'Title 3'}, {'text': [ {spaces: '2'}, {link: 'This is a different link'}, {mouse: 'No'} ]}, ]}; var newArray = art.fields.map(function(o){ return 'text' in o ? o.text[0].spaces : ''; }); console.log(newArray); ```
you could do something like this ``` const newArr = art.fields.map(space => { return {...space.text} }); ``` so I'm assuming you want to return a new array containing an object of the text array
30,713,725
I am currently using the following to upload an image into a folder but I am finding that for my specific purpose I need to copy the image as it is uploaded and add it to a folder a little higher up in the directory. Example: The image file gets uploaded to **/folder/folder/images** and this is good. I need it there. However, I also need a copy with the same file with the same filename here: **/folder/images** Here is the PHP I am using to upload the image to begin with. How can I mdify it to also copy and add to the other folder as a new image is uploaded? ``` <?php // A list of permitted file extensions $allowed = array('png', 'jpg', 'gif','zip'); if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){ $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); if(!in_array(strtolower($extension), $allowed)){ echo '{"status":"error"}'; exit; } if(move_uploaded_file($_FILES['file']['tmp_name'], 'images/'.$_FILES['file']['name'])){ $tmp='images/'.$_FILES['file']['name']; echo 'images/'.$_FILES['file']['name']; //echo '{"status":"success"}'; exit; } } echo '{"status":"error"}'; exit; ?> ``` **UPDATE**: Here is the code that got things working for me: ``` <?php // A list of permitted file extensions $allowed = array('png', 'jpg', 'gif','zip'); if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){ $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); if(!in_array(strtolower($extension), $allowed)){ echo '{"status":"error"}'; exit; } if(move_uploaded_file($_FILES['file']['tmp_name'],'images/'.$_FILES['file']['name'])){ $tmp='images/'.$_FILES['file']['name']; $new = '../images/'.$_FILES['file']['name']; //adapt path to your needs; if(copy($tmp,$new)){ echo 'images/'.$_FILES['file']['name']; //echo '{"status":"success"}'; } exit; } } echo '{"status":"error"}'; exit; ?> ```
2015/06/08
[ "https://Stackoverflow.com/questions/30713725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914251/" ]
Based on the comments on your question: ``` if(move_uploaded_file($_FILES['file']['tmp_name'],'images/'.$_FILES['file']['name'])){ $tmp='images/'.$_FILES['file']['name']; $new = 'newFolder/'.$_FILES['file']['name']; //adapt path to your needs; if(copy($tmp,$new)){ echo 'images/'.$_FILES['file']['name']; //echo '{"status":"success"}'; } exit; } ```
Is good idea to use `copy()` function. ``` if(move_uploaded_file($_FILES['file']['tmp_name'], 'images/'.$_FILES['file']['name'])){ $tmp='images/'.$_FILES['file']['name']; echo 'images/'.$_FILES['file']['name']; copy($tmp,'/folder/images/'.$_FILES['file']['name']); //echo '{"status":"success"}'; exit; } ```
14,145,931
I am trying to delete some data from a table variable using a SELECT query. The following code works perfectly: ``` DECLARE @sgID int SET @sgID = 1234 DELETE FROM @tbl_users WHERE (userID NOT IN ( SELECT userID FROM [SGTable] WHERE (sgID = @sgID) )) ``` I'm trying to speed up this query, and read that the following approach may be better. However, when I use the following code - ALL records are deleted from the table variable. ``` DELETE tmp FROM @tbl_Users tmp INNER JOIN [SGTable] sgu ON sgu.userID = tmp.userID WHERE (sgu.sgID <> @sgID) ``` I (obviously incorrectly) assumed that these two queries did the same thing (delete all userIDs in the table variable where the userID is not found in the sub-query). Can anyone please offer some advice on making the second query work, as it is obviously easier to read and maintain?
2013/01/03
[ "https://Stackoverflow.com/questions/14145931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792888/" ]
Is it possible that a userID can be associated with more than one sgID in SGTable? If so, then you're deleting users in your sgID (@sgID) because they are also associated with another sgID. You might prefer: ``` DELETE tmp FROM @tbl_Users tmp LEFT OUTER JOIN [SGTable] sgu ON sgu.userID = tmp.userID AND sgu.sgID = @sgID WHERE sgu.sgID IS NULL ```
Shouldn't that where clause be "=" rather than "<>" ? You want to delete the record that matches, not the ones that don't (which might be all of them), right?
188,607
Over the course of my PhD, I've had the pleasure of being a TA for many courses under many different profs, all were great experiences. I learned a lot, did a lot of good work with the other TAs and helped the students a ton. Currently however, the professor I am a TA for is an absolute menace to deal with, especially over email. He will give me vague instructions on what to do. If I do what I think he wants, he will rudely ask if I ever bothered to read his emails. If I ask him for clarification, he also rudely asks if I bothered to read his emails (even though the emails have nothing to do with my question). If I say nothing, then he tells me I am not responsive and need to communicate more and ask more questions if I'm confused. At one point, I asked him about a problem that students had with an assignment, and he told me not to bother with anything anymore and that he would just do everything himself (implying that my question had annoyed him to the point of giving up on me trying to help him as his TA). He just seems impossible to work with. No matter what I do, he will complain about something. He has a very bad review on RateMyProf, and from what I heard from his former PhD students, he was a nightmare and they were treading on thin ice because they didn't want to lose funding. Fortunately this TA position is only a semester long, and even if he ends up giving me poor feedback, I just want to be able to tell myself I did my best at doing my job, even if he does not think so. So I'd like to ask for general advice on dealing with such people, especially when they're professors.
2022/09/11
[ "https://academia.stackexchange.com/questions/188607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/162547/" ]
Depending on the structure of your department, *this professor is probably not your boss.* You probably report to the Graduate Director in your department, or someone in a similar position. This is worth keeping in mind! Moreover, bullies are usually known to be bullies. All too often, there is usually no way to dismiss them or make them change. If most people in the department are nice, then they probably don't hold your bully in high regard. (*Probably* -- I can't say for certain!) If so, then this means that he might not have a lot of actual power. In addition to the other suggestions, I'd recommend doing two things: * Ask to speak to the graduate director (if you trust him or her). Explain the situation and ask for their advice. You might get some good advice specific to the situation -- and you also cover for yourself if your bully later tries to complain about you. * You say that "I just want to be able to tell myself I did my best at doing my job", which is admirable. From what you say about your professor, I'd say that he is incompetent to recognize or evaluate good teaching. So, although you'll want to minimize any damage there, I'd focus on your students, and remember that it is to them and not to your professor that you are accountable. Do right by them, and you will have done a good job. Good luck!
This professor is a bully and a [redacted], and luckily your interaction with him will be over relatively soon. Your focus should be on getting there with minimal repercussions to yourself and, where possible, others. I recommend you change your perspective on your TA position to get the best out of it nevertheless. * **There is no appeasing people like him.** There is no magic combination of words, email frequency and content that will result in him interacting pleasantly with you (or with anyone else, it seems). Stop seeing him as an ally (and trying to extract something useful from him: blood from a stone, etc.), and start seeing him as what he is: an obstacle to your goal. * **Focus on helping the course students as your goal.** Ideally your professor should be on your side in this, but clearly not. What do your students need? In some cases it's someone to act as buffer/intermediary with the professor, in which case it may be necessary for you to contact him and bear the rude and unhelpful responses; even here, write the queries with your goal in mind, ideally with a very simple answer (e.g. "clarify whether exercise 3 is intended to be solved using technique A or B", not "help me make students understand the applicability of A and B techniques"). But in many other cases, the professor may not really be any help anyway - find the answer on your own, perhaps identifying other authoritative people or peers with the relevant experience, then (if you want) send him an email with your intentions (as per [Ethan Bolker's quite correct answer](https://academia.stackexchange.com/a/188618/155556)) as a CYA. Don't seek your professor's approval but your students' success. * **Learn from the experience.** This is quite different from your other TAing jobs (which is good!) and therefore you are finding your past experiences are not useful here. Observe this person, how he interacts with others (he may be quite different with "underlings" like you and PhD students, compared to "peers") and learn to spot the signs - it will be useful in the future when you meet others like him. There's plenty of [redacted] out there.
18,040
I'm looking for a baby monitor that comes with both a monitor device that I can use to view it and also the option to download a mobile app that can view it via a mobile (over Wifi). I have googled it to death with no luck. It would give me the option to use my phone to see when baby cries as well as a device for convenience to leave downstairs if I don't bring my mobile with me, or for others to use without having to give my phone or wifi password away.
2014/12/21
[ "https://parenting.stackexchange.com/questions/18040", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/11921/" ]
You're looking for a "smart baby monitor". However, asking to have a baby monitor that comes with both a proprietary viewing device **and** and mobile app is probably asking too much from the manufacturers. Developing hardware to view the baby monitors requires the manufacturer to have: * More materials costs * Increased engineering costs for developing the hardware * Software development costs for developing the software * More limiting computing constraints based on need for minimum-spec hardware Developing an application for smartphones is seen as an *alternative* to physical devices. You're already providing/own the hardware (why may be better than the hardware they produced), so they can put their resources into the software development aspect of the viewing app. Since apps are an alternative to, rather than a supplement for, proprietary hardware I'd be impressed if any such products exist. Even if such a product existed, the dedicated viewing device would most likely have less features and feel terribly basic when compared to the app. However, you can get your solution yourself just by looking for a smart baby monitor. Searching Amazon, for instance, with those terms brings up at least 4 monitors with Android/iOS apps in the first 10 hits. Brands listed include: * Withings * iBaby * VideoSecu * WiFi Baby * Medisana Of the models I quickly found, they have a wide variety of features, so make sure you're looking for other features than just being Android/iOS. Some features are: * Pan and tilt * 360 rotation * Night vision * 2-way audio * Video recording * Snapshots * Multiple users (AKA, more than 1 smart device can be used to view the monitor) * App support (how old is the app? Is it being updated regularly?) * Minimum requirements for the app Some smart baby monitors don't come with apps, but have proprietary handheld video monitors and web-based features that make them "smart", so be aware that calling it a *smart* monitor can mean different things. However, this should at least guide you to finding a device. To get your 2nd device that you can leave downstairs, you can simply purchase or acquire another smart device. You can buy a pre-paid carrier phone and *not* use it as a phone at all, and use only the baby monitor app. There's a wide variety of low-cost tablets available these days. You may also already have old smart phones you haven't recycled that can be used. While this may seem like an additional expense, I would argue that it's probably not any more expensive than a product that would have both a dedicated viewer and a mobile app. Economically speaking, it's in no one's best interest for a manufacturer to provide both.
You could use any ip camera(such as a foscam or drop cam) and simply buy a low cost tablet as the monitor device. Any Android or iPad device would do the trick. Amazon kindle fire for example is very low cost and would work with any ip camera. Or you may already have an old iPod touch or tablet that you don't use or could be used for this that would cost you nothing.
68,738,441
I'm quite new to Spring Boot and I'm not sure on which version is preferable to use. In particular, I don't know if it's better to choose a RELEASE version ( that should be more stable, but has a nearer End Of Life ) or one of the last version. For example, which version of Spring Boot Starter Parent is better to use between: - 2.3.12.RELEASE ( End of life : February 2022 ) - 2.5.2 ( End of life: February 2023) Thank's a lot for any response/advice.
2021/08/11
[ "https://Stackoverflow.com/questions/68738441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9188403/" ]
My rule of thumb - if you don't have any limitation (dependencies or such), always take the latest. more features/bugfixes/etc. and the release in the name is meaningless, they are both valid stable versions
I usually use the latest stable version of spring(in this moment is the 2.5.3). The RELEASE part in the name is not used anymore, just be careful to don't use the "SNAPSHOT" version, sometimes those are unstable.
252,341
I was having Ubuntu 10.04 Server running over a software raid 0. Yesterday, I left it running continuously for 10 hours, when I came back, the computer became weird. I cannot shut it down. It was saying "Bus error" or something similar to that. So I force a shutdown by holding power button for 4 seconds. Then I turn it on back. And here come disaster: The raid was broken. System kept dumping out "Failed command: READ DMA EXT". I tried to run fsck.ext4 /dev/md0 from the Alternate CD rescue mode, but fsck.ext4 then said: "Attempt to read block from filesystem resulted in short read". So I use a Hiren CD and run the hard drive scanner and find 12 bad sectors on second hard drive (and at the very end of the drive: more than 80% from the beginning I recall) The told the software to fix the 12 bad sectors but I doubt if Ubuntu understand the fix. I again ran the Alternate CD rescue mode again, and did e2fsck /dev/sda but it was saying device or resource is busy. God and geeks, how come that 12 bad sectors mess up my whole RAID. What should I do to have my RAID and Ubuntu work again? **P/S**: Once I get stuff work back, I'll switch to RAID 5. I swear.
2011/03/27
[ "https://serverfault.com/questions/252341", "https://serverfault.com", "https://serverfault.com/users/33163/" ]
RAID 0 has no redundancy so errors will break the entire array. Are you confusing it with RAID 1 (mirrored)?
Can you tell us how your RAID 0 array was set up? I had the impression that it consists of 2 physical drives: `/dev/sda + /dev/sdb` and the resulting device is /dev/md0. Now you are talking about /dev/md1. Does `/dev/md0 = /dev/sda1 + /dev/sdb1` and `/dev/md1 = /dev/sda2 + /dev/sdb2`? And if so - how you expect to repair the md0 filesystem (which is spread across 2 devices/partitions) when you run it only on one of these devices? This is RAID 0, not 1. > > The funny thing is none of /dev/sda1, > /dev/sda2, /dev/sdb1, /dev/sdb2 is > fsck-able without error. > > > -> is it the same "Superblock invalid" error?
21,811
According to Star Trek (2009) movie, Kirk became captain of USS Enterprise NCC-1701 when he was much younger than he was in TOS. In TOS, it was shown that Christopher Pike was captain of Enterprise 13 years prior to Kirk's 5 year mission. Why was Kirk replaced with Christopher Pike?
2012/08/10
[ "https://scifi.stackexchange.com/questions/21811", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/931/" ]
J. J. Abrams has confirmed 100% that the 2009 film is in an alternate timeline to TOS, so the events for Kirk and Pike can be completely different between the two. > > The notion that when this one character arrived – Nero – that basically **the timeline is altered at that moment. So everything forward is essentially an alternative timeline.** That is not to say that everything that happened in the original series doesn’t exist. ... We are simply saying that **from this moment in the opening scene of the movie, that everything people knew of Star Trek splits off into another timeline.** > > > [Source](http://www.treknews.net/2011/12/23/jj-abrams-talks-star-trek-alternate-timeline-nick-meyer-nerdist/)
They're not in the same continuity. The 2009 film exists in an alternate timeline to TOS.
10,113,380
I'm writing a class constructor with a decimal field, that is need to be initialized by a random value. Just one little field and I need to create new `Random` object. In the first place it looks cumbersome, and in the second there is can arise a lot of equal values, in case of creating a lot of objects in one time slice (`new Random()` is euqal to `new Random(System.currentTimeMillis())`, and equal timeMillis entails equal random values). What is the best way to avoid this?
2012/04/11
[ "https://Stackoverflow.com/questions/10113380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/897090/" ]
You're looking for [Math.random](http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#random%28%29). This is a static method that implicitly initializes a new `Random` object the first time it is called, and then uses that object thereafter. So you get the benefits of sharing a single `Random` object between all the static field initializations, without having to manage a `Random` object yourself.
Are you're using Java 7, `Random` is thread-safe, as documented: > > Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs. > > > So you *can* just use: ``` private static final Random random = new Random(); ``` ... or use [`ThreadLocalRandom`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html) if you're going to be using this from many threads. It's still not going to be as random as [`SecureRandom`](http://docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html) of course. Basically adjust your choice according to your needs.
19,040,151
Simple problem: I have an array A of n entries each one containing one character. I want to create the corresponding string S from this array in an efficient way, i.e. in O(n) time, without using external commands, just bash code and bash builtins. This obvious way... ``` func_slow () { local numel=${#A[*]} for ((i=0; i < numel ; i++)) do S=${S}${A[$i]} done } ``` is not efficient with bash. It's O(n^2) time because the "append" operation S=${S}${A[$i]} doesn't take O(1) time worst case (or even O(1) time amortized which would be enough to guarantee an overall O(n) time). It takes O(#S) each time (clearly it generates the new string S by copying both ${S} and ${A[$i]}). The only way I can find to solve this in O(n) time (without external commands) is by defining this function ``` func_fast () { local numel=${#A[*]} for ((i=0; i < numel ; i++)) do echo -n "${A[$i]}" done } ``` and then using it like this ``` S=`func_fast` ``` This takes O(n) time and it just uses bash code and bash builtins. Implementing (within an interpreter of a language) strings with an efficient append operator (one that would allow func\_slow to run in O(n) time) while still retaining O(1) time direct access of each position of a string is pretty simple from an algorithmic point of view, I was wondering if I'm missing some special efficient bash string operator.
2013/09/26
[ "https://Stackoverflow.com/questions/19040151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2821398/" ]
If you want to do an in-place edit, adding text to the end, you can do this: ``` sed -ie 's/$/WHATEVER/g' FILENAME ``` Or, to add text to the beginning: ``` sed -ie 's/^/WHATEVER/g' FILENAME ``` Special characters will have to be escaped via `\`. A regex cheat sheet is your best friend.
Not sure about the computational complexity, but this works: ``` t=${A[@]} S=${t// /} ```
36,397,537
I need row number 1,2,3,4,5 as new column in below screen shot.. [![enter image description here](https://i.stack.imgur.com/aDqtt.png)](https://i.stack.imgur.com/aDqtt.png) Query: ``` Select ROW_NUMBER() OVER (ORDER BY vgid) AS RowNumber, * from T_EMS_VGDM_RULEMST where VGID in (156, 157, 158, 159, 165) order by CASE WHEN VGID = 165 then 1 WHEN VGID = 158 then 2 WHEN VGID = 159 then 3 WHEN VGID = 157 then 4 WHEN VGID = 156 then 5 END ``` Please suggest
2016/04/04
[ "https://Stackoverflow.com/questions/36397537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1485536/" ]
Isn't it simply: ``` Select ROW_NUMBER() OVER (ORDER BY CASE WHEN VGID = 165 then 1 WHEN VGID = 158 then 2 WHEN VGID = 159 then 3 WHEN VGID = 157 then 4 WHEN VGID = 156 then 5 END) AS RowNumber , * from T_EMS_VGDM_RULEMST where VGID in (156,157,158,159,165) ORDER BY CASE WHEN VGID = 165 then 1 WHEN VGID = 158 then 2 WHEN VGID = 159 then 3 WHEN VGID = 157 then 4 WHEN VGID = 156 then 5 END ```
``` Select ROW_NUMBER() OVER (ORDER BY vgid desc) AS RowNumber, * from T_EMS_VGDM_RULEMST where VGID in (156,157,158,159,165) ORDER BY CASE WHEN VGID = 165 then 1 WHEN VGID = 158 then 2 WHEN VGID = 159 then 3 WHEN VGID = 157 then 4 WHEN VGID = 156 then 5 END ```
4,970,297
The [FactoryBean](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean) can be used to programmatically create objects which might require complex instantiation logic. However, it seems that the beans *created* by the `FactoryBean` doesn't become spring managed. Is this interpretation correct? If so, are there any nice workarounds? A short code sample is included to illustrate my problem. ApplicationContext: ``` <bean id="searcher" class="some.package.SearcherFactory" /> <bean id="service" class="some.package.Service" /> ``` Factory implementation: ``` public class SearcherFactory implements FactoryBean<Searcher> { @Override public Searcher getObject() throws Exception { return new Searcher(); // not so complex after all ;) } @Override public Class<Searcher> getObjectType() { return Searcher.class; } .... } ``` Class created by the factory: ``` public class Searcher() { private Service service; @Autowired public void setService(Service service) { // never invoked this.service=service; } } ```
2011/02/11
[ "https://Stackoverflow.com/questions/4970297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416564/" ]
The object created by the `FactoryBean` *are* managed by Spring, but not instantiated or configured by Spring. By using a `FactoryBean`, you take responsibility for that yourself. All injection and config must be handled by the `FactoryBean` There is an alternative which may work better for you - use [annotation-based config instead of XML-based config](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java). This means you can have complex instantiation logic in Java, whilst still using things like `@Autowired` on the objects themselves. I tend to use annotation-style config for all non-trivial Spring apps now, it makes many things a lot easier.
A manual way would be: 1. Inject the dependencies in the factory bean 2. set them manually on the target object. You can also inject `ApplicationContext` in the factory bean (or get it by implementing `ApplicationContextAware`), and do `ctx.getAutowireCapableBeanFactory().autowireBean(bean)` I admit both feel strange, though. But in fact, if the logic is that simple (only instantiation), use `prototype` scope.
36,750,167
Suppose I have the following function: ``` def sum(summands) s = 0 for a in summands: s = a + s ``` The user might call it with a list `sum([1, 2, 3])` but it would be convenient if you could also call it directly with a number `sum(5)`. (It's not actually about numbers, just a simplified example.) I could invent a function: ``` def make_iterable(x): # returns x if x is iterable, returns [x] if x is not iterable ``` **But is there an even shorter, built-in way to make a single element iterable?**
2016/04/20
[ "https://Stackoverflow.com/questions/36750167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109064/" ]
You can check if it's iterable and make it one (assuming it's not a string). Note: `sum` is the name of a built-in, so you probably shouldn't name your own function the same thing. See [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/). ``` import collections def mysum(summand): if not isinstance(summand, collections.Iterable): summand = (summand,) elif isinstance(summand, str): raise TypeError('string argument not supported') s = 0 for a in summand: s += a return s print(mysum([1, 2, 3])) print(mysum(42)) print(mysum("won't work")) ``` Output: ```none 6 42 Traceback (most recent call last): File "iterate-over-something.py", line 18, in <module> print(mysum("won't work")) File "iterate-over-something.py", line 10, in mysum raise TypeError('string argument not supported') TypeError: string argument not supported ```
You could test if it is a list or an int: ``` if isinstance(summand, list) sumlist(summand) if isinstance(summand, int) Sumint(summand) ``` And then write summing functions for each type. Or you could use a list comp to turn the integer ino a list 'summand = [x for x in range(summand +1)] and use that.
15,091,284
I have the following input: ``` AG23,VU,Blablublablu,8 IE22,VU,FooBlaFooBlaFoo,3 and so on... ``` I want it to "parse" with `scanf()` using some code like this: ``` char sem[5]; char type[5]; char title[80]; int value; while(scanf("%s,%s,%s,%d", sem, type, title, &value) == 4) { //do something with the read line values } ``` But the execution of the code gives me: `illegal instruction` How would you read a comma-separated file like this?
2013/02/26
[ "https://Stackoverflow.com/questions/15091284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291235/" ]
The comma is not considered a whitespace character so the format specifier `"%s"` will consume the `,` and everything else on the line writing beyond the bounds of the array `sem` causing undefined behaviour. To correct this you need to use a scanset: ``` while (scanf("%4[^,],%4[^,],%79[^,],%d", sem, type, title, &value) == 4) ``` where: * `%4[^,]` means read at most four characters or until a comma is encountered. Specifying the width prevents buffer overrun.
The problem that you are having is because when you say ``` scanf("%s,%s,%s,%d", sem, type, title, &value) ``` what happens is that you are trying doing is that you are fitting all the line into the first string which is just 5 characters. Therefore the **`sem[5]` overflows**, and soes all sorts of funny things. To avoid this problem, I tried using the expression `%[^,]`, but it is not quite working. The best bet is to use something like ``` while(scanf("%s%c%s%c%s%c%d", sem, &ch, type, &ch, title, &ch, &value) != EOF) ``` Then you can just discard the `ch`. However bear in mind that is better to use other functions to reading input such as `getchar()`, and things like that, which are much faster and safer in some sense.
90,227
> > **Possible Duplicate:** > > [How to force Windows XP to rename a file with a special character?](https://superuser.com/questions/31587/how-to-force-windows-xp-to-rename-a-file-with-a-special-character) > > > I have a few files whose names have characters such as "?" and ":" that are forbidden by windows. I'm not sure how they managed to get there with these names, since I can't manually create files with these names. They're recovered from an HFS drive, but the tool that recovered them was running under windows and so should have been subject to the same restrictions while creating them, I would think. Anyway... now that they're here, I can open them, but I can't move, copy, rename, or delete them. I want to delete a few of them, but most I want to save and copy to another drive. How might I go about this?
2010/01/01
[ "https://superuser.com/questions/90227", "https://superuser.com", "https://superuser.com/users/22053/" ]
If Idigas' suggestion does not work, you could always move them with a Linux LiveCD such as [Ubuntu](http://ubuntu.com). It allows question marks and colons in filenames so it should have no problem handling the files. You just need to mount your drive first. If XP is your only operating system installed on the disk, it can probably be mounted from `/dev/sda1` or `/dev/hda1` depending on if it's a SCSI drive or IDE drive. to mount a SCSI drive (if running NTFS): ``` mount -t ntfs-3g /dev/sda1 /mnt ``` to mount an IDE drive (running NTFS): ``` mount -t ntfs-3f /dev/hda1 /mnt ``` If it's a FAT32 volume, you can use vfat as the type (`-t vfat`)
For some reason, I usually have more luck when moving/copying/renaming/(anything really) files from the command line, than when doing it windows explorer.
47,257,172
Is the following the recommended way to attempt finding Max with streams? ``` List<Employee> emps = new ArrayList<>(); emps.add(new Employee("Roy1",32)); emps.add(new Employee("Roy2",12)); emps.add(new Employee("Roy3",22)); emps.add(new Employee("Roy4",42)); emps.add(new Employee("Roy5",52)); Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b)); System.out.println("Max " + maxSal); ``` It results in a compilation error - what does this mean? ``` error: incompatible types: OptionalInt cannot be nverted to Integer Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()). uce((a,b)->Math.max(a, b)); ```
2017/11/13
[ "https://Stackoverflow.com/questions/47257172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483620/" ]
You can use the method `Integer.min` in reduce which returns `OptionalInt`, can be used to get `Int` (make sure the boundary checks) using `IntStream` ``` int max1 = emps.stream().mapToInt(Employee::getSalary).max().getAsInt(); ``` using `IntSummaryStatistics` [if you are interested in statistics, like min, max, avg] ``` IntSummaryStatistics stats = emps.stream().mapToInt(Employee::getSalary).summaryStatistics(); int max2 = stats.getMax(); ``` `reduce` function ``` int max3 = emps.stream().mapToInt(Employee::getSalary).reduce(Integer::min).getAsInt(); ```
First, you *might* shorten your `emps` initialization with`Arrays.asList(T...)` like ``` List<Employee> emps = Arrays.asList(new Employee("Roy1", 32), new Employee("Roy2", 12), new Employee("Roy3", 22), new Employee("Roy4", 42), new Employee("Roy5", 52)); ``` Next, you can use [`OptionalInt.orElseThrow(Supplier<X>)`](https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html#orElseThrow-java.util.function.Supplier-) which will get the `max` value from the `List` **or** throw a `RuntimeException` ``` int maxSal = emps.stream().mapToInt(Employee::getSalary).max() .orElseThrow(() -> new RuntimeException("No Such Element")); System.out.println("Max " + maxSal); ``` Finally, you *could* also reason that no one would accept a negative salary, and use [`orElse(int)`](https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html#orElse-int-) like ``` int maxSal = emps.stream().mapToInt(Employee::getSalary).max().orElse(-1); System.out.println("Max " + maxSal); ```
118,421
I tried to illustrate a landscape, and I am very unsatisfied as it is [![My current try](https://i.stack.imgur.com/0auf2.png)](https://i.stack.imgur.com/0auf2.png) I think it lacks depth, I think the lighting is weak and and I just... I don't know. I don't what it all lacks, but I am just not satisfied. What can I do to improve this? What are the basics of illustrating a nice landscape? Also, might sound annoying but could you guys not use terms that are too high caliber? I am just a hobbyist, not a professional.
2018/12/23
[ "https://graphicdesign.stackexchange.com/questions/118421", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/131019/" ]
**Changes:** First thing that comes to my mind; it **isn't** landscape *orientation*. I would definitely start with making it landscape proportions. [![Landscape orientation](https://i.stack.imgur.com/BhIUt.png "Landscape proportion, like a postcard")](https://i.stack.imgur.com/BhIUt.png "Landscape proportion, like a postcard") Add some more color to the trees. [![Tree with more colors](https://i.stack.imgur.com/0Krgb.png "Tree with more colors")](https://i.stack.imgur.com/0Krgb.png "Tree with more colors") The snowflakes should be more spread out (like real snowflakes) and they should vary in size and shape significantly, don't just use circles. [![Snowflakes with variations](https://i.stack.imgur.com/4I165.png "Variable snowflakes")](https://i.stack.imgur.com/4I165.png "Variable snowflakes") The moon looks a bit like a sun (because it's yellow and lacks texture). To make it clearer that it's the moon, add some "[craters](https://i.stack.imgur.com/c659F.jpg "Actual image of moon")" to the moon. [![Moon with craters](https://i.stack.imgur.com/i2qwd.png "Moon with craters")](https://i.stack.imgur.com/i2qwd.png "Moon with craters") Consider changing the color to a bit less yellow - unless you want a [supermoon](https://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Supermoon_over_Germany%2C_2011.jpg/800px-Supermoon_over_Germany%2C_2011.jpg "Supermoon image"). In that case, you can probably make it a bit more orange. Add more **trees**, **snowflakes** and **stars** which should get smaller as they move "further" from wherever the illustration is staged from. [![More trees and snowflakes with distance](https://i.stack.imgur.com/eVu0C.png)](https://i.stack.imgur.com/eVu0C.png) The image has a roundish feel to it, but the trees are very pointy. *Round 'em up* [![Rounded Trees](https://i.stack.imgur.com/hwpp6.png "Tree with rounded points")](https://i.stack.imgur.com/hwpp6.png "Tree with rounded points") --- **Other:** * I think you should remove the clouds, they are unnecessary. * You can add in shadows behind the mountains if you'd like. * If you're making this in Illustrator, make the shapes which you will be duplicating a lot into symbols (snowflakes and stars and maybe even the trees - if you are going to place a great amount). Now just duplicate the symbols as many times as you want, this will save faster and use a *significantly* smaller file size. --- I made my own version following most of my input mentioned above, here's my result: [[GIF](https://i.stack.imgur.com/FFboh.gif)] [![Final result](https://i.stack.imgur.com/uruHs.png "My final recreation")](https://i.stack.imgur.com/uruHs.png "My final recreation") **Notes:** * I did a ratio of **3:2** to look like a postcard. * I made the mountains more like triangles to match the trees and to fit better in the landscape orientation. * I also made some of the trees snow covered, which I think adds a nice touch. [![Snow covered tree](https://i.stack.imgur.com/5Cv9r.png "Snow covered tree tops")](https://i.stack.imgur.com/5Cv9r.png "Snow covered tree tops") * My final `.ai` file size is less than 1 mb because I used symbols.
First of all, I will try to maintain the original image's look. Composition ----------- Explore some basics of composition. In photography, a basic one is the rule of thirds. This means that if you divide your frame in a 3x3 grid, some elements should be in those lines. Look how none of your elements follow this composition rule. [![enter image description here](https://i.stack.imgur.com/LoH0M.jpg)](https://i.stack.imgur.com/LoH0M.jpg) If you place some elements on these lines, the image starts to look more interesting. It is regardless of any additional detail, maintaining the same style. [![enter image description here](https://i.stack.imgur.com/RP6yN.jpg)](https://i.stack.imgur.com/RP6yN.jpg) Planes ------ You probably want your image as it is, but to add more interest you can put elements of different sizes, making them appear as different planes, front, medium, back plane. [![enter image description here](https://i.stack.imgur.com/AUEPg.jpg)](https://i.stack.imgur.com/AUEPg.jpg) Point of interest ----------------- Add something to draw attention into. Something simple is ok, but to add context to your scene. [![enter image description here](https://i.stack.imgur.com/Hs7hu.jpg)](https://i.stack.imgur.com/Hs7hu.jpg) --- Besides that, you can try different styles, but that is another topic. Add gradients, textures or more detail to the images. @Welz answer comments these points, but the truth is that those are changes in the style you have. The composition is the first thing you want to work with. Leave the details for later.
47,232,954
Can anyone provide some code examples that act differently when compiled with `-fwrapv` vs without? The [gcc documentation](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html) says that `-fwrapv` *instructs the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation*. But whenever I try overflowing the result is the same with or without `-fwrapv`.
2017/11/11
[ "https://Stackoverflow.com/questions/47232954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8922300/" ]
Think of this function: ``` int f(int i) { return i+1 > i; } ``` Mathematically speaking, `i+1` should always be greater than `i` for any integer `i`. However, for a 32-bit `int`, there is one value of `i` that makes that statement false, which is `2147483647` (i.e. `0x7FFFFFFF`, i.e. `INT_MAX`). Adding one to that number will cause an overflow and the new value, according to the 2's compliment representation, will **wrap-around** and become `-2147483648`. Hence, `i+1>i` becomes `-2147483648>2147483647` which is false. When you compile **without `-fwrapv`**, the compiler will assume that the overflow is 'non-wrapping' and it will **optimize that function to always return `1`** (ignoring the overflow case). When you compile **with `-fwrapv`**, the function will **not be optimized**, and it will have the logic of adding 1 and comparing the two values, because now the overflow is 'wrapping' (i.e. the overflown number will wrap according to the 2's compliment representation). The difference can be easily seen in the [generated assembly](https://godbolt.org/z/XWMrOR) - in the right pane, without `-fwrapv`, function always returns `1` (`true`).
-fwrapv tells the compiler that overflow of signed integer arithmetic must be treated as well-defined behavior, even though it is undefined in the C standard. Nearly all CPU architectures in widespread use today use the "2's complement" representation of signed integers and use the same processor instructions for signed and unsigned addition, subtraction and non-widening multiplication of signed and unsigned values. So at a CPU architecture level both signed and unsigned arthimetic wrap around modulo 2n. The C standard says that overflow of signed integer arithmetic is undefined behavior. Undefined behavior means that "anything can happen". Anything includes "what you expected to happen", but it also includes "the rest of your program will behave in ways that are not self-consistent". In particular, when undefined behavior is invoked on modern compilers, the optimiser's assumptions about the value in a variable can become out of step with the value actually stored in that variable. Therefore if you allow signed arithmetic overflow to happen in your programs and do not use the fwrapv option, things are likely to look ok at first, your simple test programs will produce the results you expect. But then things can go horribly wrong. In particular checks on whether the value of a variable is nonnegative can be optimised away because the compiler assumes that the variable must be positive, when in fact it is negative.
760,204
I was able to go to the ubuntu software center before and remove it and now it doesn't show up since the switch to the gnome software store. Trying the terminal method of removing the shopping lens doesn't work in this release. [![enter image description here](https://i.stack.imgur.com/m5RKG.png)](https://i.stack.imgur.com/m5RKG.png)
2016/04/21
[ "https://askubuntu.com/questions/760204", "https://askubuntu.com", "https://askubuntu.com/users/234461/" ]
You just click on the app then drag it into the trash (it work for me).
[How can I remove Unity web apps?](https://askubuntu.com/questions/214755/how-can-i-remove-unity-web-apps) -> Try: ``` sudo apt-get remove unity-webapps-amazon* ``` Can't say it's the solution, because first thing I did, was search "amazon" files and manualy deleted "/usr/share/unity-webapps/userscripts/unity-webapps-amazon/" *(no this it didn't remove Amazon)* and now the apt-get wont find the Amazon.
70,595,087
How SWT browser works internally? does it call native browser or it uses OS libraries? Kindly explain internal working of swt browsers or share some free documentations
2022/01/05
[ "https://Stackoverflow.com/questions/70595087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14501769/" ]
According to the [Eclipse Foundation](https://www.eclipse.org/articles/Article-SWT-browser-widget/browser.html) - "The Browser widget binds to a suitable native HTML rendering engine for the platform it is running on (Internet Explorer on Windows, Mozilla on Linux, Safari on the Mac"
The open source SWT browser Equo Chromium (<https://github.com/equoplatform/chromium-swt>) does not rely on native browsers (Internet Explorer on Windows, WebKit on macOS, and WebKitGTK+ or Mozilla/XULRunner on Linux). Instead, it binds to Chromium. Then you will have the same rendering experience across all platforms and you won't have to install any external libraries.
70,621,381
I want to make a GUI Windows application that can run console applications. When this happens, the console window should not be shown. Instead its content should be shown in a visual component (memo/richedit). This component should show exactly the same content which would appear in the console window, even the color of the text and its background should be displayed. So this visual component should work exactly as a console window. I know that the standard output can be captured but many console applications do not use it. Is it possible to capture the output of a console application this way? Are there Windows API calls that can handle this? I use Delphi XE2 but C# code would also be helpful.
2022/01/07
[ "https://Stackoverflow.com/questions/70621381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17862719/" ]
You wrote `$table->string('status')->default("Pending");` and ind your const vars you write it lowercase. that would be the problem. Please check if you also consider lower and uppercase when setting the status. ``` class Constants{ const APPROVED = "approved"; const PENDING = "pending"; const REJECTED = "rejected"; ```
Laravel have the authorization already figured out for you, what you need to do is create a [middleware](https://laravel.com/docs/8.x/middleware) file named (eg. Status) ``` public function handle($request, Closure $next) { if ($request->user()->status !== 'APPROVED') { return back()->with('error_message', 'not approved'); // do something if the user is not approved } return $next($request); // else just continue } ``` in your route now add the middleware ``` Route::post('/post', [PostController::class, 'post'])->middleware(['approved']); ```
9,952,505
I am new to iOS development and am trying to figure out how it is MVC. I see how there are controllers that produce views. However, where are the models that represent data? I just see iOS development as controllers that "delegate" (I still don't see what that çlearly means.) functionality to each other.
2012/03/31
[ "https://Stackoverflow.com/questions/9952505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1279646/" ]
iOS development done the right way is a great example of true MVC programming. If you really want to see this in action, check out Stanford's iTunes U videos. The model for iOS will be either a CoreData store, a manually built class, etc. The ViewController is the controller and the View will be the nib or storyboard scene that contains the UI elements and is wired up to the VC.
In simply words you create views and code separately. Then you link them between themselves using class name, variables and methods. Likewise for program data. But it is too basic question. You can learn it from the first pages of all the books about objective-c
35,667,209
My table id is "termTable". I am iterating through each row of the table. The id of textbox is "label'+ i +'" since I used for loop to generate ids randomly. The values of i will be unordered maybe after adding the rows or deleting the rows. Example: IDs are label1, label2, label3. After deleting the 2nd row, I am adding another row. So now the IDs are label1,label3, label4. I want to retrieve all the ids of all the textbox elements. How can I achieve it? Please help. ``` for (var i = 0; i < firstTabLength; i++) { var row = $("#termTable tr").eq(i); var id = row.find('input[type="text"]').attr('id'); // I could see id = undefined } ``` This is Html. This is for adding the new rows to table. Guess you can visualize the table structure with the help of below code. ``` function AddCustomTerm1() { len = len + 1; var table = document.getElementById("termTable"); var rowCount = table.rows.length; var row = table.insertRow(rowCount); row.insertCell(0).innerHTML = '<input type="text" class="form-control" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>'; row.insertCell(1).innerHTML = '<select class="form-control" id="dataTypes' + (len - 1) + '" name="dataTypes' + (len - 1) + '" onchange="changeDataType(this)"></select>' row.insertCell(2).innerHTML = '<input type="text" class="form-control" id="ContractTerm' + (len - 1) + '" name="ContractTerm' + (len - 1) + '" value="">'; var DD = document.getElementById("dataTypes" + (len - 1)); for (var i = 0; i < datatypesarray.length; i++) { var opt = document.createElement("option"); opt.text = datatypesarray[i]; opt.value = datatypesarray[i]; DD.appendChild(opt); } ```
2016/02/27
[ "https://Stackoverflow.com/questions/35667209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5389766/" ]
without you html format cant help much. but try this ones.you dont even need a for loop to get all the textbox and their ids from table. ``` var ids=[]; $('#termTable input[type="text"]').each(function(){ ids.push($(this).attr('id')) }) ``` if you want ids of the textboxes in first column of the table.the try this ``` var ids=[]; $('#termTable tr').each(function(){ ids.push($(this).find('td:first-child input[type="text"]').attr('id')) }) ```
The best practice is to add a specific class to all of your elements that need to be iterated. For example add the class `term-table-input` to your inputs: ``` row.insertCell(0).innerHTML = '<input type="text" class="form-control term-table-input" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>'; ``` And iterate them with: ``` var termTableInputIDs = []; $('.term-table-input').each(function () { termTableInputIDs.push($(this).attr('id')); }); ``` Also you could read more about writing efficient css here: <https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS>
2,421,086
Can someone give me a solution to this problem, I'm lost. $\lim \limits\_{n \to \infty}$ $ (\frac {(n!) ^{(1/n)} } {n}) $
2017/09/08
[ "https://math.stackexchange.com/questions/2421086", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401136/" ]
**Hint**: Use the theorem that *if $a\_{n} >0$ and $a\_{n+1}/a\_{n}\to L$ then $a\_{n} ^{1/n}\to L$*. Take $a\_n=n! /n^{n} $. You should easily get the answer as $1/e$.
In the same spirit as in answers and comments, consider $$A\_n=\frac{(n!)^{\frac{1}{n}}}{n}\implies \log(A\_n)=\frac{\log (n!)}{n}-\log (n)$$ and use Stirling formula for large $n$ $$\log(n!)=n (\log (n)-1)+\frac{1}{2} \left(\log (2 \pi )+\log \left({n}\right)\right)+O\left(\frac{1}{n}\right)$$ which makes $$\log(A\_n)=-1+\frac{\log (2 \pi )+\log \left({n}\right)}{2 n}+O\left(\frac{1}{n^2}\right)$$ which shows the limit and how it is approached. In fact, even for small values of $n$, this approximation leads to quite accurate values $$\left( \begin{array}{ccc} n & \text{approximation} & \text{exact} \\ 1 & 0.922137 & 1.000000 \\ 2 & 0.692641 & 0.707107 \\ 3 & 0.600144 & 0.605707 \\ 4 & 0.550472 & 0.553341 \\ 5 & 0.519303 & 0.521034 \\ 6 & 0.497813 & 0.498966 \\ 7 & 0.482039 & 0.482859 \\ 8 & 0.469932 & 0.470544 \\ 9 & 0.460323 & 0.460796 \\ 10 & 0.452496 & 0.452873 \end{array} \right)$$
254,216
My table structure looks like this: ``` tbl.users tbl.issues +--------+-----------+ +---------+------------+-----------+ | userid | real_name | | issueid | assignedid | creatorid | +--------+-----------+ +---------+------------+-----------+ | 1 | test_1 | | 1 | 1 | 1 | | 2 | test_2 | | 2 | 1 | 2 | +--------+-----------+ +---------+------------+-----------+ ``` Basically I want to write a query that will end in a results table looking like this: ``` (results table) +---------+------------+---------------+-----------+--------------+ | issueid | assignedid | assigned_name | creatorid | creator_name | +---------+------------+---------------+-----------+--------------+ | 1 | 1 | test_1 | 1 | test_1 | | 2 | 1 | test_1 | 2 | test_2 | +---------+------------+---------------+-----------+--------------+ ``` My SQL looks like this at the moment: ``` SELECT `issues`.`issueid`, `issues`.`creatorid`, `issues`.`assignedid`, `users`.`real_name` FROM `issues` JOIN `users` ON ( `users`.`userid` = `issues`.`creatorid` ) OR (`users`.`userid` = `issues`.`assignedid`) ORDER BY `issueid` ASC LIMIT 0 , 30 ``` This returns something like this: ``` (results table) +---------+------------+-----------+-----------+ | issueid | assignedid | creatorid | real_name | +---------+------------+-----------+-----------+ | 1 | 1 | 1 | test_1 | | 2 | 1 | 2 | test_1 | | 2 | 1 | 2 | test_2 | +---------+------------+-----------+-----------+ ``` Can anyone help me get to the desired results table?
2008/10/31
[ "https://Stackoverflow.com/questions/254216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
``` SELECT IssueID, AssignedID, CreatorID, AssignedUser.real_name AS AssignedName, CreatorUser.real_name AS CreatorName FROM Issues LEFT JOIN Users AS AssignedUser ON Issues.AssignedID = AssignedUser.UserID LEFT JOIN Users AS CreatorUser ON Issues.CreatorID = CreatorUser.UserID ORDER BY `issueid` ASC LIMIT 0, 30 ```
Does this work? SELECT i.issueid, i.assignedid, u1.real\_name as assigned\_name, i.creatorid, u2.real\_name as creator\_name FROM users u1 INNER JOIN issues i ON u1.userid = i.assignedid INNER JOIN users u2 ON u2.userid = i.creatorid ORDER BY i.issueid
44,807,980
I'm making an application with swift 3.0. But I have a problem, because in the API REST still have not implemented the service, I'm creating a simulated JSON to continue working. But the problem as you will see at the end of all the explanation in the image is that I do not know how to declare a JSON "-.- .... Basically the program will make a call to the server and it will respond with a JSON (now I pass it "the simulated" you will see it in the code). And with that JSON maps it with ObjectMapper to some models (that I pass the code) so that in the end the application has an object. [Error declaring Simulated JSON](https://i.stack.imgur.com/Qq09f.png) These are the three models I have to map the JSON when it will come from the server or in this case, the simulated JSON. The first is "LegendEntriesModel": ``` import Foundation import ObjectMapper import AlamofireDomain class LegendEntriesModel: Mappable { fileprivate var _id_snapshot: String? fileprivate var _date: String? fileprivate var _deliverables: [DeliverablesModel]? init(){} required init?(map: Map) { } func mapping(map: Map) { self.id_snapshot <- map["id_snapshot"] self.date <- map["date"] self.deliverables <- map["deliverables"] } var id_snapshot: String { get { if _id_snapshot == "" { _id_snapshot = "" } return _id_snapshot! } set { _id_snapshot = newValue } } var date: String { get { if _date == "" { _date = "" } return _date! } set { _date = newValue } } var deliverables: [DeliverablesModel] { get { if _deliverables == nil { _deliverables = [] } return _deliverables! } set { _deliverables = newValue } } //MARK: RELEASE MEMORY BETWEEN OBJECT AND API REST (BROKE DEPENDENCIS) func copy()->LegendEntriesModel { let legendEntriesModel = LegendEntriesModel() legendEntriesModel.id_snapshot = self.id_snapshot legendEntriesModel.date = self.date legendEntriesModel.deliverables = copyDeliverables() return legendEntriesModel } func copyDeliverables() -> [DeliverablesModel]{ var newArray: [DeliverablesModel] = [] for item in deliverables { newArray.append(item.copy()) } return newArray } } ``` The second on is "DeliverablesModel" ``` import Foundation import ObjectMapper import AlamofireDomain class DeliverablesModel: Mappable { fileprivate var _id: String? fileprivate var _type: String? fileprivate var _url_layer: String? fileprivate var _options: OptionsDeliverablesModel? init(){} required init?(map: Map) { } func mapping(map: Map) { self.id <- map["id"] self.type <- map["type"] self.url_layer <- map["url_layer"] self.options <- map["options"] } var id: String { get { if _id == "" { _id = "" } return _id! } set { _id = newValue } } var type: String { get { if _type == "" { _type = "" } return _type! } set { _type = newValue } } var url_layer: String { get { if _url_layer == "" { _url_layer = "" } return _url_layer! } set { _url_layer = newValue } } var options: OptionsDeliverablesModel { get { if _options == nil { _options = OptionsDeliverablesModel() } return _options! } set { _options = newValue } } //MARK: RELEASE MEMORY BETWEEN OBJECT AND API REST (BROKE DEPENDENCIS) func copy()->DeliverablesModel { let deliverablesModel = DeliverablesModel() deliverablesModel.id = self.id deliverablesModel.type = self.type deliverablesModel.url_layer = self.url_layer deliverablesModel.options = self.options return deliverablesModel } } ``` And the last one is "OptionsDeliverablesModel": ``` import Foundation import ObjectMapper import AlamofireDomain class OptionsDeliverablesModel: Mappable { fileprivate var _type: String? fileprivate var _max_range: Float? fileprivate var _min_range: Float? fileprivate var _title: String? fileprivate var _initial_max_value: Float? fileprivate var _initial_min_value: Float? fileprivate var _id: String? init(){} required init?(map: Map) { } func mapping(map: Map) { self.type <- map["type"] self.max_range <- map["max_range"] self.min_range <- map["min_range"] self.title <- map["title"] self.initial_max_value <- map["initial_max_value"] self.initial_min_value <- map["initial_min_value"] self.id <- map["id"] } var type: String { get { if _type == "" { _type = "" } return _type! } set { _type = newValue } } var max_range: Float { get { if _max_range == 0 { _max_range = 0 } return _max_range! } set { _max_range = newValue } } var min_range: Float { get { if _min_range == 0 { _min_range = 0 } return _min_range! } set { _min_range = newValue } } var title: String { get { if _title == "" { _title = "" } return _title! } set { _title = newValue } } var initial_max_value: Float { get { if _initial_max_value == 0 { _initial_max_value = 0 } return _initial_max_value! } set { _initial_max_value = newValue } } var initial_min_value: Float { get { if _initial_min_value == 0 { _initial_min_value = 0 } return _initial_min_value! } set { _initial_min_value = newValue } } var id: String { get { if _id == "" { _id = "" } return _id! } set { _id = newValue } } //MARK: RELEASE MEMORY BETWEEN OBJECT AND API REST (BROKE DEPENDENCIS) func copy()->OptionsDeliverablesModel { let optionsDeliverablesModel = OptionsDeliverablesModel() optionsDeliverablesModel.type = self.type optionsDeliverablesModel.max_range = self.max_range optionsDeliverablesModel.min_range = self.min_range optionsDeliverablesModel.title = self.title optionsDeliverablesModel.initial_max_value = self.initial_max_value optionsDeliverablesModel.initial_min_value = self.initial_min_value optionsDeliverablesModel.id = self.id return optionsDeliverablesModel } } ``` With these three "Models" are what I can map the JSON inside the class DAO, but here is the problem, because I do not know how to pass my JSON that I have simulated. The code is as follows: ``` import AlamofireDomain import Alamofire import ObjectMapper class DeliverablesLegendDAO : SimpleDAO { var deliverables = Dictionary<String, Any>() deliverables = [{"legendEntries": [{"id_snapshot": "123","date": "2016-10-20","deliveries": [{"id": "12","type": "RGB","url_layer":"topp:states","options": [{"type": "range","max_range": 100,"min_range": 0,"title": "Option RGB","initial_max_value": 100,"initial_min_value": 0,"id": "depth"}]}]}]}] func snapshots(_ parameters: String, callbackFuncionOK: @escaping (LegendEntriesModel)->(), callbackFunctionERROR: @escaping (Int,NSError)->()) { Alamofire.request(parameters, method: .post, encoding: JSONEncoding.default) .responseJSON { response in if response.result.isSuccess{ if let status = response.response?.statusCode { switch(status){ case 200: let value = response let legendEntries = Mapper<LegendEntriesModel>().map(JSONObject: value) callbackFuncionOK(legendEntries!) default: break } } } else { var statusCode = -1 if let _response = response.response { statusCode = _response.statusCode } var nsError: NSError = NSError(domain: Constants.UNKNOWN_HTTP_ERROR_MSG, code: Constants.UNKNOWN_HTTP_ERROR_ID, userInfo: nil) if let _error = response.result.error { nsError = _error as NSError } callbackFunctionERROR(statusCode,nsError) } } } } ``` As you can see in the image, I am declaring my simulated JSON wrong and then map it with "LegendDeliveriesModel" to an object. How can I do it? [Error declaring simulated JSON](https://i.stack.imgur.com/2l1un.png) If you need anything else, tell me. I repeat, the problem is in the JSON simulated statement that I do not know how to pass it to DAO and that it maps it.
2017/06/28
[ "https://Stackoverflow.com/questions/44807980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7672866/" ]
Hi not sure if you will be open to this, but it will be better to try creating a JSON in file and load it in using Bundle like this : ``` func loadJsonFrom(fileName: String) -> NSDictionary { let path = Bundle.main.path(forResource: filename, ofType: "json") let jsonData = try! Data(contentsOf: URL(fileURLWithPath: path!)) let jsonResult: NSDictionary = try! JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! NSDictionary return jsonResult } ```
I think your syntax is wrong for declaring your JSON. Pretty sure declaring Dictionaries inline in swift you only use ["key":"value"] So just remove all of the { and } Edit: Sorry, didn't realise it was outside of a method. If you want to do that you have to declare it directly like so ``` var deliverables = ["legendEntries": ["id_snapshot": "123","date": "2016-10-20","deliveries": ["id": "12","type": "RGB","url_layer":"topp:states","options": ["type": "range","max_range": 100,"min_range": 0,"title": "Option RGB","initial_max_value": 100,"initial_min_value": 0,"id": "depth"]]]] ``` If you're just using it as mock Data I would also consider making it a let constant rather than a variable
59,237,418
How to position both buttons below at the end of their respective columns ? [![buttons](https://i.stack.imgur.com/otyjy.png)](https://i.stack.imgur.com/otyjy.png) By default, the buttons are positioned to **start** in each column. ``` <div id="app"> <v-app id="inspire"> <v-container fluid> <v-row justify="center" style="border: 1px solid;"> <v-col cols="12" sm="4" style="border: 1px solid red;" > <v-btn>Ok</v-btn> </v-col> <v-col cols="12" sm="4" style="border: 1px solid blue;" > <v-btn>Cencel</v-btn> </v-col> </v-row> </v-container> </v-app> </div> ``` [Codepen.](https://codepen.io/begueradj-the-sasster/pen/RwNrbwm?&editable=true&editors=101)
2019/12/08
[ "https://Stackoverflow.com/questions/59237418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329664/" ]
Option 1: Add `class="text-right"` to both `<v-col>` elements if you want to position inline elements such as text. Option 2: Add `class="d-flex justify-end"` to both `<v-col>` elements to position block elements. Since the `<v-btn>` element is most likely displayed as an inline-block element, both options will work.
Just add `align="end"` to each of `v-col`. Here is the [working codepen](https://codepen.io/loia5tqd001/pen/OJPMJBE?&editable=true&editors=101). Because `v-col` is just `display: flex; flex-direction: column;`. Instead of `v-row` you use `justify` to align elements, in `v-col` you use `align`. [![snapshot](https://i.stack.imgur.com/78jWZ.png)](https://i.stack.imgur.com/78jWZ.png)
3,061,013
I want to pass the String value between the classes both are same package. so i created the the classs like the code: ``` public class Map_Delegate { String myLatitude; String myLongitude; String myName; private String TAG = "Map_Delegate"; public String getMyName() { return this.myName; } public void setMyName(String value) { Log.v(TAG, value); this.myName = value; } public String getMyLatitude() { return this.myLatitude; } public void setMyLatitude(String value) { Log.v(TAG, value); this.myLatitude = value; } public String getMyLongitude() { return this.myLongitude; } public void setMyLongitude(String value) { Log.v(TAG, value); this.myLongitude = value; } } ``` But it can't pass the value. I done like this code to set the value: ``` Map_Delegate map = new Map_Delegate(); map.setMyName(first_name_temp + " " + last_name_temp); map.setMyLatitude(homeLatitude_temp); map.setMyLongitude(homeLongitude_temp); ``` code to get the value: ``` Map_Delegate map = new Map_Delegate(); name_val = getMyName(); lat_val = getMyLatitude(); long_val = getMyLongitude(); ``` Why get the Null value can you Guess? All classes in the same package and public .AnyIdea?
2010/06/17
[ "https://Stackoverflow.com/questions/3061013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267269/" ]
I'm not sure I entirely understand what you are doing, but from what you wrote it looks like you are creating a new Map\_Delegate each time. So you create one object and set the values then you create another object and try to get the values (but by creating a new object the values are initialised to null). You should be calling get on the object you first created, which requires holding a reference to it and passing it around to wherever it is needed. Alternatively it might be that you are trying to implement the Singleton design pattern. Using the Singleton design pattern means that there will only ever be one instance of a given class so you don't need to pass the reference around you can just get it by calling getInstance again. Basically to achieve singleton for your case you would do: ``` public class Map_Delegate { private static Map_Delegate instance; private Map_Delegate() { // Private constructor so nobody can create an instance of your class. } public static Map_Delegate getInstance() { if (instance == null) { instance = new Map_Delegate(); } return instance; } // All the rest of your code can go here. } ``` Now you can do: ``` Map_Delegate a = Map_Delegate.getInstance(); a.setMyName("Name"); // Whatever else. ``` Then later on you can do: ``` Map_Delegate b = Map_Delegate.getInstance(); String name = b.getMyName(); ``` and name won't be null becuase you are using the same instance from before.
The reason for the null values that you are creating two map\_delegate instances. A new instnace has null values for the properties (unless you specify a default value - not the case here.) You set the values on the first instance, but then retrieve from second - the second instance is newly constructed with null values. I would avoid the singleton pattern. Instead, ensure that your code passes the same instance to the parts that need them. Consider what you want do with the map\_delegate, and then add a way to pass in the appropriate delegate - usually as a property or a constructor to the collaborator.
41,662,873
``` apiRoutes.post('/authenticate', function(req, res) { User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.send({success: false, msg: 'Authentication failed. User not found.'}); } else { // check if password matches user.comparePassword(req.body.password, function (err, isMatch) { if (isMatch && !err) { // if user is found and password is right create a token var expires=moment().add(1,'days').valueOf(); var token = jwt.encode(user, config.secret,{ exp: expires}); // return the information including token as JSON res.json({success: true, token: 'JWT ' + token}); } else { res.send({success: false, msg: 'Authentication failed. Wrong password.'}); } }); } }); }); ``` It prompt error : /home/oracle/node/ang\_backend1/node\_modules/jwt-simple/lib/jwt.js:130 throw new Error('Algorithm not supported'); ^ Error: Algorithm not supported at Object.jwt\_encode [as encode] (/home/oracle/node/ang\_backend1/node\_modules/jwt-simple/lib/jwt.js:130:11) at /home/oracle/node/ang\_backend1/app.js:198:27 at /home/oracle/node/ang\_backend1/app/models/user.js:48:9 at /home/oracle/node/ang\_backend1/node\_modules/bcryptjs/dist/bcrypt.js:261:17 at /home/oracle/node/ang\_backend1/node\_modules/bcryptjs/dist/bcrypt.js:1198:21 at Immediate.next [as \_onImmediate] (/home/oracle/node/ang\_backend1/node\_modules/bcryptjs/dist/bcrypt.js:1078:21) at processImmediate [as \_immediateCallback] (timers.js:383:17)
2017/01/15
[ "https://Stackoverflow.com/questions/41662873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7091886/" ]
> > if one of them are in lines[k], the code have to pass and do next code > > > The If statement should be: ``` if 2 in list[k] or 0 in list[k]: pass else: continue ```
If I understood your question correctly, you want to check each nested list inside `lines = [[1,1,1],[1,2,1],[1,0,1],[1,1,1]]` whether it contains `2` or `0` and perform a certain operation if that is the case. You can do this by looping over the nested lists inside `lines`: ``` lines = [[1,1,1], [1,2,1], [1,0,1], [1,1,1]] for sublist in lines: if 2 in sublist or 0 in sublist: # Perform operation, e. g. print('Performing operation on ' + str(sublist)) ``` As already stated, the syntax for checking if an iterable contains a certain value is `in` or `not in`, not `is in` or `is not in` respectively.
55,947
I am learning about SSH and how to use it to secure file transfers and commands between a windows machine and a Linux server. Everything that I have read so far indicates that I need to use an SFTP client (like WinSCP) to connect to my server and transfer files. Gettin gin a little deeper, the docs for WinSCP never tell me to set up a public or private key pair on my client and server. I thought that the public and private keys were a fundamental element of how SSH worked. How is SFTP (which I have read is based on SSH) able to function without a public and private key pair (or is it defaulting to an insecure mode like FTP in the situation?) Originally, I thought that I needed to create these pairs for each individual that wanted to connect to the server and manually copy the public key file to the clients machine. EDIT ============================= I did not understand that there are two sets of public/private keys in use, one that is created by the server and one that could possibly be created by the client. Initially, I though that they were the same public/private key pair.
2014/04/16
[ "https://security.stackexchange.com/questions/55947", "https://security.stackexchange.com", "https://security.stackexchange.com/users/42370/" ]
**Short answer:** there is necessarily a public/private key pair on the server. There *may* be a public/private key pair on the client, but the server may elect to authenticate clients with passwords instead, --- [SSH](http://en.wikipedia.org/wiki/Secure_Shell) is a generic tunnel mechanism, in which some "application data" is transferred. One such application is the "remote shell" which is used to obtain an open "terminal" on a server, in which terminal applications can be run. Another, distinct application is the file transfer protocol known as SFTP. From the SSH point of view, which application is used is irrelevant. This means that any authentication concept applies equally to SSH (the "remote shell" part) and SFTP. The server MUST have a public/private key pair. That key is used for the tunnel part, so a server will use the same key pair for all applicative protocols. Most Unix-like operating systems (e.g. Linux) create a SSH key pair when first installed, and will use it thereafter. This means that you don't have to "create a key" when you configure your SSH server to also be used as SFTP: the server already has a key. A client may have a public/private key pair if it wishes to be authenticated based on that key; this is all about *client authentication*, i.e. about how the server will make sure that it is talking to the right client. Password-based authentication and key-based authentication are the two most common methods (some servers are configured to require *both*). By definition, only the key-based authentication requires that the client stores and uses a key pair of its own.
In SSH, you have two sets of key pairs: one for the server and one for the users. The server key pair is mandatory but it is typically generated during the installation of the server: all you have to do is validate the server public key fingerprint (a simple hash) and, as long as the key is unchanged, your client will silently connect. The key pair you use for authenticating, however, can be optional (or disallowed) depending on what authentication method you've decided to allow or require on the server. The [Wiki article on SSH](http://en.wikipedia.org/wiki/Secure_Shell) has plenty of juicy details but, to summarise, there are 4 supported authentication mechanism: * **Password** requires a username and password combination * **Public key** requires acess to the private part of the public key you use for authentication (typically, you setup the key pair on the client and just update the server configuration with your public key). * **Keyboard interactive** is mostly used for one-time passwords and similar. * **[GSSAPI](http://en.wikipedia.org/wiki/Generic_Security_Services_Application_Program_Interface)**, a framework used for implementing other authentication scheme, usually to implement [single sign-on](http://en.wikipedia.org/wiki/Single_sign-on) (most notably [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29))
30,733
A project manager's responsibility is to lead a project to a successful completion, which includes finishing the project on time, a happy customer, a proud team, etc. But it also includes financial results, right? A project manager is preparing correct estimations and a project plan and controls their execution - these estimations and the project manager's control skills largely determine whether the project will be profitable at all. A project manager is able to organize and motivate the project team to complete the project earlier and so to increase the profitability of the project. A project manager is able to avoid or mitigate the risks and thus avoid time and financial losses. If the project is completed later than it was planned, then what is the financial impact of this failure? etc. So what are commonly used financial indicators of a project and a project manager's efficiency (EBITDA, ROI, profitability, etc)? The question assumes that the company earns money by doing projects for customers, for example a vendor of custom software.
2020/12/06
[ "https://pm.stackexchange.com/questions/30733", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/40376/" ]
A lot depends on the commercial context, the business need being served and presumably the nature of the PM role as well. You have tagged this question with "Scrum" but in Scrum there is no project manager and the Product Owner is the person who is expected to be responsible for delivering business value. Irrespective of the means of delivery, most businesses are more interested in measuring product outcomes and ROI rather than *project* success. The fact that one project finished on time or on budget may be of little significance if the product it developed is a loser. On the other hand a project that bust its budget and took unexpectedly long might yield a world-beating product. In business terms the former looks like failure; the latter is a success. In the case where the project *is* your product, for example you are selling software development, systems integration or consulting services, then different considerations might apply. Individual project profitability isn't necessarily the measure of success however. Service providers sometimes run projects at a loss, either in the expectation that they may get more business in future or just because a loss-making project is preferable to the fixed costs of no project at all. In short, trying to measure a project's success is probably the wrong thing to do. Measuring products and value streams is better. In any case, success or failure should not be attributable to one person but to a team.
As noted [here](https://www.projectmanagement.com/wikis/345150/Key-Performance-Indicators), it doesn't really matter which financial indicator is used, as long as it's objective and measurable. The other key point is, that for a Project Manager to be held responsible to avoid and mitigate risks (as well as all the other magic you attribute to us) they need the authority, not only the responsibility. More often than not, it's the PjM's responsibility to keep all the balls in the air, yet they don't have the authority to make it happen, and therefore the success (and more often than not, failure) depend on how fast and cooperative the "authorities" are, once the PjM identifies an issue.
4,079,575
In some web pages, when we stop mouse cursor on some words (e.g. some popular movie star names) on the web page, a pop-up box near the words will show-up, showing maybe some related pictures for the move star, a short summary for the movie star, and related twitter link for this movie star. Then we can move mouse on the pop-up windows to click for picture or twitter link. When the mouse cursor is leaving such pop-up window, the pop-up window will disappear automatically. Are there any existing ready to use code to implement such effect? BTW: I remembered some web site has some underline keyword, and when mouse move over such keywords, a related Ads windows will pop-up around the keyword. This is the effect I am looking for in this question. thanks in advance, George
2010/11/02
[ "https://Stackoverflow.com/questions/4079575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/63235/" ]
You're looking for the HoverCard effect? <http://www.shoutmeloud.com/gravatar-hovercards-for-wordpress-org-blogs.html> <http://closure-library.googlecode.com/svn/docs/closure_goog_ui_hovercard.js.source.html>
I think `onmouseover` is what you need to look into
16,210
Are there any other runners out there who have bunions on their feet? If so, has running led to any long-term or short-term health problems? Is it worthwhile to get a special pair of shoes to accommodate the bunions? I've heard conflicting answers on this, from both professionals and well-meaning people who don't necessarily have bunions themselves. I don't think my bunions have affected my running, though I've been told that I walk on the outside of my feet, and when I run, my feet roll towards the inside, onto my bunions. I've also been told that my bunions raise the risk of hurting my arch, or cause me to run flat-footed. I was told this by a running-shoe salesman, however; in reality, how bad is it to be running flat-footed? Having read *Born To Run*, the jury's still out for me there. My bunions are the type where the joint where my big toe meets my metatarsus (the inside edge of the balls of my feet) protrudes outwards significantly more than usual. The bones of my feet have just grown that way; it's not a case of chafing leading to calluses, as I originally thought bunions were. (Also, for reference, I'm just an amateur runner; I don't work on any particular goals except for continuous running, and I usually just toss on my shoes and go without planning much beforehand.)
2014/04/21
[ "https://fitness.stackexchange.com/questions/16210", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/8434/" ]
Disclaimer: I am not an expert in running form or podiatry. This is my own experience. I have a bunion on one foot, which was I suspect caused by over-aggressive rock climbing shoes, but when it flares up it can also make running painful. What seems to set off the pain is shoes that put lateral pressure on my toes (i.e. squeeze my toes together). What has really helped has been switching to toe shoes (Vibram FiveFingers) and running barefoot. I guess because there is then no inward pressure on my toes at all and they are free to move. This is slightly at odds with professional advice I was given which was to get custom splints and inserts made to immobilse the toe. It is worth bearing in mind when receiving advice who stands to profit from it. Not that people are profiteering, but that they will naturally know more about, be more interested in, and be more likely to recommend interventions they have a professional interest in.
I've heard from my trainer that you could really hurt yourself if you continue to run with bunions on hard surfaces. I'd suggest running on a track (the rubberized kind) or on grass - even bare feet would be ok. Alternately if you live near a beach, running on dry sand is also a great idea. Finally if none of the above are options, get yourself a good pair of shoes and hit a treadmill.
41,281,747
I want to customize the display of my html, using `window.open()`. I wrote the code below, and got the output as per the screen shot attached. My points are: 1. I found the window to be `resizable` though i used `resizable=no` 2. how to hide the `bar title` 3. How to add my customs title to the form/page, I want to replace the `untitled` by `report`: `var report = window.open('', '_blank', 'title="Report",toolbar=0, top=500,left=500, width=200,height=100,resizable=no,scrollbars=no, menubar=no, location=no, status=no');` ``` report.document.body.innerHTML = text; ``` [![enter image description here](https://i.stack.imgur.com/BtTdq.png)](https://i.stack.imgur.com/BtTdq.png)
2016/12/22
[ "https://Stackoverflow.com/questions/41281747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2441637/" ]
If you want a title to appear in the new window just set the `title` tag in your `text` inside the `<head>`. ``` <title>Title you want</title> ``` Example: ``` var report = window.open('', '_blank', 'title="Report",toolbar=0, top=500,left=500, width=200,height=100,resizable=no,scrollbars=no, menubar=no, location=no, status=no'); report.document.write("<html><head><title>TEST</title></head></html>"); ``` Notice that I used `document.write()`. Also, in modern browser is not permitted to hide the url bar, you can find more info [here](https://stackoverflow.com/a/16603908/4266836). The resize option has also a bug. Check [this](https://stackoverflow.com/a/1715220/4266836) answer about disabling resize of new windows.
``` var report = window.open('', '_blank', 'title="Report",toolbar=0, top=500,left=500, width=200,height=100,resizable=no,scrollbars=no, menubar=no, location=no, status=no'); report.document.body.innerHTML = text; **report.document.title = 'custom one';** ```
32,030,244
I'm using Django 1.8. When running `python manage.py squashmigrations myapp` I get this: ``` manage.py squashmigrations: error: the following arguments are required: migration_name ``` How do I find the **migration\_name**?
2015/08/15
[ "https://Stackoverflow.com/questions/32030244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4162811/" ]
the migration\_name is the number head of the files locate in yourapp/migrations/ ``` python manage.py sqlmigrate asset 0001 ll asset/migrations/ total 12 -rw-r--r--. 1 root root 1326 Feb 9 20:17 0001_initial.py -rw-r--r--. 1 root root 1405 Feb 9 20:20 0001_initial.pyc -rw-r--r--. 1 root root 0 Feb 5 06:07 __init__.py -rw-r--r--. 1 root root 140 Feb 5 06:48 __init__.pyc ``` asset is my app and 0001 is the migration\_name
To find out programatically in a script you can use ``` ./manage.py migrate --list <app_name> | tail -1 | cut -d ' ' -f 3 ``` For a bunch of apps ``` APPS="asset common product" for APP in $APPS do # find out the latest migration MIGRATION_NAME=`./manage.py migrate -l $APP | tail -1 | cut -d ' ' -f 3` ./manage.py squashmigrations $APP $MIGRATION_NAME done ```
59,784,489
I am trying to implement MVP Matrices into my engine. My Model matrix is working fine but my View and Projection Matrices do not work. Here is the creation for both: ``` public void calculateProjectionMatrix() { final float aspect = Display.getDisplayWidth() / Display.getDisplayHeight(); final float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))) * aspect); final float x_scale = y_scale / aspect; final float frustum_length = FAR_PLANE - NEAR_PLANE; proj.identity(); proj._m00(x_scale); proj._m11(y_scale); proj._m22(-((FAR_PLANE + NEAR_PLANE) / frustum_length)); proj._m23(-1); proj._m32(-((2 * NEAR_PLANE * FAR_PLANE) / frustum_length)); proj._m33(0); } public void calculateViewMatrix() { view.identity(); view.rotate((float) Math.toRadians(rot.x), Mathf.xRot); view.rotate((float) Math.toRadians(rot.y), Mathf.yRot); view.rotate((float) Math.toRadians(rot.z), Mathf.zRot); view.translate(new Vector3f(pos).mul(-1)); System.out.println(view); } ``` The vertices i'm trying to render are: -0.5f, 0.5f, -1.0f, -0.5f, -0.5f, -1.0f, 0.5f, -0.5f, -1.0f, 0.5f, 0.5f, -1.0f I Tested the view matrix before the upload to shader and it is correct. This is how I render: ``` ss.bind(); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); ss.loadViewProjection(cam); ss.loadModelMatrix(Mathf.transformation(new Vector3f(0, 0, 0), new Vector3f(), new Vector3f(1))); ss.connectTextureUnits(); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); ss.unbind(); ``` Vertex Shader: ``` #version 330 core layout(location = 0) in vec3 i_position; layout(location = 1) in vec2 i_texCoord; layout(location = 2) in vec3 i_normal; out vec2 p_texCoord; uniform mat4 u_proj; uniform mat4 u_view; uniform mat4 u_model; void main() { gl_Position = u_proj * u_view * u_model * vec4(i_position, 1.0); p_texCoord = i_texCoord; } ```
2020/01/17
[ "https://Stackoverflow.com/questions/59784489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11562753/" ]
While the answer of @Rabbid76 of course it totally right in general, the actual issue in this case is a combination of bad API design (in the case of JOML) and not reading the JavaDocs of the used methods. In particular the [Matrix4f.\_mNN()](https://joml-ci.github.io/JOML/apidocs/org/joml/Matrix4f.html#_m00(float)) methods only set the respective matrix field but omit reevaluating the matrix properties stored internally in order to accelerate/route further matrix operations (most notably multiplication) to more optimized methods when knowing about the properties of a matrix, such as "is it identity", "does it only represent translation", "is it a perspective projection", "is it affine", "is it orthonormal" etc... This is an optimization that JOML applies to in most cases very significantly improve performance of matrix multiplications. As for bad API design: Those methods are only public in order for the class `org.joml.internal.MemUtil` to access them to set matrix elements read from NIO buffers. Since Java does not (yet) have friend classes, those \_mNN() methods must have been public for this reason. They are however not meant for public/client usage. [I've changed this now](https://github.com/JOML-CI/JOML/commit/51efdc9858d271e630dd21bd57e06161abe64b6b) and the next JOML version 1.9.21 will not expose them anymore. In order to set matrix fields still explicitly (not necessary in most cases like these here) one can still use the [mNN()](https://joml-ci.github.io/JOML/apidocs/org/joml/Matrix4f.html#m00(float)) methods, which do reevaluate/weaken the matrix properties to make all further operations still correct, albeit likely non-optimal. So the issue in this cases is actually: JOML still thinks that the manually created perspective projection matrix is the identity matrix and will short-cut further matrix multiplications assuming so.
So I tried everything and found out that you should not initialise the uniform locations to 0. In the class that extends the ShaderProgram class, I had: ``` private int l_TextureSampler = 0; private int l_ProjectionMatrix = 0; private int l_ViewMatrix = 0; private int l_ModelMatrix = 0; ``` Changing it to this: ``` private int l_TextureSampler; private int l_ProjectionMatrix; private int l_ViewMatrix; private int l_ModelMatrix; ``` Worked for me.
40,974,664
I'm trying to generate a system that allows me to check if multiple jobs have completed running on a cluster. This bash code should work to wait until all PBS jobs have completed: ``` #create the array ALLMYJOBS=() # loop through scripts, submit them and store the job IDs in the array for i in 1 2 3 4 5 do ALLMYJOBS[${i}]=$(qsub script${i}.bash) done JOBSR=true # check if all jobs have completed: while [ ${JOBSR} ];do JOBSR=false for m in "${ALLMYJOBS[@]}" do if qstat ${m} &> /dev/null; then JOBSR=true fi done done ``` am I missing something obvious?
2016/12/05
[ "https://Stackoverflow.com/questions/40974664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7252002/" ]
You've called `in_fridge` but you haven't done anything with the result. You could print it, for example: ``` result = in_fridge() print(result) ```
You are not priting the result of the `in_fridge` call, you should print it: ``` def in_fridge(): try: count =fridge [wanted_food] except KeyError: count =0 return count fridge ={"apples":10, "oranges":3, "milk":9} wanted_food="apples" print(in_fridge()) ```
61,433,963
I have a button. I want to change the background after I click on it. My problem here is the button auto call `paintComponent()`. How can prevent this? I expect after clicking the button the button will be blue, but it will still be red. ``` package test; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class ButtonDemo extends JButton implements ActionListener{ public ButtonDemo() { this.setText("BUTTON TEXT"); this.addActionListener(this); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); setBackground(Color.RED); } public static void main(String[] args){ JFrame frame = new JFrame(); JPanel contentPane = new JPanel(); frame.setContentPane(contentPane); contentPane.add(new ButtonDemo()); frame.setSize(500, 500); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { this.setBackground(Color.BLUE); } } ```
2020/04/25
[ "https://Stackoverflow.com/questions/61433963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10721258/" ]
My personal gut feeling is that `JButton` is probably not suited to your desired goal. Essentially, you want to control when and how the "selected" state of the piece is changed. Personally, I would have some kind of controller which monitored the mouse events in some way (probably having the piece component delegate the event back to the controller) and some kind of model which control when pieces become selected, this would then notify the controller of the state change and it would make appropriate updates to the UI. But that's a long process to setup. Instead, I'm demonstrating a simple concept where a component can be selected with the mouse, but only the controller can de-select. In this example, this will allow only a single piece to be selected ``` import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.LineBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Main { public static void main(String[] args) { new Main(); } public Main() { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { public TestPane() { setLayout(new GridLayout(5, 5)); ChangeListener listener = new ChangeListener() { private PiecePane selectedPiece; @Override public void stateChanged(ChangeEvent e) { if (!(e.getSource() instanceof PiecePane)) { return; } PiecePane piece = (PiecePane) e.getSource(); // Want to ignore events from the selected piece, as this // might interfer with the changing of the pieces if (selectedPiece == piece) { return; } if (selectedPiece != null) { selectedPiece.setSelecetd(false); selectedPiece = null; } selectedPiece = piece; } }; for (int index = 0; index < 5 * 5; index++) { PiecePane pane = new PiecePane(); pane.addChangeListener(listener); add(pane); } } } public class PiecePane extends JPanel { private boolean selecetd; private Color selectedBackground; private Color normalBackground; private MouseListener mouseListener; public PiecePane() { setBorder(new LineBorder(Color.DARK_GRAY)); mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { setSelecetd(true); } }; setNormalBackground(Color.BLUE); setSelectedBackground(Color.RED); } @Override public Dimension getPreferredSize() { return new Dimension(50, 50); } @Override public void addNotify() { super.addNotify(); addMouseListener(mouseListener); } @Override public void removeNotify() { super.removeNotify(); removeMouseListener(mouseListener); } public void addChangeListener(ChangeListener listener) { listenerList.add(ChangeListener.class, listener); } public void removeChangeListener(ChangeListener listener) { listenerList.remove(ChangeListener.class, listener); } protected void fireSelectionChanged() { ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class); if (listeners.length == 0) { return; } ChangeEvent evt = new ChangeEvent(this); for (int index = listeners.length - 1; index >= 0; index--) { listeners[index].stateChanged(evt); } } public boolean isSelected() { return selecetd; } public void setSelecetd(boolean selecetd) { if (selecetd == this.selecetd) { return; } this.selecetd = selecetd; updateSelectedState(); fireSelectionChanged(); } public Color getSelectedBackground() { return selectedBackground; } public void setSelectedBackground(Color selectedBackground) { this.selectedBackground = selectedBackground; updateSelectedState(); } public Color getNormalBackground() { return normalBackground; } public void setNormalBackground(Color normalBackground) { this.normalBackground = normalBackground; updateSelectedState(); } protected void updateSelectedState() { if (isSelected()) { setBackground(getSelectedBackground()); } else { setBackground(getNormalBackground()); } } } } ```
If you want to change the background for a short while you can do it with swing `Timer`: ``` import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class ButtonDemo extends JButton implements ActionListener{ private static final int DELAY = 600; //milliseconds private final Timer timer; public ButtonDemo() { this.setText("BUTTON TEXT"); this.addActionListener(this); Color defaultCloor = getBackground(); timer = new Timer(DELAY, e-> setBackground(defaultCloor)); timer.setRepeats(false); } public static void main(String[] args){ JFrame frame = new JFrame(); JPanel contentPane = new JPanel(); frame.setContentPane(contentPane); contentPane.add(new ButtonDemo()); frame.setSize(300, 200); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { timer.stop(); this.setBackground(Color.RED); timer.start(); } } ```
3,046,284
I'm currently trying to capitalize the very first letter from an input. Here's what I tryed : ``` fieldset input { text-transform:capitalize; } ``` But it doesn't work the way I want, as every word is capitalized. I also tryed this : ``` fieldset input:first-letter { text-transform:uppercase; } ``` But it seems <input /> doesn't work at all with first-letter... Anyway, do you have any idea of how to achieve this without javascript (or as little as possible) ?
2010/06/15
[ "https://Stackoverflow.com/questions/3046284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367392/" ]
**JS**: `str.charAt(0).toUpperCase();`
``` $('#INPUT_ID').keyup(function(){ if($(this).val().length>0 && $(this).val().length<5){ $(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().substr(1)); } }); ``` Can't use length==1, as it doesn't work if user types fast.
6,452,466
I have a service which I believe to have running in the foreground, How do I check if my implementation is working?
2011/06/23
[ "https://Stackoverflow.com/questions/6452466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811985/" ]
Starting with API29 (Q), you can simply check it with the following code. Can be called from inside your service. If you don't have your service instance, you can obtain it by using binder. ``` class MyService : Service { val isForeground: Boolean get() = foregroundServiceType != FOREGROUND_SERVICE_TYPE_NONE } ```
This worked for me in the [***Coinverse***](https://play.google.com/store/apps/details?id=app.coinverse) app for crypto news. It's is the most concise **Kotlin** solution. Thanks to [Abbas Naqdi](https://github.com/oky2abbas) in this [GitHub issue](https://gist.github.com/kevinmcmahon/2988931#gistcomment-2937968). ``` @Suppress("DEPRECATION") // Deprecated for third party Services. fun <T> Context.isServiceRunning(service: Class<T>) = (getSystemService(ACTIVITY_SERVICE) as ActivityManager) .getRunningServices(Integer.MAX_VALUE) .any { it.service.className == service.name } ```
51,639,263
My task is to remove Placeholder from input box when user clicks on it and make label visible. If user doesn't fill anything in it again place back the placeholder and make label invisible. I am able to hide it but can't reassign it. I have tried element.setAttribute(attribute,value) , element.attribute=value & element.[attribute]=value type but isn't working. I have kept default `visibility` of `<label>` `"hidden"` I have created hide() and show() functions for the task both having 2 parameters viz. 1. id of input box 2. id of label Code JavaScript: ``` var placehlder; function hide(input_id,lbl){ var e1=document.getElementById(input_id); placehlder=e1.getAttribute('placeholder'); /*document.write(placehlder);*/ e1.placeholder=""; var e2=document.getElementById(lbl); e2.style.visibility="visible"; } function show(input_id,lbl){ var e1=window.document.getElementById(input_id).value; var e2=document.getElementById(lbl); /*document.write(placehlder);*/ if (e1.length ==0) { e2.style.visibility="hidden"; e1.placeholder=placehlder; /*e1.setAttribute('placeholder',placehlder);*/ /*e1['placeholder']=placehlder;*/ } } ``` Code HTML: ``` <form> <label id="first" >First Name</label><br/> <input id="box" type="text" placeholder="First Name" onclick="hide(id,'first')" onfocusout="show(id,'first')"/> </form> ``` Full Code: HTML + CSS + JAVASCRIPT: ```js var placehlder; function hide(input_id,lbl){ var e1=document.getElementById(input_id); placehlder=e1.getAttribute('placeholder'); /*document.write(placehlder);*/ e1.placeholder=""; var e2=document.getElementById(lbl); e2.style.visibility="visible"; } function show(input_id,lbl){ var e1=window.document.getElementById(input_id).value; var e2=document.getElementById(lbl); /*document.write(placehlder);*/ if (e1.length ==0) { e2.style.visibility="hidden"; e1.placeholder=placehlder; /*e1.setAttribute('placeholder',placehlder);*/ /*e1['placeholder']=placehlder;*/ } } ``` ```css #first{ visibility: hidden; } #box{ } ``` ```html <!doctype html> <html> <head> <meta charset="utf-8"/> <title> Functions </title> </head> <body> <form> <label id="first" >First Name</label><br/> <input id="box" type="text" placeholder="First Name" onclick="hide(id,'first')" onfocusout="show(id,'first')"/> </form> </body> </html> ``` EDIT 1: I have got the solution to my problem using CSS in answer by @Darlesson . But if possible please tell whats wrong in my Code. EDIT 2: As pointed by @lenilsondc my code didn't worked because of `var e1` didn't had element but the `value attribute` of element. `var e1=window.document.getElementById(input_id).value;` replaced to `var e1=window.document.getElementById(input_id);` did worked with `e1.placeholder=placehlder;`
2018/08/01
[ "https://Stackoverflow.com/questions/51639263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8810517/" ]
I would suggest to use CSS for the placeholder portion instead: ``` :focus::placeholder{ opacity: 0; } ``` ```css :focus::placeholder { opacity: 0; } ``` ```html <input placeholder="Visible"> ```
If you can't do this using css ([using @Darlesson's answer](https://stackoverflow.com/a/51639331/4488121)) for compatibility reasons, you can do this as the following snippet using javascript. The trick is to store the old placeholder so that when you need to restore you have it available. In this case I used a new attribute `data-placeholder` where I store de current value and clean the real `placeholder` attribute. Finally, when the element lose focus, you can get the attribute `data-placeholder` and reset the real `placeholder` value with it. ```js var myInputLabel = document.getElementById('myInputLabel'); var myInput = document.getElementById('myInput'); // when element gets focused myInput.addEventListener('focus', function (e) { // save current placeholder myInput.setAttribute('data-placeholder', myInput.getAttribute('placeholder')); // clear current placeholder myInput.setAttribute('placeholder', ''); // show label myInputLabel.style.display = 'inline'; }); // when element gets blured myInput.addEventListener('blur', function (e) { // restore the placeholder stored on data-placeholder myInput.setAttribute('placeholder', myInput.getAttribute('data-placeholder')); // hide label myInputLabel.style.display = 'none'; }); ``` ```html <form> <label id="myInputLabel" style="display: none;">Name</label><br> <input type="text" id="myInput" placeholder="Name"> </form> ```
1,604,060
I want to remove this [arrow thing](https://i.stack.imgur.com/V4oF7.png) in MS Word [![arrow thing](https://i.stack.imgur.com/V4oF7.png)](https://i.stack.imgur.com/V4oF7.png) I tried everything like searching about this on the net but to my dismay, I found nothing. Please help.
2020/11/22
[ "https://superuser.com/questions/1604060", "https://superuser.com", "https://superuser.com/users/-1/" ]
All you have to do is Google. "Expand/Collapse is a feature built-in to all the default heading styles in Word except for No Space and Normal. There is no option to disable the Expand/Collapse feature unless you will be using the Normal style or you will be creating a custom style based on the Normal formatting." [How do you remove all instances of expand/collapse in Word 2016?](https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-mso_win10-mso_2016/how-do-you-remove-all-instances-of-expandcollapse/57fb3f29-3c02-48a2-aa3c-99fc2e0e5457#:%7E:text=Expand%2FCollapse%20is%20a%20feature,based%20on%20the%20Normal%20formatting.)
As others have mentioned, this is most likely due to the OP using one of the Heading styles. However, it can still happen that you will have the expand/collapse arrows when using the Normal style. This is a problem I ran into from time to time for years, and no amount of Googling ever provided me with a solution, but I finally figured it out. If the text is in the Normal style, and you still have expand/collapse arrows, what you need to do is click on the line(s) where you see the arrows, open the paragraph settings, and on the Indents and Spacing tab find where it says Outline Level. It will probably be set to 'Level 1'. If you change it to 'Body Text', the arrows will disappear, and you will no longer have to worry about accidentally collapsing random sections of the text. If you're using one of the Heading styles, this option will be locked at Level 1. I hope that helps someone. I know it drove me crazy for a long time.
3,430,810
I'm using wget to download website content, but wget downloads the files one by one. How can I make wget download using 4 simultaneous connections?
2010/08/07
[ "https://Stackoverflow.com/questions/3430810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413869/" ]
I found (probably) [a solution](http://blog.netflowdevelopments.com/2011/01/24/multi-threaded-downloading-with-wget) > > In the process of downloading a few thousand log files from one server > to the next I suddenly had the need to do some serious multithreaded > downloading in BSD, preferably with Wget as that was the simplest way > I could think of handling this. A little looking around led me to > this little nugget: > > > > ``` > wget -r -np -N [url] & > wget -r -np -N [url] & > wget -r -np -N [url] & > wget -r -np -N [url] > > ``` > > Just repeat the `wget -r -np -N [url]` for as many threads as you need... > Now given this isn’t pretty and there are surely better ways to do > this but if you want something quick and dirty it should do the trick... > > > **Note:** the option `-N` makes `wget` download only "newer" files, which means it won't overwrite or re-download files unless their timestamp changes on the server.
`make` can be parallelised easily (e.g., `make -j 4`). For example, here's a simple `Makefile` I'm using to download files in parallel using wget: ``` BASE=http://www.somewhere.com/path/to FILES=$(shell awk '{printf "%s.ext\n", $$1}' filelist.txt) LOG=download.log all: $(FILES) echo $(FILES) %.ext: wget -N -a $(LOG) $(BASE)/$@ .PHONY: all default: all ```
1,369,388
I know of the ||= operator, but don't think it'll help me here...trying to create an array that counts the number of "types" among an array of objects. ``` array.each do |c| newarray[c.type] = newarray[c.type] ? newarray[c.type]+1 ? 0 end ``` Is there a more graceful way to do this?
2009/09/02
[ "https://Stackoverflow.com/questions/1369388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160863/" ]
``` types = Hash.new(-1) # It feels like this should be 0, but to be # equivalent to your example it needs to be -1 array.each do |c| types[c.type] += 1 end ```
In Ruby 1.8.7 or later you can use `group_by` and then turn each list of elements into count - 1, and make a hash from the array returned by `map`. ``` Hash[array.group_by(&:class).map { |k,v| [k, v.size-1] }] ```
13,252,684
I'm trying to set up my own autoscaling system on AWS and I've set up alarms for any instance spawned with a specific AMI ID. When I check the the metrics which are only monitoring one server, they get information just fine. The "aggregated" stats however always fail. Is this a problem with AWS or does this not do what I think it does. I'll also point out these are all default metrics, not added through the CLI API.
2012/11/06
[ "https://Stackoverflow.com/questions/13252684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1400370/" ]
Have you enabled detailed monitoring for your instances? AWS supports aggregated metrics only for instances with detailed monitoring enabled: > > For the instances where you've enabled detailed monitoring, you can also get aggregated data across groups of similar instances. > > > See: <http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/US_GetStatistics.html>.
If your cloud metrics says "insufficient data" that means your server have not met the state which you have configured using CLI.
38,327,133
I've got this error on Android. Just in case, I use react-native-maps. Do you know what is it from? [![error from device](https://i.stack.imgur.com/FmbJE.png)](https://i.stack.imgur.com/FmbJE.png)
2016/07/12
[ "https://Stackoverflow.com/questions/38327133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1442172/" ]
I also got this error when I was conditionally rendering a element based on the truthiness of a non-boolean value: ``` <View> {stringVariable && <Text>{stringVariable}</Text>} </View> ``` This code gives me the error. However, if I double negate string variable like so: ``` <View> {!!stringVariable && <Text>{stringVariable}</Text>} </View> ``` it works. Kind of a dumb error on my part, but it took me a while to figure out.
The problem for me with this error was that somehow I managed to end up with a `<View>` inside of `<Text>`. That was not very obvious because I had a `Button` component that was accepting some children wrapped in a `<Text>` and I was using some custom component for an `Icon` when instantiating Button. After a while somebody wrapped the `Icon` in a `<View>` to give it some padding and that caused the issue in the end. It took some time to figure it out but in the end I solved it. It may differ from case to case but I hope my problem inspires you in your debugging session. Cheers!
11,832,371
So this is not about the pumping lemma and how it works, it's about a pre-condition. Everywhere in the net you can read, that regular languages must pass the pumping lemma, but noweher anybody talks about finite languages, which actually are a part of regular languages. So we might all aggree, that the following language is a finite language as well as it's a regular one, but it definitely does not pass the pumping lemma: `L = {'abc', 'defghi'}` Please, tell me if simply no one writes about it or **why** we're wrong - or even not.
2012/08/06
[ "https://Stackoverflow.com/questions/11832371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572445/" ]
There's a simplest way to show that some language is infinite. Assume that L is the language for some regular expression E, L(E). Suppose L(E) is equivalent to `{ab^nc | n ≥ 0}`. We know that E is in the form `ab*c`, and we know this language is probably regular(we can't prove something be regular), since the pumping lemma this conclusion is `k = 0`, put in another way, `xz = ac`, and every regular expression has an equivalent automaton. The conclusion is simple, if the DFA has some state with transition to itself, the language is infinite. ``` a b c q0 q1 q1 q1 q2 *q2 ``` q1 has transition to itself, thus L(E) is infinite.
Finite languages are regular languages by definition because you can build a regular expression that satisfies it by just expressing the union of all the words (e.g. `(abc)|(defghi)` is a regular expression that satisfies your language) and consequently you can have a [deterministic finite automaton](http://en.wikipedia.org/wiki/Deterministic_finite_automaton) that satisfies it. Not being able to pass the pumping lemma does not means that the language is not regular. In fact, to use the pumping lemma your language must have some kind of closure in its definition. If your language is just a set of words there is nothing to "pump" in it.
24,828,382
I have one asp.net page with two gridview using updatepanel.when i click the submit button data inserting in db and update the gridview. i'm handling duplicate insertion of same data when refresh the page. but the problem is when i refreshing the page previous data in the gridview showing not present data. again if i'm clicking the menu its reloading and showing actual data.i'm handling button click but i don't know how to handle this gridview problem when i refresh the page. if anybody pass through same problem please show some light on this or please give some suggession.
2014/07/18
[ "https://Stackoverflow.com/questions/24828382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1307273/" ]
Here is some code that produces the strings you want. I leave to you defining the new value labels and assigning to the variables. Let us know if it's useful. ``` clear all set more off *----- example ----- label def gen 0 "Male" 1 "Female", modify *label value Gender gen label def meal 0 "Lunch" 1 "Dinner", modify *label value Meal me *----- what you want ----- label dir local rnames `=r(names)' foreach labname of local rnames { quietly label list `labname' local myname forvalues i = 0/`r(max)' { local name : label `labname' `i', strict local newname \hspace{0.3cm}`name' local myname `myname' `newname' } display "`myname'" } ``` You can make it a bit shorter, but it's all very "explicit". `help label` and `help extended_fcn` are a must-read. (I still insist that a solution within `tabout` is **maybe** possible; but I can't be sure.) Edit ---- The following is more general, has better form and is a complete example. *Extended macro functions* are still the basis for the code. ``` clear all set more off *----- example database ----- sysuse voter *----- what you want ----- foreach var of varlist _all { local cnewname quietly labellist `var' if "`r(lblname)'" != "" { *disp "`var'" forvalues i = 1/`r(`r(lblname)'_k)' { local val : word `i' of `r(values)' local labval : word `i' of `r(labels)' local newname `val' "\hspace{0.3cm}`labval'" local cnewname `cnewname' `newname' } // forvalues label define newlbl`var' `cnewname' label value `var' newlbl`var' } // if } // foreach labellist ``` I define new value labels and re-associate with corresponding variables. You can try replacing or whatever fits your needs.
Stata doesn't understand TeX or LaTeX, at least not like this. You could just prefix with space(s), but often Stata would just ignore them any way. A bizarre trick I've used occasionally is to use `char(160)` as a pad which looks like a space but won't be trimmed. ``` length(trim("`=char(160)'")) ``` is reported as 1, i.e. `char(160)` is not trimmed. To check that `char(160)` is invisible on your machine, ``` di char(160) ``` But how this works surely depends on your TeX/LaTeX code and how it treats that character.
68,435,943
I have a problem with a code that scrapes a weather website. It's supposed to update hourly, but for some reason, the data given is not the current data on the website; it also doesn't update its data, but keeps feeding the same data continuously. Please help!!! Also, I need help scraping the weather icon from the site. Here is my code: ``` from bs4 import BeautifulSoup from plyer import notification import requests import time if __name__ == '__main__': while True: def notifyMe(title, message): notification.notify( title = title, message = message, #app_icon = icon, timeout = 7 ) try: # site = requests.get('https://weather.com/weather/today/l/5.02,7.97?par=google') site = requests.get('https://weather.com/en-NG/weather/today/l/4dce0117809bca3e9ecdaa65fb45961a9718d6829adeb72b6a670240e10bd8c9') # site = requests.get('http://localhost/weather.com/weather/today/l/5.02,7.97.html') soup = BeautifulSoup(site.content, 'html.parser') day = soup.find(class_= 'CurrentConditions--CurrentConditions--14ztG') location = day.find(class_='CurrentConditions--location--2_osB').get_text() timestamp = day.find(class_='CurrentConditions--timestamp--3_-CV').get_text() tempValue = day.find(class_='CurrentConditions--tempValue--1RYJJ').get_text() phraseValue = day.find(class_='CurrentConditions--phraseValue--17s79').get_text() precipValue = day.find(class_='CurrentConditions--precipValue--1RgXi').get_text() #icon = day.find(id ='svg-symbol-cloud').get_icon() weather = timestamp + "\n" + tempValue + " " + phraseValue + "\n" + precipValue except requests.exceptions.ConnectionError: location = "Couldn't get a location." weather = "Error connecting to website." except AttributeError: weather = timestamp + "\n" + tempValue + " " + phraseValue # print (weather) notifyMe( location, weather ) time.sleep(30) ``` Expected output: Uyo, Akwa Ibom Weather As of 13:28 WAT 30° Mostly Cloudy 55% chance of rain until 14:00
2021/07/19
[ "https://Stackoverflow.com/questions/68435943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16478105/" ]
```py import requests from bs4 import BeautifulSoup def main(url): r = requests.get(url) soup = BeautifulSoup(r.text, 'lxml') x = list(soup.select_one('.card').stripped_strings) del x[4:8] print(x) main('https://weather.com/en-NG/weather/today/l/4dce0117809bca3e9ecdaa65fb45961a9718d6829adeb72b6a670240e10bd8c9') ``` Output: ``` ['Uyo, Akwa Ibom Weather', 'As of 8:03 WAT', '24°', 'Cloudy', '47% chance of rain until 9:00'] ```
It appears the error might have been from the site, because it's working now without the issues. Thank you all for the suggestions. @Ahmed American your code is beautiful. I've learnt from it. @furas I'll try to construct the SVG as you suggested. [That's the output.](https://i.stack.imgur.com/BXfmp.png)
70,660,908
> > Write a function called `minVal` that returns the minimum of the two numbers values passed in as parameters. Note: Be sure to include comments for all functions that you use or create. For example, if you made a call like `x = minVal(10, 14)` `x` should have the value `10`. For your program, you need to define the function and call it and print out the result like this: > > > > ``` > x = minVal(10, 14) > print("The min is " + str(x)) > > ``` > > here is what i have. ``` def minVal(x,y): if x<y: minVal==x else: y=minVal return minVal x=minVal(2,4) print("The min is" + str(x) ) ```
2022/01/11
[ "https://Stackoverflow.com/questions/70660908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17898009/" ]
Just for fun: ``` def minVal(x, y): return x if x < y else y x = minVal(2, 4) print("The min is " + str(x)) ```
> > With Two Different Options > > > ``` def minVal(x, y): if x>y: return x elif x==y: return None else: return y ``` > > With a List With Two Items > > > ``` def minVal(l1): if l1[0]>l1[1]: return l1[0] elif l1[0]==l1[1]: return None else: return l1[1] ``` The second is a poor idea. There is no guarantee l1 will have two items, and if it has more, then the function isn't guaranteed to return the minimum value in the entire function. Also, returning None is odd. If they are equal, then surely returning either one will return the minimum value.
451
Do numbers have an objective existence? If life had not evolved on planet earth would there be numbers or are numbers an invention of human minds? Are there any relevant works that discuss this? (I know of Husserl's *Über der Begriff der Zahl* and Frege's *Grundlagen der Arithmetik* already; are there any other notable discussions of this theme?)
2011/06/17
[ "https://philosophy.stackexchange.com/questions/451", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/160/" ]
A number is an abstract thing. It doesn't exist independently of a thought about it. For example a cat... . A cat can exist without a human observing it - ask the mouse! Or think about Brontosaurus. But a number is abstract - you can compare a basket with 3 bananas and a box with 3 letters, and the common thing among them is, that there are 3 elements. But if you imagine a monkey, deciding between a basket of 3 bananas and another one with 4 - does he have an idea of the number 3, and does he see a connection to 3 strawberries? Or can he divide 3 bananas to 3 monkey childs? I'm not sure, but most scientists assume today, that in the great universe, there is more live - not only on earth, and more intelligent species have been evolved, and they will need numbers as well to reason about their world. See how numbers exist in different cultures, and how they were early used to document ownership. There are different number systems, and not everybody invented the zero, but see how fluently the most potent system was adopted elsewhere. The names of the numbers are convention, but not the numbers themselves. Think about, how the numbers of electrons and protons determine the atoms.
Mathematics is a science that studies common properties of physical objects which do not depend on the actual physical substance of which the objects are constructed. For example it studies what is in common with all round things, with all triangular things etc. Certain objects can be said of to consist of other constituent objects. There is a property of being composed of only one object, of two objects, of three objects etc. All objects that are composed of six other objects have something in common. For example, they can be divided in two objects that have three parts or into three objects that have two parts. This property of being composed of six parts is named "number 6" so the mathematicians could study this common property and then make conclusions about other composed objects (a bunch of flowers, a set of cards etc) without studying them separately. Thus the numbers as properties of real-word objects exist independently, like any other properties, such as being big, or being round, or being heavy (the common properties of all heavy things for example studies mechanics, thus mass is also something that exists independently).
48,873,489
I am developing a REST API using node js and express js. For example, my RESTful API end points are as follows ``` /api/v1/books/:id /api/v1/books ``` I want to authorize the end points only for specific application(web, android or ios). \*\*The users of the application may or may not authenticate in the application. ``` ex: www.bookstore.com bookstore android/ios app ``` ie. only these applications can have access to those end points. How can I implement this using OAuth 2.0 and JWT For example we can view every item in amazon(web/android/ios) without providing login credentials. How can this be implemented.
2018/02/19
[ "https://Stackoverflow.com/questions/48873489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6109352/" ]
I would suggest trying the following: * Log into the server, preferably as the user that the service is set to run as. * Ensure your Zebra printer is installed as a local printer, and the printer name is correct. * Print a test page from the printer properties. * Print your ZPL manually: `net use lpt1 "printer shared name" print "C:\Users\serviceuser\desktop\label.txt"` If you try the above and it works, I would be surprised that the code you linked does not work.
i develop a websockt for this cases [ZPLwebSocket](https://drive.google.com/open?id=1vse4zhsYnPhSoJ6HqyzfhOWYm9PeqEyP) 1. Download the file and uncompress. 2. Run SetUp.exe on client PC. 3. Go to services and start 'Servicio de Impresion desde Navegador' 4. open trysocket.html with GoogleChrome or mozilla 5. write the name of local printer 6. click on button 'enviar' 7. show the messages of server this is javascriptcode on page. ``` $(document).ready(function () { var connection = new WebSocket('ws://localhost:2645/service/'); const reader = new FileReader(); $('.sendZPL').on('click', function () { var tosend = { TipoArchivo: 0, nombre: "Etiqueta de Prueba", code: $(".sendZPL").val(), Tipo: 4, Impresora: $(".impresora").val() } connection.send(JSON.stringify(tosend)); }); connection.addEventListener('message', function (event) { reader.readAsText(event.data); }); reader.addEventListener('loadend', (e) => { const text = e.srcElement.result; console.log(text); $(".serverResponse").val(text); }); }); ``` this is the socket code c# for run on ConsoleApp: ``` class Program { private static Server.WebsocketServer websocketServer; private static System.Diagnostics.EventLog eventLog1= new EventLog(); static void Main( string[] args ) { if (!System.Diagnostics.EventLog.SourceExists( "MySource" )) { System.Diagnostics.EventLog.CreateEventSource( "MySource", "MyNewLog" ); } eventLog1.Source = "MySource"; eventLog1.Log = "MyNewLog"; websocketServer = new Server.WebsocketServer(); websocketServer.LogMessage += WebsocketServer_LogMessage; websocketServer.Start( "http://localhost:2645/tryservice/" ); Console.Read(); } private static void WebsocketServer_LogMessage( object sender, Server.WebsocketServer.LogMessageEventArgs e ) { // eventLog1.WriteEntry( e.Message ); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine( e.Message ); Console.ForegroundColor = ConsoleColor.White; } public class WebsocketServer { public event OnLogMessage LogMessage; public delegate void OnLogMessage(Object sender, LogMessageEventArgs e); public class LogMessageEventArgs : EventArgs { public string Message { get; set; } public LogMessageEventArgs(string Message) { this.Message = Message; } } public bool started = false; public async void Start(string httpListenerPrefix) { HttpListener httpListener = new HttpListener(); httpListener.Prefixes.Add(httpListenerPrefix); httpListener.Start(); LogMessage(this, new LogMessageEventArgs("Listening...")); started = true; while (started) { HttpListenerContext httpListenerContext = await httpListener.GetContextAsync(); if (httpListenerContext.Request.IsWebSocketRequest) { ProcessRequest(httpListenerContext); } else { httpListenerContext.Response.StatusCode = 400; httpListenerContext.Response.Close(); LogMessage(this, new LogMessageEventArgs("Closed...")); } } } public void Stop() { started = false; } private List<string> _printers = new List<string>(); public List<string> Printers { get { _printers.Clear(); foreach (string imp in System.Drawing.Printing.PrinterSettings.InstalledPrinters) { _printers.Add(imp); } return _printers; } } private async void ProcessRequest(HttpListenerContext httpListenerContext) { WebSocketContext webSocketContext = null; try { webSocketContext = await httpListenerContext.AcceptWebSocketAsync(subProtocol: null); LogMessage(this, new LogMessageEventArgs("Connected")); } catch (Exception e) { httpListenerContext.Response.StatusCode = 500; httpListenerContext.Response.Close(); LogMessage(this, new LogMessageEventArgs(String.Format("Exception: {0}", e))); return; } WebSocket webSocket = webSocketContext.WebSocket; try { while (webSocket.State == WebSocketState.Open) { ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]); WebSocketReceiveResult result = null; using (var ms = new System.IO.MemoryStream()) { do { result = await webSocket.ReceiveAsync(buffer, CancellationToken.None); ms.Write(buffer.Array, buffer.Offset, result.Count); } while (!result.EndOfMessage); ms.Seek(0, System.IO.SeekOrigin.Begin); if (result.MessageType == WebSocketMessageType.Text) { using (var reader = new System.IO.StreamReader(ms, Encoding.UTF8)) { var r = System.Text.Encoding.UTF8.GetString(ms.ToArray()); var t = Newtonsoft.Json.JsonConvert.DeserializeObject<Datos>(r); bool valid = true; byte[] toBytes = Encoding.UTF8.GetBytes("Error..."); ; if (t != null) { if (t.Impresora.Trim() == string.Empty) { var printers = ""; Printers.ForEach(print => { printers += print + "\n"; }); toBytes = Encoding.UTF8.GetBytes("No se Indicó la Impresora\nLas Impresoras disponibles son:\n" + printers); valid = false; } else if(!Printers.Contains(t.Impresora)) { var printers = ""; Printers.ForEach(print => { printers += print + "\n"; }); toBytes = Encoding.UTF8.GetBytes("Impresora no valida\nLas Impresoras disponibles son:\n" + printers); valid = false; } if (t.nombre.Trim() == string.Empty) { toBytes = Encoding.UTF8.GetBytes("No se Indicó el nombre del Documento"); valid = false; } if (t.code== null) { toBytes = Encoding.UTF8.GetBytes("No hay datos para enviar a la Impresora"); valid = false; } if (valid && print.RawPrinter.SendStringToPrinter(t.Impresora, t.code, t.nombre)) { LogMessage(this, new LogMessageEventArgs(String.Format("Enviado: {0} => {1} => {2}", t.Impresora, t.nombre, t.code))); toBytes = Encoding.UTF8.GetBytes("Correcto..."); } await webSocket.SendAsync(new ArraySegment<byte>(toBytes, 0, int.Parse(toBytes.Length.ToString())), WebSocketMessageType.Binary, result.EndOfMessage, CancellationToken.None); } else { toBytes = Encoding.UTF8.GetBytes("Error..."); await webSocket.SendAsync(new ArraySegment<byte>(toBytes, 0, int.Parse(toBytes.Length.ToString())), WebSocketMessageType.Binary, result.EndOfMessage, CancellationToken.None); } } } } } } catch (Exception e) { LogMessage(this, new LogMessageEventArgs(String.Format("Exception: {0} \nLinea:{1}", e, e.StackTrace))); } finally { if (webSocket != null) webSocket.Dispose(); } } } public class Datos { public enum TipoArchivo { zpl, pdf, doc, json, text} public string nombre { get; set; } public string code { get; set; } public TipoArchivo Tipo { get; set; } = TipoArchivo.text; public string Impresora { get; set; } = ""; } } ``` the RAWPrinterClass [link](https://stackoverflow.com/a/12842174/7782179): ``` public class RawPrinter { // Structure and API declarions: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class DOCINFOA { [MarshalAs(UnmanagedType.LPStr)] public string pDocName; [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile; [MarshalAs(UnmanagedType.LPStr)] public string pDataType; } [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, ref IntPtr hPriknter, IntPtr pd); [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool ClosePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In(), MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di); [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool EndDocPrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool StartPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool EndPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, ref Int32 dwWritten); // SendBytesToPrinter() // When the function is given a printer name and an unmanaged array // of bytes, the function sends those bytes to the print queue. // Returns true on success, false on failure. public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount, string DocName = "") { Int32 dwError = 0; Int32 dwWritten = 0; IntPtr hPrinter = new IntPtr(0); DOCINFOA di = new DOCINFOA(); bool bSuccess = false; // Assume failure unless you specifically succeed. di.pDocName = string.IsNullOrEmpty(DocName) ? "My C#.NET RAW Document" : DocName; di.pDataType = "RAW"; // Open the printer. if (OpenPrinter(szPrinterName.Normalize(), ref hPrinter, IntPtr.Zero)) { // Start a document. if (StartDocPrinter(hPrinter, 1, di)) { // Start a page. if (StartPagePrinter(hPrinter)) { // Write your bytes. bSuccess = WritePrinter(hPrinter, pBytes, dwCount, ref dwWritten); EndPagePrinter(hPrinter); } EndDocPrinter(hPrinter); } ClosePrinter(hPrinter); } // If you did not succeed, GetLastError may give more information // about why not. if (bSuccess == false) { dwError = Marshal.GetLastWin32Error(); } return bSuccess; } public static bool SendFileToPrinter(string szPrinterName, string szFileName) { // Open the file. FileStream fs = new FileStream(szFileName, FileMode.Open); // Create a BinaryReader on the file. BinaryReader br = new BinaryReader(fs); // Dim an array of bytes big enough to hold the file's contents. Byte[] bytes = new Byte[fs.Length]; bool bSuccess = false; // Your unmanaged pointer. IntPtr pUnmanagedBytes = new IntPtr(0); int nLength = 0; nLength = Convert.ToInt32(fs.Length); // Read the contents of the file into the array. bytes = br.ReadBytes(nLength); // Allocate some unmanaged memory for those bytes. pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); // Copy the managed byte array into the unmanaged array. Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength); // Send the unmanaged bytes to the printer. bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength); // Free the unmanaged memory that you allocated earlier. Marshal.FreeCoTaskMem(pUnmanagedBytes); return bSuccess; } public static bool SendStringToPrinter(string szPrinterName, string szString, string DocName = "") { IntPtr pBytes = default(IntPtr); Int32 dwCount = default(Int32); // How many characters are in the string? dwCount = szString.Length; // Assume that the printer is expecting ANSI text, and then convert // the string to ANSI text. pBytes = Marshal.StringToCoTaskMemAnsi(szString); // Send the converted ANSI string to the printer. var t= SendBytesToPrinter(szPrinterName, pBytes, dwCount, DocName); Marshal.FreeCoTaskMem(pBytes); return t; } } ```
68,800,162
I got this code from <https://github.com/aws/aws-lambda-go/blob/master/events/README_ApiGatewayEvent.md> : ``` package main import ( "context" "fmt" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func handleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { fmt.Printf("Processing request data for request %s.\n", request.RequestContext.RequestID) fmt.Printf("Body size = %d.\n", len(request.Body)) fmt.Println("Headers:") for key, value := range request.Headers { fmt.Printf(" %s: %s\n", key, value) } log.Printf("%v", request.Body) return events.APIGatewayProxyResponse{Body: request.Body, StatusCode: 200}, nil } func main() { lambda.Start(handleRequest) } ``` I only added: the log: log.Printf("%v", request.Body) When I compile and use the lambda test GUI, I send this: ``` {"body":"[{\"id\":\"123\"}]"} ``` and the log in the tab shows this: ``` 2021/08/16 08:51:50 [{"id":"123"}] ``` However, when I do this: ``` curl https://qmk743l1p0.execute-api.us-east-1.amazonaws.com/default/simplegateway -d '{"body":"[{\"id\":\"123\"}]"}' --header "Content-Type: application/json" ``` I get this in the CloudWatch logs: ``` 2021/08/16 08:56:07 {"body":"[{\"id\":\"123\"}]"} ``` I have no idea why request.body would have two different values when going through the http gateway. How do I get the intended "body" in both the lambda test GUI and in through the http API gateway?
2021/08/16
[ "https://Stackoverflow.com/questions/68800162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019965/" ]
This happens because your handler has the same signature in both cases, but what that implies differs based on what is proxying your request. When you send the request from the Lambda GUI, the body gets unmarshaled into the `events.APIGatewayProxyRequest` straight away. That struct has a field defined as: ``` Body string `json:"body"` ``` So when you send the payload `{"body":"[{\"id\":\"123\"}]"}`, `json.Unmarshal` populates that field with the value of the JSON `body` property, which is `[{"id":"123"}]` When the same request is proxied through the API Gateway, the Gateway constructs a AWS event that contains your payload **as-is**, so it will probably look like: ``` { ... "body": "{\"body\":\"[{\"id\":\"123\"}]\"}\" } ``` And only then the event is unmarshaled into the `events.APIGatewayProxyRequest` struct, resulting in the `Body` field having the value `{"body":"[{\"id\":\"123\"}]"}`.
Though i am not familiar with the lambda GUI i suspect that there you input the json representation of the request (with headers and body), but when sending via curl, you don't need to wrap the body (-d), so just send it like this `[{\"id\":\"123\"}]` as this is what the body should contain.
166,849
``` Fatal error: Uncaught TypeError: Argument 1 passed to FDB\FreeSamples\Helper\SampleCategories::__construct() must be an instance of FDB\FreeSamples\Model\Checkout\Type\Onepage, instance of Magento\Checkout\Model\Type\Onepage\Interceptor given, ``` Model ``` namespace FDB\FreeSamples\Model\Checkout\Type; class Onepage extends \Magento\Checkout\Model\Type\Onepage { } ``` I am attempting to the load class in a helper: ``` public function __construct( \FDB\FreeSamples\Model\Checkout\Type\Onepage $onePage ) { $this->_onePage = $onePage; parent::__construct($context); } ```
2017/03/30
[ "https://magento.stackexchange.com/questions/166849", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/49811/" ]
Ok, so I discovered a little more about this but as @circlesix pointed out it's not possible to use these LESS mixins nested like this. Furthermore if you look at the `<head>` section of Magento you'll notice that the *styles-l.css* is loaded after the mobile styles, i.e. *styles-m.css*. ``` <link rel="stylesheet" type="text/css" media="all" href="http://example.com/pub/static/frontend/Magento/luma/en_US/css/styles-m.css" /> <link rel="stylesheet" type="text/css" media="screen and (min-width: 768px)" href="http://example.com/pub/static/frontend/Magento/luma/en_US/css/styles-l.css" /> ``` So *styles-l.css* is only loaded on screens 768px and over in width, saving mobile devices from having to load it. If you write a LESS rule like normal without any of the mixins it will be put into both of these files and anything you add to with the `media-width()` mixin will be added before it, and therefore overwritten. You can use the `@media-common = true` separation variable to output it only to *styles-m.css* before any of the media query rules are added. This way it will be applied to both desktop and mobile devices, as both load *styles-m.css*. `media-width()` mixins under 768px are only put in *styles-m.css*, vice-a-versa any `media-width()` mixins 768px over in width is only put in *styles-l.css*. So, I think the best practice is to put all your common styles within `& when (@media-common = true) {}` and use the `media-width()` mixin for any css rules which are specific to a particular width. For instance, below is what I went with in the end... ``` // // Common // _____________________________________________ & when (@media-common = true) { .logo img { width: 125px; height: 29px; } } // // Mobile // _____________________________________________ //.media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__m) {} // // Desktop // _____________________________________________ .media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) { .logo img { width: 177px; height: 41px; } } ``` It's the same approach used by Magento in: * *app/design/frontend/Magento/blank/web/css/source/\_navigation.less* * *vendor/magento/theme-frontend-blank/web/css/source/\_navigation.less*
Using the the core files as an example for how to use that mixin, i don't think you can have them nested in that way (even though i think that is the preferred way to use media queries). Looking at a file in core like **vendor/magento/theme-frontend-luma/Magento\_Theme/web/css/source/module/\_collapsible\_navigation.less** ``` // // Desktop // _____________________________________________ .media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) { .block-collapsible-nav { .title { &:extend(.abs-visually-hidden-desktop all); } } } // // Mobile // _____________________________________________ .media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__m) { .block-collapsible-nav { left: 0; position: absolute; top: -21px; width: 100%; z-index: 5; .title { &:extend(.abs-toggling-title-mobile all); } .content { border-bottom: @border-width__base solid @border-color__base; display: none; &.active { display: block; } } } } ``` You see that each css class is repeated into a media query container. I don't know if there is another way to do this, but i have stuck to this pattern and it works. One thing that helps is to have very small `.less` files in your theme, as it reduces that amount of scrolling you have to do to find what you are looking for.
8,549
In Mark 11, as Jesus is entering the temple he stops to inspect a fig tree to find out if it has any fruit. It doesn't, which Mark tells us is "because it was not the season for figs." Jesus then proceeds to curse the tree, saying "May no one ever eat from from you again." The whole episode strikes me as rather odd, but especially the part where Mark explains that it wasn't the season for figs. My expectation reading the story is that it has no figs *despite* it being the season, but Mark's statement upends this expectation, leaving me to ponder: why would Jesus look for fruit on a tree when it wasn't the season for bearing fruit?
2014/03/11
[ "https://hermeneutics.stackexchange.com/questions/8549", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/33/" ]
The fig tree cursing narrative is found in Matthew's and Mark's gospels. Mark's account varies in sequence from Matthew's account as it is written in two sections: First, after departing the temple, Jesus sees the fig tree **in leaf**, but no fruit found, followed by cursing [Mark 11:12-14]. Second, after departing from temple (Where Jesus drives out money changers), Jesus and disciples find same fig tree withered, then Jesus teaches lesson on prayer [Mark 11:20-25]. These two sections provided an acted out prophetic lesson to Christ's disciples as they were also spoken in parabolic forms also. Before getting to the heart of the answer, we must examine a few other linking passages. A few years earlier John the Baptist who came in the spirit of Elijah, foretold Israel's demise with these words: *Mat 3:8 **Bear fruit** in keeping with repentance. Mat 3:9 And do not presume to say to yourselves, 'We have Abraham as our father,' for I tell you, God is able from these stones to raise up children for Abraham. Mat 3:10 Even now the axe is laid to the root of the trees. Every tree therefore that **does not bear good fruit is cut down and thrown into the fire.*** It would seem fitting that after the cursed tree of Mark 11 had withered its only value laid in being burned. **Parable of the barren fig tree.** *Luk 13:6 And he told this parable: "A man had a fig tree planted in his vineyard, and he came seeking fruit on it and found none. Luk 13:7 And he said to the vinedresser, 'Look, for **three years now** I have come seeking fruit on this fig tree, and I find none. Cut it down. Why should it use up the ground?' Luk 13:8 And he answered him, 'Sir, let it alone this year also, until I dig around it and put on manure. Luk 13:9 Then if it should bear fruit next year, well and good; but if not, you can **cut it down**.'"* These parables unfolds three years of a planter's (The father's) frustration after finding no fruit (Repentance). The vine dresser (The Son) appeals to need of further cultivation (ministry of Holy Spirit), and if not effective, tree is to be burned (wrath of God). It's no coincidence that the three years mentioned summed up Christ's earthly ministry. **Answer:** In his work *New Testament Documents: Are They Reliable* scholar F.F. Bruce points out that given the time frame of Mark 11, being late March/early April, it was not uncommon for people to seek a knob like fruit called taqsh from the broad leaf displaying yet too early for fig producing fig tree. *NT Doc: Are They Reliable F.F. Bruce. Ch 5: The other miracle is the cursing of the barren fig tree (Mk. xi. '2 ff.), a stumblingblock to many. They feel that it is unlike Jesus, and so someone must have misunderstood what actually happened, or turned a spoken parable into an acted miracle, or something like that. Some, on the other hand, welcome the story because it shows that Jesus was human enough to get unreasonably annoyed on occasion. It appears, however, that a closer acquaintance with fig trees would have prevented such misunderstandings. 'The time of figs was not yet,' says Mark, for it was just before Passover, about six weeks before the fully formed fig appears. The fact that Mark adds these words shows that he knew what he was talking about. When the fig leaves appear about the end of March they are accompanied by a crop of small knobs, called **taqsh** by the Arabs, a sort of forerunner of the real figs. These taqsh are eaten by peasants and others when hungry. They drop off before the real fig is formed. But if the leaves appear unaccompanied by taqsh, there will be no figs that year. So it was evident to our Lord, when He turned aside to see if there were any of these taqsh on the fig tree to assuage His hunger for the time being, that the absence of the taqsh meant that there would be no figs when the time for figs came. For all its fair show of foliage, it was a fruitless and hopeless tree.'* According to Bruce, it was not actual figs Jesus sought, it was the taqsh, an edible sign that the tree would in fact bear fruit that season. Mark wisely inserted the note on figs not yet being in season. The people of the far east would have immediately known of the taqsh Jesus looked for. Though there is a puzzling element even given this information and linking parables. Jesus says in Mark 11:14: *"May no one ever eat fruit from you again"*. These word may be summed up in the words of the JFB Commentary notes on this verse: *Those words did not make the tree barren, but sealed it up in its own barrenness*. In other words, the cursed fig tree was the emblem of the unrepentant Jewish nation. And because they knew not the time of their Messiah's visitation it was impossible for them to bear fruit, or if it did its fruit would be bad. If room would allow I'd show why Jesus cleansed the temple, and how Jesus' lesson on prayer, and his reference to the mountain being thrown into the sea relates to the symbolism of Revelation 8:8, where a huge mountain **ablaze** is cast into the sea. It directly relates to why Jesus cursed the fig tree and the subsequent burning of Jerusalem in AD 70.
Before entering Jerusalem Jesus sent His disciples to Bethphage to find things which were to be brought to Him (Matthew 21:1, Mark 11:1, and Luke 19:29). Bethphage means "house of unripe figs" [[G967-Bethphage]](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=G967&t=KJV). Figs picked too early will not ripen and a "house of unripe figs" is a place where figs taken from the tree too soon would be kept. The first figs are actually from last years growth and they and the leaves both appear in the spring: > > *And seeing in the distance a fig tree [covered] with leaves, He went to see if He could find any [fruit] on it [for in the fig tree the fruit appears at the same time as the leaves]. But when He came up to it, He found nothing but leaves, for the fig season had not yet come. (Mark 11:13 AMPC)* > > > Mark records the "season" for figs had not yet come. Season is καιρὸς – kairos. When used in an agricultural context it means harvest time [[G2540-kairos]](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=G2540&t=KJV). For example: > > *Then he began to speak to them in parables: “A man planted a vineyard. He put a fence around it, dug a pit for its winepress, and built a watchtower. Then he leased it to tenant farmers and went on a journey. At harvest time (καιρῷ) he sent a slave to the tenants to collect from them his portion of the crop. (Mark 12:1-2 NET)* > > > The man did not attempt to collect his portion when the leaves appeared or when the grapes first appeared. He waited until the fruit had ripened on the vine and was "in season." Leaves by themselves are never a sign figs are ripe or "in season." Depending on climate two additional months are needed before they should be harvested (or eaten). In Israel the first crop is normally ripe in June. They would never be ripe at the time of Passover. While someone who is hungry would normally look for figs which were ripe (either on the tree or dried), Mark makes it clear Jesus sought figs which were "out of season." These figs would be unripe and not very good to eat. Nevertheless, the existence of Bethphage, a house of unripe figs, shows that Jesus is not alone in seeking out unripe figs. There are others who actually harvested them raising the possibility the tree which Jesus went to had produced fruit which someone else had already removed and taken to Bethphage, the house of unripe figs. Matthew describes a similar event: > > *After noticing a fig tree by the road he went to it, but found nothing on it except leaves. He said to it, “Never again will there be fruit from you!”… (Matthew 21:19 NET)* > > > In addition to making no mention of season, there is a difference between taking and eating the fruit: > > Mark: *He said to it, “May no one ever eat fruit from you again."... (11:14 NET)* > > > Matthew: *…He said to it, “Never again will there be fruit from you!”... (21:19 NET)* > > > Each conveys a similar message from a different perspective. Matthew places the emphasis on the **tree** never again producing fruit. Immediately it withers; this tree will never again produce figs. In Mark Jesus states a **person** will never again eat fruit from this tree (and the tree is observed by Peter the following day). The command in Mark does not necessarily require the tree to die. For example, a similar command was given in the Garden of Eden: > > *Then the LORD God commanded the man, “You may freely eat fruit from every tree of the orchard, but you must not eat from the tree of the knowledge of good and evil, for when you eat from it you will surely die.” (Genesis 2:16-17 NET)* > > > As in Mark this tree was never to be eaten from (or eaten from again). Significantly, leaves from a fig tree are also found in the Genesis account: > > *Then the eyes of both of them opened, and they knew they were naked; so they sewed fig leaves together and made coverings for themselves. (Genesis 3:7 NET)* > > > The Gospel events highlighting fig leaves and missing fruit are deliberate actions by Jesus to recall the history of man. The first man and woman were not to eat fruit from a certain tree and after they ate they used leaves from a fig tree to cover themselves. The common element is fig leaves calling attention to the first man and woman who took fruit which was supposed to be left on the tree and used leaves from a fig tree to try and cover themselves. The timing of the result of Jesus speaking to the trees also follows the events of the Garden of Eden. The fruit on the tree remained, but no one would ever again eat from this tree. The leaves which they used to make aprons became unnecessary on the same day after the LORD God made tunics of animal skins: > > *The Lord God made garments from skin for Adam and his wife, and clothed them. (Genesis 3:21)* > > >
589,520
I use the following code to call a wcf service. If i call a (test) method that takes no parameters, but returns a string it works fine. If i add a parameter to my method i get a wierd error: > > {"ExceptionDetail":{"HelpLink":null,"InnerException":null,"Message":"The token '\"' was expected but found '''.","StackTrace":" at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)","Type":"System.Xml.XmlException"},"ExceptionType":"System.Xml.XmlException","Message":"The token '\"' was expected but found '''.","StackTrace":" at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"} > > > My jquery looks like this, but i tried changing the actual data which i send as a string serialized json (as you can see) to a pure json object with the same sad result. ``` $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "ajax/Statistics.svc/Get7DaysStatistics", dataType: "json", data: "{'customerId': '2'}", timeout: 10000, success: function(obj) { updateStatistics(obj.d); }, error: function(xhr) { if (xhr.responseText) $("body").html(xhr.responseText); else alert('unknown error'); return; } }); ``` The wcf service looks like this: ``` [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), OperationContract] public string Get7DaysStatistics(string customerId) { Debug.WriteLine(customerId); return "Test done"; } ``` It's placed in a a class with the following attributes: ``` [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] ``` I won't list the configuration in the web.config to keep this long message "short" but i can post it if anybody thinks they can use it - i just want to stress that i CAN call a method and get a result - string or even a json object i can read from as long as i DON'T pass any data to the wcf service.
2009/02/26
[ "https://Stackoverflow.com/questions/589520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
I have only ever thought that posting is essential for username and password log on functionality so this is the way I encode the JSon parameters I send to the web service... Here is the Webservice Contract.. ```cs [ServiceContract] public interface ILogonService { [OperationContract] [WebInvoke( Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json )] string Logon(string un, string pw); } ``` Here is the JQuery (Note the use of " and ' is important!) ``` $.ajax({ type: 'POST', url: "/LogonService.svc/Logon", data: '{ "un": "' + $('#un').val() + '", "pw": "' + $('#pw').val() + '"}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { } }); ```
I think on your operation you need this attribute: ``` [WebInvoke(Method="POST", BodyStyle=WebMessageBodyStyle.Wrapped, ResponseFormat=WebMessageFormat.Json )] ``` See [jQuery AJAX calls to a WCF REST Service](http://www.west-wind.com/weblog/posts/324917.aspx) for more info.
11,386,843
This is a PHP/Apache question... 1. I have the following code. In particular I would like to emphasize the following: ``` // store email in session variable $_SESSION["jobseeker_email"] = $_POST["jobseeker_email"]; // perform redirect $target = util_siblingurl("jobseekermain.php", true); header("Location: " . $target); exit; /* ensure code below does not executed when we redirect */ ``` which is where the problem lies. When I execute this code on localhost it works fine, but then when I execute it on the remote server (which is an ipage.com hosted site), I do not get the desired outcome. In fact, when the header("Location: $target); part runs I see a blank page (and no redirect). It's as though something was being output before the call to header(), but this is not the case, as I've checked it. So why is it not working? 1. If I comment out the part that invokes header() and then exit, I am able to perform either an html redirect or a javascript redirect. However, when I do this I lose my session variable $\_SESSION["jobseeker\_email"]. I cannot understand why this happens. Any help with these issues would be greatly appreciated as I need to perform a redirect and still retain the session state from the former page, and all of this on a server (not just on localhost). ``` <?php session_start(); require_once('include/connect.php'); require_once('include/util.php'); util_ensure_secure(); if (isset($_GET['logout'])) { session_destroy(); // restart session header("Location: " . util_selfurl(true)); } function do_match_passwords($password1, $password2) { return strcmp($password1, $password2) == 0; } function valid_employer_login($email, $password) { global $mysqli; global $employer_error; $query = "SELECT passwd FROM Employer WHERE email = '" . $mysqli->escape_string($email) . "'"; $result = $mysqli->query($query); util_check_query_result($query, $result); $invalid_credentials = false; if ($result->num_rows == 0) { $invalid_credentials = true; } else { $row = $result->fetch_assoc(); $retrieved_password = $row["passwd"]; if (!do_match_passwords($password, $retrieved_password)) $invalid_credentials = true; } if ($invalid_credentials) { $employer_error = "Invalid credentials."; return false; } return true; } function valid_jobseeker_login($email, $password) { global $mysqli; global $jobseeker_error; $query = "SELECT passwd FROM JobSeeker WHERE email = '" . $mysqli->escape_string($email) . "'"; $result = $mysqli->query($query); util_check_query_result($query, $result); $invalid_credentials = false; if ($result->num_rows == 0) { $invalid_credentials = true; } else { $row = $result->fetch_assoc(); $retrieved_password = $row["passwd"]; if (!do_match_passwords($password, $retrieved_password)) $invalid_credentials = true; } if ($invalid_credentials) { $jobseeker_error = "Invalid credentials."; return false; } return true; } if (isset($_POST["employer_submitted"])) { global $error; // check whether specified username and password have been entered correctly if (valid_employer_login($_POST["employer_email"], $_POST["employer_password"])) { // store email in session variable $_SESSION["employer_email"] = $_POST["employer_email"]; // perform redirect $target = util_siblingurl("jobseekermain.php", true); header("Location: " . $target); exit; /* ensure code below does not executed when we redirect */ } } if (isset($_POST["jobseeker_submitted"])) { global $error; // check whether specified username and password have been entered correctly if (valid_jobseeker_login($_POST["jobseeker_email"], $_POST["jobseeker_password"])) { // store email in session variable $_SESSION["jobseeker_email"] = $_POST["jobseeker_email"]; // perform redirect $target = util_siblingurl("jobseekermain.php", true); header("Location: " . $target); exit; /* ensure code below does not executed when we redirect */ } } ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Work Net: Sign In</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="container"> <h1>Work Net: Sign In</h1> <div id="content"> <ul> <li> <h2>Employers</h2> <p><a href="accountcreate.php?accounttype=employer">Create new employer account.</a></p> <form method="post" action="<?php util_selfurl(true); ?>"> <table> <tr> <td>E-mail:</td> <td><input type="text" name="employer_email" value="<?= htmlentities(util_setvalueorblank($_POST['employer_email'])); ?>" /> </tr> <tr> <td>Password:</td> <td><input type="password" name="employer_password" value="<?= htmlentities(util_setvalueorblank($_POST['employer_password'])); ?>" /></td> </tr> </table> <?php if (isset($employer_error)) echo "<p style=\"color: red;\">" . htmlentities($employer_error) . "</p>"; ?> <input type="hidden" name="employer_submitted" /> <input type="submit" value="Sign In" /> </form> <p><a href="forgottenpassword.php?accounttype=employer">Forgotten Employer Password.</a></p> </li> <li> <h2>Job Seekers</h2> <p><a href="accountcreate.php?accounttype=jobseeker">Create new job seeker account.</a></p> <form method="post" action="<?php util_selfurl(true); ?>"> <table> <tr> <td>E-mail:</td> <td><input type="text" name="jobseeker_email" value="<?= htmlentities(util_setvalueorblank($_POST['jobseeker_email'])); ?>" /> </tr> <tr> <td>Password:</td> <td><input type="password" name="jobseeker_password" value="<?= htmlentities(util_setvalueorblank($_POST['jobseeker_password'])); ?>" /></td> </tr> </table> <?php if (isset($jobseeker_error)) echo "<p style=\"color: red;\">" . htmlentities($jobseeker_error) . "</p>"; ?> <input type="hidden" name="jobseeker_submitted" /> <input type="submit" value="Sign In" /> </form> <p><a href="forgottenpassword.php?accounttype=jobseeker">Forgotten Job Seeker Password.</a></p> </li> </ul> </div> <div id="footer"> <p> <?php include('markup/footer.php'); ?> </p> </div><!-- end #footer --> </div><!-- end #container --> </body> </html> ```
2012/07/08
[ "https://Stackoverflow.com/questions/11386843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1510578/" ]
```css h1, h2, h3, h4, h5, h6 { scroll-margin-top: 80px; } ``` Got this idea from React docs.
Everyone else gave CSS answers but the question asked for JS @assmmahmud's answer works with one small tweak: gotoSpecificPosition needs to changed to offsetAnchor in the first statement. This was very helpful in adjusting all id links for a sticky header. ``` /* go to specific position if you load the page directly from address bar */ var navbarHeight = document.getElementById('mynavbar').clientHeight; function offsetAnchor() { if (window.location.hash.length !== 0) { window.scrollTo(window.scrollX, window.scrollY - navbarHeight ); } } /* Captures click events on all anchor tag with a hash tag */ $(document).on('click', 'a[href^="#"]', function(event) { // Click events are captured before hashchanges. Timeout // causes offsetAnchor to be called after the page jump. window.setTimeout(function() { offsetAnchor(); }, 0); }); window.setTimeout(offsetAnchor, 0); ```
8,814,472
What is the simplest way to create an `<a>` tag that links to the previous web page? Basically a simulated back button, but an actual hyperlink. Client-side technologies only, please. **Edit** Looking for solutions that have the benefit of showing the URL of the page you're about to click on when hovering, like a normal, static hyperlink. I'd rather not have the user looking at `history.go(-1)` when hovering on a hyperlink. Best I've found so far is: ```html <script> document.write('<a href="' + document.referrer + '">Go Back</a>'); </script> ``` Is `document.referrer` reliable? Cross-browser safe? I'll be happy to accept a better answer.
2012/01/11
[ "https://Stackoverflow.com/questions/8814472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/835805/" ]
And another way: ```html <a href="javascript:history.back()">Go Back</a> ```
The easiest way is to use `history.go(-1);` Try this: ```html <a href="#" onclick="history.go(-1)">Go Back</a> ```
50,011,443
I'm using tslint, and got the error. ``` 'myVariable' is declared but its value is never read. ``` I went to the website that documents the rules <https://palantir.github.io/tslint/rules/> and searched for the string `is declared but its value is never read` but didn't find that text. While I can and did look for settings that might be tied to this error, it shouldn't be a guessing game. **What is the configuration change needed to suppress/stop this error?** Just as importantly, **when I get an error in tslint that says "this happened" how can I find what setting is used to configure or change the tslint behavior on how to handle that error?** I also did a search on the website (google search I used was) ``` site:palantir.github.io is declared but its value is never read ``` but a direct hit did not appear, so the answer might be on the palantir.github.io website but I just didn't (yet) find it. **How do others find the tslint variable/configuration settings that change to suppress a particular error?** Please refrain from suggesting I comment out the code that is causing the problem. I'm looking for an answer to my more general question as well as to the specific question. Thank you.
2018/04/24
[ "https://Stackoverflow.com/questions/50011443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3281336/" ]
Add this line just before the line which causes the error: ``` /* tslint:disable:no-unused-variable */ ``` You will no longer receive the tslint error message. This is a better solution than turning off the error for you whole codebase in tslint.conf because then it wouldn't catch variables that really aren't used.
Another way to avoid this is to create a get-method for every variable you have, like this: ``` get variablename():variabletype{return this.variablename;} ```
40,716,356
I am trying to convert `varchar` field which is in format `dd.mm.yyyy` to date type field in SQL SERVER 2008. I used approach like `convert(datetime, left(yourDateField, 2) + '01 20' + right(yourDateField, 4), 100)` but unable to so. Is there any way to convert `Varchar` string which is in format `dd.mm.yyyy` to `Date type` in SQL?
2016/11/21
[ "https://Stackoverflow.com/questions/40716356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5566276/" ]
``` select convert(date,dateField,104) from tab ```
If Your date field is not in proper datetime format then this type of Out of range value error will occurred. If your date field is in proper datetime format then you can easily convert varchar field to datetime format. see example: ``` select CONVERT(datetime,'2016-11-21 01:02:12') select CONVERT(datetime,'2016-11-31 01:02:12') select CONVERT(datetime,'2016-11-21 00:00:01 PM') ``` In above Example,First query get easily converted to datetime but second and third query will give error as out of range value. because 31 Nov is invalid date. and 00:00:00 PM is also wrong date format. IF your field is in correct format then simply try any one of the below query ``` DECLARE @String VARCHAR(100)= '21.11.2016'; SELECT CONVERT(DATETIME,@String,104) SELECT CONVERT(DATETIME,@String,103) ``` Hope so, you get what I am trying to say.
359,333
I created a windows service that's basically a file watcher that wont run unless a user is logged into the machine its on. The service is running on a Windows Server 2003 machine. It is designed to move the files that are put into one directory into a different directory based on keywords in the file names, but none of the files move until i log on, then all the files move at once.
2008/12/11
[ "https://Stackoverflow.com/questions/359333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You probably have to set the service to log on as a spesific user, try going into services, doubleclick the service and select "log in as account", and then provide your account details (domain\username and password). The LocalService account has extensive rights, but may lack the rights to spesific users files/folders for instance. You could alternatively try to grant file rights to the LocalService account spesifically. I would however try the "log in as" trick first, as it's a 1 minute job. If it works you could create a spesific account to run the service as, alternatively grant rights to LocalSystem. Btw: If it's networked files you might try the NetworkedService account.
There has to be some setup problem with your service. Windows Server doesn't have a problem running applications without a user logged in (otherwise, scheduled tasks would be a lot less useful). How did you *install* the service?
43,947,459
The problem is that it disables text editing but in case 1 of the Switch when you have to activate it again it does not This is the code I am using. ``` public class ejemolo extends AppCompatActivity { String[] Items = { "Dc amps a Kw", "Ac una fase amp a kw ", "Ac trifasicaamps a kw (linia a linea de voltaje)", "Ac trifasica amps a kw (linia a voltaje neutral)", }; Spinner s1; private String[] listOfObjects; EditText ampEditText , voltageEditText , powerfactorEditText ; TextView text1 , text2 , text3, text4 ; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ejemolo); FloatingActionButton buttonback = (FloatingActionButton)findViewById(R.id.floatingActionButtonback); buttonback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext() , Weight.class); startActivityForResult(intent ,0); } }); FloatingActionButton buttonhome = (FloatingActionButton)findViewById(R.id.floatingActionButtonhome); buttonhome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext() , MainActivity.class); startActivityForResult(intent ,0); } }); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); s1 = (Spinner) findViewById(R.id.spinnerAmp); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Items); s1.setAdapter(adapter); ampEditText = (EditText)findViewById(R.id.ampEditText); voltageEditText = (EditText)findViewById(R.id.voltageEditText); powerfactorEditText = (EditText)findViewById(R.id.powerfactorEditText); //text1=(TextView)findViewById(R.id.tonsTextResult1); //text2=(TextView)findViewById(R.id.tonsTextResult2); listOfObjects = getResources().getStringArray(R.array.object_array4); // final Spinner spinner = (Spinner)findViewById(R.id.spinnerAmp); final android.icu.text.DecimalFormat decimals = new android.icu.text.DecimalFormat("0.00"); /** la cantidad de digitos decimales que se muestra */ // ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, listOfObjects); s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0 : int indzex = s1.getSelectedItemPosition(); powerfactorEditText.setFocusable(false); powerfactorEditText.setEnabled(false); powerfactorEditText.setCursorVisible(false); powerfactorEditText.setKeyListener(null); powerfactorEditText.setBackgroundColor(Color.TRANSPARENT); break; case 1: int index = s1.getSelectedItemPosition(); powerfactorEditText.setEnabled(true); powerfactorEditText.setInputType(InputType.TYPE_CLASS_TEXT); powerfactorEditText.setFocusable(true); powerfactorEditText.setCursorVisible(true); break; } } @Override public void onNothingSelected(AdapterView<?> f } } ``` I want to enable the issue in spinner case 2..
2017/05/12
[ "https://Stackoverflow.com/questions/43947459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7767739/" ]
since OP answered himself I'll just copy-paste a commend made by @lospejos, which I think is a way better solution than the one proposed by OP (just for future generations sake) ``` if (matchesFormat(input)) { /* ok */ } else { /* not ok */ } ``` with a helper method ``` boolean matchesFormat(String input) { return input.matches("[A-F][1-6]"); } ```
I was using && when I should be using ||, fixed. Thanks
27,389,053
I need to replace a certain string with a string blanks that equal removed lines, For instance If I am given ``` 1234567890 ``` I need to replace some of the text with blanks that equals the number of letters removed. ``` 123 8790 ``` or ``` 1234 90 ```
2014/12/09
[ "https://Stackoverflow.com/questions/27389053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4314038/" ]
The standard O(n) multi-precision add goes like this (assuming [0] is LSB): ``` static void Add(byte[] dst, byte[] src) { int carry = 0; for (int i = 0; i < dst.Length; ++i) { byte odst = dst[i]; byte osrc = i < src.Length ? src[i] : (byte)0; byte ndst = (byte)(odst + osrc + carry); dst[i] = ndst; carry = ndst < odst ? 1 : 0; } } ``` It can help to think of this is terms of grade-school arithmetic, which is really all it is: ``` 129 + 123 ----- ``` Remember, where you'd perform an add and carry for each digit, starting from the left (the least-significant digit)? In this case, each digit is a byte in your array. Rather than roll your own, have you considered using the arbitrary-precision [BigInteger](http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx)? It was actually created specifically for .NET's own crypto stuff.
I used a variation of Cory Nelsons answer that creates the array with the correct endian order and returns a new array. This is quite a bit faster then the method first posted.. thanks for the help. ``` private byte[] Increase(byte[] Counter, int Count) { int carry = 0; byte[] buffer = new byte[Counter.Length]; int offset = buffer.Length - 1; byte[] cnt = BitConverter.GetBytes(Count); byte osrc, odst, ndst; Buffer.BlockCopy(Counter, 0, buffer, 0, Counter.Length); for (int i = offset; i > 0; i--) { odst = buffer[i]; osrc = offset - i < cnt.Length ? cnt[offset - i] : (byte)0; ndst = (byte)(odst + osrc + carry); carry = ndst < odst ? 1 : 0; buffer[i] = ndst; } return buffer; } ```
27,150,118
Using below web.xml (with out filter config) i can able to connect with rest services, but after this i couldn't access JSP pages under the servlet.so included a filter for rest easy inside web app tag, but after inserting filter that ear file failed to deploy in JBOSS, so am i handling the filter wrongly here. ``` <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>resteasy.jndi.resources</param-name> <param-value>RNO/routebean/no-interface</param-value> </context-param> <listener> <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class> </listener> <servlet> <servlet-name>Resteasy</servlet-name> <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class> </servlet> <servlet-mapping> <servlet-name>Resteasy</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <filter> <filter-name>Resteasy</filter-name> <filter-class>org.jboss.resteasy.plugins.server.servlet.FilterDispatcher</filter-class> <init-param> <param-name>resteasy.scan</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>Resteasy</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ```
2014/11/26
[ "https://Stackoverflow.com/questions/27150118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2047363/" ]
Try with below code: ``` String date = "2014-11-25"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); Date testDate = null; try { testDate = sdf.parse(date); }catch(Exception ex){ ex.printStackTrace(); } SimpleDateFormat formatter = new SimpleDateFormat("MMM dd,yyyy"); String newFormat = formatter.format(testDate); System.out.println(".....Date..."+newFormat); ```
``` String t = "2014-11-26"; // To parse input string SimpleDateFormat from = new SimpleDateFormat("yyyy-mm-dd", Locale.US); // To format output string SimpleDateFormat to = new SimpleDateFormat("MMMM dd, yyyy", Locale.US); String res = to.format(from.parse(t)); ```
34,156,025
Given 2 tables tbl1 and tbl2. Values in tbl1 should be updated/replaced with values from tbl2 in corresponding rows, if the values in tbl2 aren't NULL or empty strings (''). For any reason, MySQL (and MariaDB) are treating 0 values as it were empty strings or NULL values. Is there any way to get around it? **Edit:** this is just a simple example. In reality I don't know the type of the field. It's an automated PHP script which generates the SET-statements of the query for each field that exists in both tables. That can be string or (tiny)integer fields, text etc. I guess that the script should check then the type of the field and decide how to build the IF-part of the statement depending on the field's type. When I understood the comments right, I can't expect an useful result of a string-like comparison on an integer field. // <http://sqlfiddle.com/#!9/573fc> ``` UPDATE tbl1 t1, tbl2 t2 SET t1.val = IF(t2.val != '' AND t2.val IS NOT NULL, t2.val, t1.val) WHERE t1.id = t2.id; ``` Let's assume for tbl1: ``` id | val 1 | 1 ``` Let's assume for tbl2: ``` id | val 1 | 0 ``` Now I want to update val in tbl1 with the value from val of tbl2, if val in tbl2 isn't NULL neither an empty string. Since val in tbl2 is 0, val in tbl1 should become 0, too. But this doesn't happen. I don't know why. If val in tbl2 is 1, 2, 3 or whatever else different than 0, NULL or '', the query above works fine. The real query is more complex and updates more fields, depending of their values. But this part is the one that bothers me. And since the fields can have different types (strings, integers, dates and so on), I can't really work "around it". **Edit 2/Solution/Work around:** Since I couldn't change much on the code nor the DB, I came up with this solution. It's maybe not the prettiest one and far away from being neat and clean, but it works. ``` UPDATE tbl1 t1, tbl2 t2 SET t1.val = IF((t2.val != '' AND t2.val IS NOT NULL) OR t2.val = '0', t2.val, t1.val) WHERE t1.id = t2.id; ```
2015/12/08
[ "https://Stackoverflow.com/questions/34156025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5320981/" ]
The problem lies in this predicate: ``` t2.val != '' ``` This evalutes to `true` when `t2.val = 0`. This is due to *implicit type coversion*. Check [**this demo**](http://sqlfiddle.com/#!9/b4f76/3) to see for yourslef. The predicate is not necessary, since `val` is of type `tinyint(3)` (according to table definitions given in the provided sql fiddle). So leave it out of your `UPDATE` statement and you're good to go.
You can write your query much more simply as: ``` UPDATE tbl1 t1 JOIN tbl2 t2 ON t1.id = t2.id SET t1.val = t2.val WHERE t2.val IS NOT NULL; ``` A Giorgos explains, the main problem with your query is the comparison of a numeric column to a string -- and the resulting implicit type conversion. However, this version also: * Fixes the logic to use explicit `JOIN` syntax, so the intention of the query is clearer. * Moves the comparison logic to the `WHERE` clause. This makes the query more efficient, because it does not attempt to update all rows.
54,343,083
I have a problem with `range()` or the for loop. in C++, the for loop can be used like this: ``` for(int i=1;i<=100;i*=10){ //lala } ``` My Python script that causes the error looks like this: ``` li = [x for x in range(100, 0, /10)] print(li) ``` I hope to get `li = [100, 10, 1]` How can I achieve this without the use of `li.append ( 100, 10, 1 )`?
2019/01/24
[ "https://Stackoverflow.com/questions/54343083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7369672/" ]
You can simply use a generator expression, like ``` for i in (10 ** x for x in range(2, -1, -1)): print(i) # 100 # 10 # 1 ``` Or, if you want your "power range" to be a reusable function, you can create your own, i.e. ``` def powrange(*args, base=10): for i in range(*args): yield base ** i for i in powrange(2, -1, -1, base=10): print(i) # 100 # 10 # 1 ```
To change make a `log(n)` time complexity loop you need the log function or use while loops to do the job ``` In [10]: import math In [9]: [10**x for x in range( 0,int(math.log10(1000)))] Out[9]: [1, 10, 100] ``` I still think while loops are the way to go