id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23528000
So I have the following code: for y in range(0, height): if (y * 100 / height).is_integer(): print("... ", int(y * 100 / height), "%") height is the number of lines that need to be processed. However, somehow this code doesn't print the correct percentages. If height is 100 it works fine. For 4050 it prints every 2 percentages (0%, 2%, 4%, ...). For 2025 it prints every 4 percentages... Why does this happen? And how can I fix it? A: Not exactly proud of my code, but anyway: last = -1 # Start it as -1, so that it still prints 0%. for y in range(0, height): work = int(y * 100 / height) # I assigned the percentage to a variable for neatness. if work != last: # so it doesn't print the same percent over and over. print("... ", work, "%") last = work # Reset 'last'. This may/may not be completely accurate. But it works The reason you had your problem is from the is_integer() was only true on specific values. Hope this helps!
doc_23528001
so below i'd like to add data stored on firebase into the _cart list , with the method I tried below I got the error The argument type 'List<Menu>' can't be assigned to the parameter type 'Menu'(would like to know why?) , it also contains the ui for where i'd like to map the data from cart list into the dialog sheet: class AddList extends ConsumerWidget { const AddList({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final menuAsync = ref.watch(menuProvider); final model = ref.read(cartProvider); return Scaffold( appBar: AppBar( title: const Text("menu"), ), floatingActionButton: FloatingActionButton( backgroundColor: Colors.black, onPressed: () async { showDialog( context: context, builder: (context) { return AlertDialog( title: const Text("cart"), content: Column( children: const [ ...model.cart.map((item) => Text(item.mealName)), ], ), ); }); }, ), body: menuAsync.when( data: (menu) => Column( children: menu .map( (e) => Card( child: ListTile( title: Text(e.mealName), subtitle: Text(e.price), trailing: IconButton( onPressed: () { model.addProduct(menu);//where im getting error }, icon: const Icon(Icons.add)))), ) .toList(), ), error: (e, s) => Center(child: Text("$e")), loading: () => const Center(child: CircularProgressIndicator())), ); } } below im using changenotifier to modify the cart list: final cartProvider = ChangeNotifierProvider<CartNotifier>((ref) => CartNotifier()); class CartNotifier extends ChangeNotifier { final List<Menu> _cart = []; List<Menu> get cart => _cart; void addProduct(Menu menu) { _cart.add(menu); notifyListeners(); } void removeProduct(Menu menu) { _cart.remove(menu); notifyListeners(); } } how im reading data from firestore : final menuProvider = StreamProvider<List<Menu>>( (ref) => ref.read(addMealRespositoryProvider).menuSearchStream); Stream<List<Menu>> get menuSearchStream => _firestore.collection("menu").snapshots().map( (event) => event.docs.map((e) => Menu.fromFirestore(e)).toList(), ); snippet of my data model: class Menu { String mealName; String price; Menu({ required this.mealName, required this.price, }); Map<String, dynamic> toMap() { return { "mealName": mealName, "price": price, }, factory Menu.fromFirestore(DocumentSnapshot doc) { final map = doc.data() as Map<String, dynamic>; return Menu( mealName: map["mealName"] ?? '', price: map["price"] ?? '', ); } }
doc_23528002
library(XML) city.url = c("http://www.city-data.com/city/Acalanes-Ridge-California.html" city.df = readHTMLTable(city.url, header=T, which=2, stringsAsFactors=F) head(city.df,1) It returns: Males: 568 (50.0%) 1 Females: 569 (50.0%) I'd really appreciate any advice. Dollar General is trying to build in our community and I'm trying to quickly put together an impact analysis to examine what happens to small towns after a Dollar General is built. Thanks!
doc_23528003
device_id account_id is_owner with device_id and account id as conglomerate primary key How can I create an SQL Rule/Constraint such that when the is_owner is true with the conglomerate primary key it will not allow another combination of device_id = (specific device id) account_id = (any account id) is_owner = true since the owner of the device should be only one, and that: device_id = (specific device id) account_id = (any account id) is_owner = false can be 'many' since a device can be shared by the owner account to another account? A: You could use partial index: CREATE UNIQUE INDEX idx_name ON table_name(device_id, account_id) --or only (device_id) if needed WHERE is_owner = true; DBFiddle Demo Example: CREATE TABLE t(device_id INT NOT NULL, account_id INT NOT NULL, is_owner BOOL); CREATE UNIQUE INDEX idx_name ON t(device_id, account_id) WHERE is_owner = true; INSERT INTO t(device_id, account_id, is_owner) VALUES( 1,1, false),(1,1,false); SELECT * FROM t; INSERT INTO t(device_id, account_id, is_owner) VALUES( 1,2, true),(1,2,true); --ERROR: duplicate key value violates unique constraint "idx_name" --DETAIL: Key (device_id, account_id)=(1, 2) already exists.
doc_23528004
def calc_user_feedback(): users = User.objects.all() try: for user in users: fed_qry_up_votes = Model1.objects.filter(author=user).aggregate(Sum('up_vote')) + \ Model2.objects.filter(author=user).aggregate(Sum('up_vote')) + \ Model3.objects.filter(author=user).aggregate(Sum('up_vote')) fed_qry_down_votes = Model1.objects.filter(author=user).aggregate(Sum('down_vote')) + \ Model2.objects.filter(author=user).aggregate(Sum('down_vote')) + \ Model3.objects.filter(author=user).aggregate(Sum('down_vote')) logger.info("Overall user feedback calculated successfully.") except: logger.info("Error processing task: 'Calculate user feedback', please investigate") A: Assuming author has no related_name set on each model: from django.db.models import F, Sum users = ( User.objects.annotate(up_votes_1=Sum("model1_set__up_vote")) .annotate(up_votes_2=Sum("model2_set__up_vote")) .annotate(up_votes_3=Sum("model3_set__up_vote")) .annotate(total=F("up_votes_1") + F("up_votes_2") + F("up_votes_3")) ) Now you can iterate over users and get a total for each one.
doc_23528005
A: You can't really simultaneously use both Windows Auth and Forms Auth (Individual User Accounts), with or without OAuth. There's hacky ways to invalidate what I just said, but they're just that: hacky. Really, the only real approach is go Forms Auth and then connect to LDAP manually to sort of proxy authentication from the domain to Forms Auth (basically, you'd have to create a local user account that represents a domain account). Really, if you need to use simultaneous different forms of auth, the safest and easiest bet is to use separate projects and just share as much of the code as you can, with class libraries, Razor Generator for compiling views, etc. You'd of course have to host each project separately, but you could simply use a subdomain (i.e. internal.mysite.com vs www.mysite.com), or if you got your own network DNS server, you can even map internal requests vs external requests to the two different sites using the same domain.
doc_23528006
When I apply my query the posts returned are for the user role and not the original search term. Here's my query and the loop; $ids = get_users( array( 'role' => 'administrator' , 'fields' => 'ID' ) ); $query = new WP_Query( array( 'author__in' => $ids, ) ); // If the query has data if($query->have_posts() ) : // Post loop while ($query->have_posts() ) : // Setup post data $query->the_post(); ?> <!-- Do HTML markup and template tags here, eg. the_content(), the_title() etc.. --> <h1>You're a post from administrator - <?php the_title(); ?></h1> <?php get_template_part( 'template-parts/content', 'search' ); ?> <?php endwhile; // End "If the query has data" endif; This is on my search.php page ... So for example if I have two posts published from the user type 'administrator' one of those posts is tagged with 'England' and the other is not - so when I go to the search form and enter 'England' I would expect this code to display the one post out of those two however it doesn't, it displays both. So it appears to be just displaying all posts from the user type 'administrator' and ignoring the search term. I've got no idea why that is the case, in my mind this code should be working so if anyone has any advice or can point me in the right direction that would be great! A: You are creating a custom loop so you need to add the search term back into the query args. $query = new WP_Query( array( 'author__in' => $ids, 's' => $_GET['s'] ) );
doc_23528007
. <div class="row"> <div class="col-md-5"> <h1 class="pl-4" style="font-size: 200px;line-height: 2;background-image: url('https://img.freepik.com/free-vector/gradient-wallpaper-background_1159-5356.jpg?size=626&ext=jpg');">10+</h1> <h3>Years of Experience</h3> </div> <div class="col-md-7"> </div> </div> A: Basically applying the CSS found here: h1 { color: white; /* Fallback: assume this color ON TOP of image */ -webkit-background-clip: text; -webkit-text-fill-color: transparent; } <div class="row"> <div class="col-md-5"> <h1 class="pl-4" style="font-size: 200px;line-height: 2;background-image: url('https://img.freepik.com/free-vector/gradient-wallpaper-background_1159-5356.jpg?size=626&ext=jpg');">10+</h1> <h3>Years of Experience</h3> </div> <div class="col-md-7"> </div> </div> A: There is the CSS-property background-clip: text; which can do this for you. The browser support is not yet complete though and you will have to use prefixes. https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip h1 { background: linear-gradient(60deg, red, yellow, red, yellow, red); background-clip: text; -webkit-background-clip: text; color: transparent; } <h1>Hi there</h1> As an alternative you could go for an actual image or an SVG.
doc_23528008
I assume it uses threads but handling threads (without using thread pool defined in the app server) is quite dangerous in app server. As I didn't assign the task executor to the thread pool I assume SI will create threads on its own. Could you please enlighten me? Thanks, V. A: Here you are http://docs.spring.io/spring-integration/docs/latest-ga/reference/html/configuration.html#namespace-taskscheduler It's about the taskScheduler from the Java EE container, but the same rule is applied for the taskExecutor. So, what you need just to get access to that managed taskExecutor, e.g. using JNDI and inject it to the <publish-subscibe-channel>. Spring Integration is fully based on Spring Framework, so <task:executor id="executor" pool-size="5"/> is just an instance of org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor and it is responcible for the creation of threads.
doc_23528009
String value = "11100110100"; I want to split it like shown below, 111,00,11,0,1,00 I tried that by splitting based on the numbers, as shown below: List<string> result1= value.Split('0').ToList<string>(); List<string> result2= value.Split('1').ToList<string>(); It did not work so, how can i get the desired output (shown below) by splitting 1 and 0? 111 00 11 0 1 00 Thanks. A: Here is my extension method, without replacing - only parsing. public static IEnumerable<string> Group(this string s) { if (s == null) throw new ArgumentNullException("s"); var index = 0; while (index < s.Length) { var currentGroupChar = s[index]; int groupSize = 1; while (index + 1 < s.Length && currentGroupChar == s[index + 1]) { groupSize += 1; index += 1; } index += 1; yield return new string(currentGroupChar, groupSize); } } Note: it works for every char grouping (not only 0 and 1) A: You can put a character between each change from 0 to 1 and from 1 to 0, and split on that: string[] result = value.Replace("10", "1,0").Replace("01", "0,1").Split(',');
doc_23528010
Let me give you an example: I have one image on my front page and I want it to be dynamic or maybe I have a telephone in the footer. How can I make them dynamically editable without hardcoding page/post IDs in the theme. Is this possible without plugins? A: You can use the shortcodes (custom or plugin): https://wordpress.org/plugins/shortbus/ or php function to /wp-content/your-theme/function.php A: There are many ways you can do this. However for your use cases WordPress has the perfect built-in mechanism which is exactly meant for things like this. Widgets. Most probably your Theme already has all dynamic areas which you may need registered. Go to Design -> Widgets and populate them. This is how you do it with your own code. Register a dynamic sidebar within your Theme: add_action( 'widgets_init', 'my_sidebars' ); function my_sidebars() { register_sidebar( array( 'name' => __( 'Foo', 'theme-slug' ), 'id' => 'bar', 'description' => __( 'I am in area XYZ.', 'theme-slug' ), 'before_widget' => '<div>', 'after_widget' => '</div>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>', ) ); } Put this code where you want it to be: <div id="my_dynamic_content"> <?php dynamic_sidebar( 'my-dynamic-content' ); ?> </div> For 99 % of use cases the existing text widgets are enough. You can also install a Plugin for WYSIWYG widget or code your own widgets. Whatever you need is possible. More information here: https://codex.wordpress.org/WordPress_Widgets
doc_23528011
foreach ($entry in $test_array) { Write-Host $entry -BackgroundColor Red $test = Compare-Object -DifferenceObject $entry -ReferenceObject $entry -IncludeEqual $test } I have this code above. What I expect is that the result of Compare-Object appears under each entry of the array. one InputObject SideIndicator ----------- ------------- one == two InputObject SideIndicator ----------- ------------- two == three InputObject SideIndicator ----------- ------------- three == What gets output instead is this: one two three InputObject SideIndicator ----------- ------------- one == two == three == It skips every entry and outputs the result of everything in the end together. Why does this happen? I'm on Powershell 5.1
doc_23528012
Here's an example import regex as re p = r'((?!\pL)|^)blah((?!\pL)|$)' print(re.search(p, "blah u")) print(re.search(p, "blahé u")) print(re.search(p, "éblah u")) print(re.search(p, "blahaha")) gives: <regex.Match object; span=(0, 4), match='blah'> None None None Which looks correct. However: print(re.search(p, "u blah")) gives: None This is wrong, as I expect a match for "u blah". I've tried to also use Pythons built in re module, but I cannot get it to work with \pL or \p{Latin} due to "bad-escape" errors. I've also tried to use unicode strings (without the "r") but despite adding slashes to \\\\pL, I just can't get this to work right. Note: I'm using Python 3.8 A: The problem with your ((?!\pL)|^)blah((?!\pL)|$) regex is that the ((?!\pL)|^) group contains two alternatives where the first one always fails the regex (why? Because (?!\pL) is a negative lookahead that fails the match if the next char is a letter, and the next char to match is b in blah) and only ^ works all the time, i.e. your regex is equal to ^blah((?!\pL)|$) and only matches at the start of string. Note (?!\pL) already matches a position at the end of string, so ((?!\pL)|$) = (?!\pL). You should use (?<!\pL)blah(?!\pL) See the regex demo (switched to PCRE for the demo purposes). Note that the re-compatible version of the regex is (?<![^\W\d_])blah(?![^\W\d_]) See the regex demo.
doc_23528013
I need to adapt this to save the .txt file as a .fcf currently I work around this by saving the text file then manually renaming it test.fcf. Is it possible to rename this in VBA? Or save directly to .fcf? Sub SaveColumn(sheetName As String, columnName As String, fileName As String) Dim cell Dim fso Dim file Set fso = CreateObject("Scripting.FileSystemObject") Set file = fso.CreateTextFile(fileName, True) For Each cell In Sheets(sheetName).Columns(columnName).Cells If cell.Value <> "" Then file.WriteLine cell.Value End If Next file.Close Set file = Nothing Set fso = Nothing End Sub To call it... SaveColumn "Output to fcf.1", "A", "P:\4_Calcs\02. Flag Mapping\test_.txt" A: Did you try to change the filename in the call? SaveColumn "Output to fcf.1", "A", "P:\4_Calcs\02. Flag Mapping\test_.fcf"
doc_23528014
There is a table header banner which is clickable and contains a number of header elements that are also scraped. I have tried every possible xpath within the header that may contain the clickable element along with code like this: driver.find_element_by_xpath('//*[@id="income-statement-accordion"]/thead/tr/th[1]').click but no possible xpath combination expands the table. When I look at the source code, the only bit of source code that appears to change when I click the header is as follows <table _ngcontent-ng-lseg-c34="" class="full-width income-statement swipable-table accordion-container" id="income-statement-accordion"> == $0 changes to this (I'm not sure the importance of == $0?): <table _ngcontent-ng-lseg-c34="" class="full-width income-statement swipable-table accordion-container active-accordion" id="income-statement-accordion"> I have viewed a similar question here: Open an accordion with selenium in python. However, attempting a similar take on this does not do anything, although does admittedly submit without error and returns none: driver.execute_script("document.getElementById('income-statement-accordion').class='full-width income-statement swipable-table accordion-container active-accordion';") What am I missing? A: This seems to work elements = driver.find_elements_by_xpath("//span[contains(@class, 'accordion-toggler')]") for element in elements: driver.execute_script("arguments[0].click();", element) This will expand all accordion sections. If you just want to target individual sections element = driver.find_element_by_xpath("//table[@id='income-statement-accordion']//span[contains(@class, 'accordion-toggler')]") driver.execute_script("arguments[0].click();", element) We need to use javascript to click the elements because selenium does not classify them as "interactable".
doc_23528015
I have tried making a second onresponse method, i cant think of any other way of doing it Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY);//This one is working! Call<MovieResponse> call1 = apiInterface.getNowPlayingMovies(API_KEY); //This is what i what to implement Here is the code Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY); call.enqueue(new Callback<MovieResponse>() { @Override public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) { int statuscode =response.code(); List<Movie> movies = response.body().getResults(); recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext())); recyclerView1.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext())); //this works but not with the NowPlayingMovies, tested to see if it was the other recyclerview } @Override public void onFailure(Call<MovieResponse> call, Throwable t) { //Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show(); } }); A: If you dont prefer to use RxJava then you can use following solution: Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY); call.enqueue(new Callback<MovieResponse>() { @Override public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) { int statuscode =response.code(); List<Movie> movies = response.body().getResults(); recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext())); secondAPICall(); } @Override public void onFailure(Call<MovieResponse> call, Throwable t) { //Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show(); } }); public void secondAPICall(){ call1.enqueue(new Callback<MovieResponse>() { @Override public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) { int statuscode =response.code(); List<Movie> movies = response.body().getResults(); recyclerView1.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext())); } @Override public void onFailure(Call<MovieResponse> call, Throwable t) { //Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show(); } }); }
doc_23528016
A: No, there is no such conversion tool available at the moment. However, it is in principle possible to make it. PsychoPy Builder saves experiments in the open .psyexp format and then that is converted to Python code. Someone could write converters to other script structures and languages, for example, NeuroBS Presentation, PsychToolbox, etc.
doc_23528017
{{ form_start(form) }} {{ form_row(form.title) }} {{ form_row(form.description) }} {{ form_end(form) }} I get <form name="job" method="post" action="/myname/Job/create"> <div><label for="job_title" class="required">Title</label> <input type="text" id="job_title" name="job[title]" /></div> <div><label for="job_description" class="required">Description</label> <input type="text" id="job_description" name="job[description]" /></div> </form> but I need to render it something like: <form name="job" method="post" action="/myname/Job/create"> <div><label for="job_title" class="required">Title</label> <input type="text" id="job_title" name="job[0][title]" /></div> <div><label for="job_description" class="required">Description</label> <input type="text" id="job_description" name="job[0][description]" /></div> </form> the point being to insert the index [0]. (This I need to apply a JS trick) I looked at form_div_layout.html.twig, I understand that the rendering of a form is given by the lines under {%- block widget_attributes -%}, but I do not see how Symfony 2.7 assigns that piece of html to {{ full_name }}.
doc_23528018
Table Reservations: ID arrival datetime departure datetime reservation_object (FK to objects table) Now I need to generate a report that shows for a specified period the status of an object. This report will have to look like this: 6/1/09 6/2/09 6/3/09 6/4/09 ... object 1 free free busy busy object 2 busy free busy busy ... What is the best way to get this information from SQL server? I'm going to use it in C#.Net. A: You may find it easier to pivot the data client side - so ask SQL server for all the appointments that start before the end of the date window you're interested in, but only those that finish after the start of the date window you're interested in. You can then create a two dimensional array that is logically bookable resource on one dimension, date on the other, with a (potential list of) reservation at each cell -- this would allow you to then drill into details by day without a server round-trip as well... A: I decided to use http://www.daypilot.org/scheduler-lite.html.
doc_23528019
Inserting a number containing a hash (#) or asterisk (*) won't work and return me a syntax error. RFCs tell me that a number is the following: Printable string (alphabetic, digits, ', (, ), +, ,, -, ., /, :, ?, and space) and " How can I edit the schema to support # and * characters? A: We are having the same exact issue! Mobile networks offer a variety of services and information accessed using numbers that include either pound (hash) or star. Its a perfectly valid question for perfectly normal use of a phone number field. Having a very casual look at RFC 4517, I see that it's really true! The LDAP RFC offers only a very limited selection of basic syntax types, and telephoneNumber maps to PrintableString. Probably a case of the RFCWG more interested in their RFC for its own sake, than the practical application thereof. I mean, which would be more useful in a phone number field - '?' or '#'.. As was already alluded, hacking cosine.schema can lead to even larger problems and is not upgrade-safe. FYI there are a few LDAP servers out there, many a bit more flexible about the RFC implementation. Have a look at OpenDJ: https://forgerock.org/opendj/ Any server-side 'fix' in this case will likely no longer be strictly RFC compliant, which runs the risk of your original syntax issues revisiting you, if you ever need to exchange LDIF with other LDAP systems. But IMHO changing the client mapping to another unrelated field type could hardly be called 'better', especially from an onlooker's perspective. So either get another LDAP server which is more forgiving or change the field mapping on the client - either way presents risks and should be understood as a limitation of RFC 4517. A: You would have to change the OID in the telephoneNumber schema entry to refer to a more general attribute syntax OID as per the RFCs. Not a good idea. You would be better off using a different attribute.
doc_23528020
This is the command for verifying SCCM .MIG file using USMTUTIL.EXE $array = "C:\MININT\amd64\usmtutils /verify:All \\SMB001.India.kerala.net\SMPSTORED_91DAA93F$\2AE09BF0AADC04FC89E0CE8A49E8C904E44C0314A123824A7EB289CAFC258026\USMT\USMT.mig /Decrypt /key:PZSTqMLlsJAYna/ndimPT1SrSAz4JjSNH1P7Sv/8mDj8qmytPcLPE3lYzxHnMiVj/6UkdDcWmiaKqgxHO3yjZj2gu8r/j23oefWOsdyWbo4r3UX2gPvMO38np7OOabZ8B0B6A5mAYynAjfy/1e00uhIm1h6soFUWIuu3wkNevBHxkWQs4xslGlooVOn0f+1kGqe05iRWUaVZC4/yYKv3LdbFLhzRXOxVYjriao4oKCEpNEdjnDK6DRoRRrbDy8Ac > C:\temp\DENDMNPWTST008.log" I tried Invoke-expression $array While executing this command, Its separating into different lines and only first line is executing and showing error. But I can copy-paste and run it Error: CategoryInfo : NotSpecified: (:String) [], RemoteException FullyQualifiedErrorId : NativeCommandError A: Invoke-Expression is expecting a string argument and not a string array. try this: Invoke-Expression ($array | out-string)
doc_23528021
A: For depth understanding of Logical plan and physical plan, refer this link : http://chimera.labs.oreilly.com/books/1234000001811/ch07.html#explain
doc_23528022
I would like to combine this two functions in another function which alllow an user to pass a value in and having the result equal to the value passed plus 10 multiply 3 using the following functions. Pseudo code example: const myFormulat= add(10).multiply(3); How can I write this function using only vanilla JS ES6? function add(x){ return function(y){ return y + x; }; } function multiply(x){ return function(y){ return y * x; }; } // my calculation // get x add 10 and after multiply by 3 A: Bear traps and landmines This answer exists solely to demonstrate why this is not such a great idea – complexity is thru the roof with basically no gain. Note we must tell our function when to end, so i've added a special function call so our expressions will look like this .add(3).mult(4).call(x) // where x is the input for the entire function chain One last change is our library of functions add, mult, et al must be wrapped in some scope that limits the reach of our proxy. This scope tells us exactly where the functions we wish to chain exist. Oh and if the title of this section wasn't a warning enough, we use a Proxy too. // helpers const identity = x => x const comp = f => g => x => f(g(x)) // magic wand const using = scope => { let acc = identity let p = new Proxy({ call: x => acc(x), }, { get: (target, name) => { if (name in target) return target[name] else if (name in scope) return x => { acc = comp (scope[name](x)) (acc) return p } else throw Error(`${f} is not undefined in ${scope}`) } }) return p } // your functions wrapped in a scope const math = { add: x => y => x + y, mult: x => y => x * y } // chain it up const main = using(math).add(3).mult(4).add(5).mult(6).call console.log(main(2)) // (((2 + 3) * 4) + 5) * 6 // ((5 * 4) + 5) * 6 // (20 + 5) * 6 // 25 * 6 // 150 Function composition But seriously, don't do that. Pushing everything through the . operator is unnatural given your starting point and you should be looking for more effective means to combine functions. We can effectively do the same thing using a slightly different notation – the biggest difference here is complexity is almost zero const compose = (f,...fs) => x => f === undefined ? x : compose (...fs) (f(x)) const add = x => y => x + y const mult = x => y => x * y const main = compose (add(3), mult(4), add(5), mult(6)) console.log(main(2)) // => 150 Functors Maybe you don't like traditional function composition, and that's fine, because we have yet another way to tackle this problem using Functors – simply put, a Functor is a container with a map function. Below we have a Box function which puts values in our container. The map function accepts a function and creates a new Box with the return value of the user-specified function. Lastly, we have a fold function which allows us to take our value out of the box Again, it changes up the way we write the code a little bit, but the reduction is complexity is tremendous (compared to the Proxy example) const Box = x => ({ map: f => Box(f(x)), fold: f => f(x) }) const add = x => y => x + y const mult = x => y => x * y const main = Box(2).map(add(3)).map(mult(4)).map(add(5)).map(mult(6)).fold main(console.log) // 150 A: See: http://scott.sauyet.com/Javascript/Talk/Compose/2013-05-22/ function add(x){ return function(y){ return y + x; }; } function multiply(x){ return function(y){ return y * x; }; } Function.prototype.compose = function(g) { var fn = this; return function() { return fn.call(this, g.apply(this, arguments)); }; }; var f = multiply(3).compose(add(10)); console.log(f(5)); A: If i understand you correctly you are trying to figure out function chaining in JavaScript Function Chaining or Method chaining is a common pattern in JS world. one of the methods in which you can achieve chaining is by creating a class and returning this operator or current object reference back You can find interesting tutorial regarding this in following URL https://www.bennadel.com/blog/2798-using-method-chaining-with-the-revealing-module-pattern-in-javascript.htm
doc_23528023
$report = Log::select('logs.id') ->where('logs.id', '=', '1') ->get(); // event(new NewLog($report)); return $report; In this case, the returning value is 1. I am also expecting that data will be sent to Pusher will be the same as the result of the query. But the data that are being sent to Pusher are id, user_id, date` etc. I just want to send the single data that I fetched which is logs.id. Here is my NewLog Event: class NewLog implements ShouldBroadcast { public $log; use Dispatchable, InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct($log) { $this->log = $log; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('logs'); } } A: you can directly use the find() static function on Log. return $report will give you object.if you want to access the property of that object use as $report->property_name; try using the below code: $report = Log::find(1); $event = event(new NewLog($report->id)); return $report->id; OR $report = Log::select('logs.id') ->where('logs.id', '=', '1') ->get(); // event(new NewLog($report->id)); return $report;
doc_23528024
<?xml version="1.0"?> <users><user><firstname>ben</firstname><surname>kim</surname <email>benkim@test.com</email></user> <user><firstname>ken</firstname><surname>kim</surname><email>kenkim@test.com</email> </user></users> What I'd like to do is that appending a new user into existing XML above with the codes below. But I doesn't work at all. Could you guys look at them please? <?php header('Content-Type: text/xml'); ?> <?php $firstname = $_GET["firstname"]; $surname = $_GET["surname"]; $email = $_GET["email"]; $person = array("firstname"=>$firstname,"surname"=>$surname,"email"=>$email); //ECHO (fromXML()); $xmlDoc = new DOMDocument(); $xmlDoc->load("test.xml"); $xmlDoc=$xmlDoc->documentElement; toXml($person); function toXml($person) { $users = $xmlDoc->getElementsByTagName('users'); $user = $xmlDoc->createElement('user'); $user = $users->appendChild($user); $firstname = $xmlDoc->createElement('firstname'); $firstname = $user->appendChild($firstname); $valFirstname = $xmlDoc->createTextNode($person["firstname"]); $valFirstname = $firstname->appendChild($valFirstname); $surname = $xmlDoc->createElement('surname'); $surname = $user->appendChild($surname); $valSurname = $xmlDoc->createTextNode($person["surname"]); $valSurname = $surname->appendChild($valSurname); $email = $xmlDoc->createElement('email'); $email = $user->appendChild($email); $valEmail = $xmlDoc->createTextNode($person["email"]); $valEmail = $email->appendChild($valEmail); $strXml = $xmlDoc->saveXML(); $handle = fopen("test.xml", "a"); fwrite($handle, $strXml); fclose($handle); } A: Try using SimpleXML instead $xml = new SimpleXMLElement('your xml here'); $user = $xml->addChild('user'); $user->addChild('firstname', $person["firstname"]); A: You have multiple issues. First, $xmlDoc is not available inside your function's scope. For that, you need to either: * *Pass $xmlDoc as a parameter of your toXml() function (which is recommended) *Use the global keyword to tell your function that it needs to fetch $xmlDoc from the global context (which is discouraged) Then, you don't fetch the root node correctly. In your case, you simply need to fetch it using $xmlDoc->firstChild. Then, you need to create the different nodes, and then insert them in your root node. Which means that you need to create the elements before appending them to the DOM. Finally, you are opening the test.xml file in append mode (a). This means that when you'll save your document, you will actually append the content of your xml to the existing content, and thus, your document will be invalid, as it will have a new <?xml ... ?> tag each time you execute the script. Here is a corrected version of your script. Feel free to ask questions if you have any! :) <?php $person = array( "firstname" => $_GET["firstname"], "surname" => $_GET["surname"], "email" => $_GET["email"], ); $xmlDoc = new DOMDocument(); $xmlDoc->preserveWhiteSpace = false; $xmlDoc->formatOutput = true; $xmlDoc->load("test.xml"); toXml($person, $xmlDoc); header('Content-Type', 'application/xml'); exit(file_get_contents('test.xml')); function toXml(array $person, DOMDocument $xmlDoc) { $users = $xmlDoc->firstChild; $user = $xmlDoc->createElement('user'); $firstname = $xmlDoc->createElement('firstname'); $textNode = $xmlDoc->createTextNode($person["firstname"]); $firstname->appendChild($textNode); $user->appendChild($firstname); $surname = $xmlDoc->createElement('surname'); $textNode = $xmlDoc->createTextNode($person["surname"]); $surname->appendChild($textNode); $user->appendChild($surname); $email = $xmlDoc->createElement('email'); $textNode = $xmlDoc->createTextNode($person["email"]); $email->appendChild($textNode); $user->appendChild($email); $users->appendChild($user); $strXml = $xmlDoc->saveXML(); $handle = fopen("test.xml", "w"); fwrite($handle, $strXml); fclose($handle); }
doc_23528025
<?xml version='1.0' encoding='utf-8'?> <ssbpreise> <ggvs>25.15</ggvs> <einblaspauschale>40</einblaspauschale> <pelletspreis>2.9</pelletspreis> <heizoel>0.4865</heizoel> <mwstpellets>5</mwstpellets> <mwstheizoel>22</mwstheizoel> <testparameter>testtest</testparameter> </ssbpreise> In my Code I try to convert the string double einzelpreispellets = 0, einzelpreisheizoel = 0, einblaspauschale = 0, ggvs = 0, mwstpellets = 0, mwstheizoel = 0; try { if (devmode) writetolog(@"XML lesen."); using (XmlReader reader = XmlReader.Create(localFileserverBaseUrl + @"parameter.xml")) { while (reader.Read()) { if (reader.IsStartElement()) { //return only when you have START tag switch (reader.Name.ToString()) { case "pelletspreis": writetolog(string.Format("{0}: gepeichert: {1} - aus xml: {2}", reader.Name.ToString(), einzelpreispellets, reader.ReadString())); einzelpreispellets = XmlConvert.ToDouble(reader.ReadString()); break; case "heizoel": writetolog(string.Format("{0}: gepeichert: {1} - aus xml: {2}", reader.Name.ToString(), einzelpreisheizoel, reader.ReadString())); einzelpreisheizoel = XmlConvert.ToDouble(reader.ReadString()); break; case "einblaspauschale": writetolog(string.Format("{0}: gepeichert: {1} - aus xml: {2}", reader.Name.ToString(), einblaspauschale, reader.ReadString())); einblaspauschale = XmlConvert.ToDouble(reader.ReadString()); <=== this is row 322 break; case "ggvs": writetolog(string.Format("{0}: gepeichert: {1} - aus xml: {2}", reader.Name.ToString(), ggvs, reader.ReadString())); ggvs = XmlConvert.ToDouble(reader.ReadString()); break; case "mwstpellets": writetolog(string.Format("{0}: gepeichert: {1} - aus xml: {2}", reader.Name.ToString(), mwstpellets, reader.ReadString())); mwstpellets = XmlConvert.ToDouble(reader.ReadString()); break; case "mwstheizoel": writetolog(string.Format("{0}: gepeichert: {1} - aus xml: {2}", reader.Name.ToString(), mwstheizoel, reader.ReadString())); mwstheizoel = XmlConvert.ToDouble(reader.ReadString()); break; default: writetolog(string.Format("Parameter konnte nicht zugeordnet werden : {0} | Wert: {1}", reader.Name.ToString(), reader.ReadString())); break; } } } } } catch(Exception e) { writetolog("Error: " + e); return; } This is my created logfileoutput: 12:07:09: einblaspauschale: from the variabledeclaration: 0 - from xml: 40 12:07:09: Error: System.FormatException: The input string is in the wrong format at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt) at System.Xml.XmlConvert.ToDouble(String s) at Webshopfiletransfer.Webshopfiletransfer.createCSVFile() in Webshopfiletransfer.cs:Row 322. I am confuse, the value from the xml is available and would printed on the correct tag but the convertion to double seems to be wrong. Is maybe anybody able to give me a tip where my misunderstanding is? A: You have two problems: The first is that ReadString() seams to return the content once but you try to read it twice. So just do var str = reader.ReadString() and use str to refer to the content. But You could also your ReadContentAsDouble instead of converting it yourself. The second problem is that the converions is in the wrong order. You need to do var str = reader.ReadString(); einblaspauschale = XmlConvert.ToDouble(str); writetolog(string.Format("{0}: gepeichert: {1} - aus xml: {2}", reader.Name.ToString(), einblaspauschale, str)); so that the logging output can be einblaspauschale: gepeichert: 40 - aus xml: 40
doc_23528026
A: Ansible has two types of nodes * *Master / Control Machines : The node from which ansible is invoked *Client / Remote Machine : The nodes on which ansible operates Ansible's primary mode of transport is ssh, using which it applies the playbook to the remote machine. In order for ansible to ssh into the remote machine, ssh has to be already setup between the machine using private/public key authentication preferably. When it comes to EC2: 1) Every node has a default key with which the instance is launched, and ansible could use this key to ssh, but this considered insecure / not a best pratice. 2) A key has to present in the client node, with which ansible can authenticate successfully, and the most preferred way is to pull the keys using user-data from a restricted S3 bucket.
doc_23528027
A: This was changed in commit 9b525539f0c7bf734be8e01db082fca775dbd028, “[dcl.type.simple] Factor out decltype(e) wording into its own subclause.” To me, this looks like a purely editorial change. Such changes are continuously made by the editors of the standard.
doc_23528028
http://127.0.0.1:8000/hotes/12/access/7/update I get an error 404 "None access object was found" To make a long story short: I want to update an object linked to another. To do so, I have to send through the link, both primary keys (12 and 7 in the url). Also, I use the generic view "UpdateView" given by Django. This is the path concerned in my project.urls: urlpatterns = [ path('hotes/<int:pk>/access/<int:access_pk>/update/',views.AccessUpdateView.as_view(), name='access_update'), path('hotes/add',views.host_add, name='host_add'), path('hotes/<int:pk>/', include([ path('edit',views.HostUpdateView.as_view(), name='host_update'), path('delete',views.host_delete, name='host_delete'), ])), path('hotes/<int:pk>/add/', include([ path('access',views.access_add, name='access_add'), path('oncall',views.onCall_add, name='onCall_add'), path('network',views.network_add, name='network_add'), ])), path('hotes/<int:pk>/',views.host_view, name='host_view'), path('hotes/',views.hosts_view, name='hosts_view'), path('', views.home, name='home'), path('admin/', admin.site.urls), ] I want the second primary key to be used in my view "AccessUpdateView". This is a part of my models.py: class Host(models.Model): name = models.CharField(max_length=30, unique=True) usage = models.CharField(max_length=30, blank=True) function = models.CharField(max_length=30, blank=True) production = models.NullBooleanField(blank=True, null=True) place = models.CharField(max_length=30, blank=True) type = models.CharField(max_length=30, blank=True) processor = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) storage = models.CharField(max_length=10, blank=True) memory = models.CharField(max_length=10, blank=True) dns_inner = models.CharField(max_length=50, blank=True) dns_extern = models.CharField(max_length=50, blank=True) os = models.ForeignKey(Os, null=True, related_name='hosts', on_delete=models.SET_NULL, blank=True) class Access(models.Model): service = models.CharField(max_length=20) client_access = models.NullBooleanField(blank=True, null=True) ip = models.GenericIPAddressField() login = models.CharField(max_length=30, blank=True) password = models.CharField(max_length=50, blank=True) host = models.ForeignKey(Host, related_name='access', on_delete=models.CASCADE) As you can see on host can have multiple access but an access in linked to only one host. This is the view concerned: class AccessUpdateView(UpdateView): model = Access fields = ('service','client_access','ip','login','password', ) template_name = 'access_update.html' pk_url_kwarg = 'access_pk' context_object_name = 'access' def form_valid(self, form): access = form.save(commit=False) host_id = self.kwargs['pk'] access.host_id = host_id access.save() return redirect('host_view', pk=host_id) EDIT: new error when I try to access the url: NoReverseMatch at /hotes/12/access/7/update/ Reverse for 'host_view' with arguments '('',)' not found. 1 pattern(s) tried: ['hotes\/(?P[0-9]+)\/$'] EDIT: The error was coming from "access_update.html" I removed the href in the Hote link which contained {% url host.pk %} {% extends 'base.html' %} {% load widget_tweaks %} {% block title %}Modifier Acces{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'hosts_view' %}">Hotes</a></li> <li class="breadcrumb-item"><a href="">Hote</a></li> <li class="breadcrumb-item active">Modification Acces</li> {% endblock %} {% block contenu %} <form method="post" novalidate> {% csrf_token %} {% include 'includes/form.html' %} <button type="submit" class="btn btn-success">Modifier</button> </form> {% endblock %} The question is what is the right way to write the pk of the host in the url? (host_id doesn't work) A: If you want to use access_pk, then you should set pk_url_kwarg = 'access_pk' in the view. In your form_valid method, you are using host without defining it. If pk from the URL is the host id, then you can access it with self.kwargs['pk']. def form_valid(self, form): access = form.save(commit=False) host_id = self.kwargs['pk'] access.host_id = host_id access.save() return redirect('host_view', pk=host_id) Inside the template for the AccessUpdateView, you have access to access since that is the object that is being updated. If you want to use the host or its id, you should access it via access. {% url 'host_view' access.host_id %}
doc_23528029
If you think about it, you can divide a game object into its view (the graphic on the screen) and a view-model/model (the state, ai, and other data for the object). In silverlight, it seems common to make each object a user control, putting the model and view into a single object. I suppose the advantage of this is simplicity. But, perhaps it's less clean or has some disadvantages in terms of the underlying "game engine". What are your thoughts on this matter? What are some advantages and disadvantages of using the MVVM pattern for game development? How about performance? All thoughts are welcome. A: You may run into performance problems, since MVVM typically leads to a lot of Data Binding functionality in WPF to accomplish a clean separation. However, it's still an excellent idea and worth pursuing; you can always profile the application later and optimize certain elements, if you need to. Most likely it'll be the AI that's gating rather than the UI integration. As far as figuring out where to divide Model | View Model | View, I like to take the following approach: * *The Model is everything that has nothing or very little to do with direct user interaction. This would include the game rules engine, the AI, etc. The View Models interact with the Model in well-defined ways where the user either has control or receives feedback on what's happening in the Game Model. *I try to create View Models for each major component of the interface. For example, if you were building an RPG, you might have an InventoryViewModel, CharacterStatsViewModel, WorldMapViewModel, etc. I usually don't create them for individual controls/widgets (like health indicators, item glyphs or '+' signs to level up) unless they have a reasonably complex interface. *The Views are of course how the user finally gets to interact and observe, which is fairly straightforward to understand. One nice thing is that you can create multiple Views for a given ViewModel, so you might have a large view for the Inventory and also a smaller view for quick access to important items, for example, if the way you interact with them is essentially the same. A: In a word - great! In fact, Josh Smith just published a book on MVVM using a game as his explanatory app. Recommend you read Ward Bell's excellent (and free) critique of Josh's work first.
doc_23528030
Thanks. A: If you added the code you have to your question it would be more descriptive. I've written a bit of code to demonstrate the usage of the tear off menu with GTKAda, it's not so difficult, but it may be hard to find documentation about it: function CreateFileMenu(tearOff : boolean) return Gtk_Menu is fileMenu : Gtk_Menu; newFile, loadFile, saveFile, saveAs, close : Gtk_Menu_Item; begin -- Create the menu: Gtk_New(fileMenu); -- Add the tear off item to the menu if required: if tearOff then declare tear : Gtk_Tearoff_Menu_Item; begin Gtk_New(tear); Append fileMenu, tear); Show(tear); end; end if; -- Create the rest of the menu items: Gtk_New_With_Mnemonic(newFile, "_New"); Gtk_New_With_Mnemonic(loadFile, "_Load"); Gtk_New_With_Mnemonic(saveFile, "_Save"); Gtk_New_With_Mnemonic(saveAs, "Save _as..."); Gtk_New_With_Mnemonic(close, "_Close"); -- Add the items to the menu: Add(fileMenu, newFile); Add(fileMenu, loadFile); Add(fileMenu, saveFile); Add(fileMenu, saveAs); Add(fileMenu, close); return fileMenu; end CreateFileMenu; The declare/begin/end structure allows you to declare variables in run time. The boolean parameter allows you decide if you want it to be a tear off menu when you create it. The function just creates the menu so you'd have to add it to a menu bar (for example) later. A: Not sure if this is what you are looking for, but the GtkAda reference manual says: All the menus in GtkAda can be "Tear off" menus, i.e you can detach them from their parent (either a menu bar or another menu) to keep them visible on the screen at all times). So it sounds as if you don't have to do anything.
doc_23528031
// Fork Kovan await hre.network.provider.request({ method: 'hardhat_reset', params: [{ forking: { jsonRpcUrl: KOVAN_JSON_RPC } }], }); // Act like AAVE_HOLDER await hre.network.provider.request({ method: 'hardhat_impersonateAccount', params: [AAVE_HOLDER], }); const signer = await hre.ethers.getSigner(AAVE_HOLDER); console.log('signer:', signer.address); // AAVE token on Kovan network const aavetoken = IERC20__factory.connect(AAVE_TOKEN_ADDRESS, signer); console.log('token balance:', (await aavetoken.balanceOf(signer.address)).toString()); const MyV2CreditDelegation = new MyV2CreditDelegation__factory(signer); const delegation = await MyV2CreditDelegation.deploy({ gasLimit: 1e7 }); console.log('delegation:', delegation.address); // Set the allowance higher than the deposit amount // so we know we can make multiple transactions let allowance = 100000 let despositAmount = 10; await aavetoken.approve(delegation.address, allowance); console.log('allowance:', (await aavetoken.allowance(signer.address, delegation.address, { gasLimit: 1e6 })).toString()); const depositTrans = await delegation.depositCollateral(aavetoken.address, despositAmount, true, { gasLimit: 1e6 }); console.log('depositTrans:', depositTrans.hash); const depositReceipt = await depositTrans.wait(); Deposit works fine, However when I try to withdraw: try { var withdrawTrans = await delegation .withdrawCollateral(aavetoken.address, { gasLimit: 1e6 }) console.log('withdrawTrans:', withdrawTrans.hash); const withdrawReceipt = await withdrawTrans.wait(); } catch (err) { console.log('Error:' + err); } I get an error: Transaction reverted: function returned an unexpected amount of data I'm pretty new to hardhat, I'm now sure of how to debug this any further. How can I withdraw from Aave?
doc_23528032
Calendar has events with ampersands in the summary e.g. mother&father Problem is that this is not found when using the Events:list q parameter from code. When using the API from this google API test page, the behaviour is as follows: * *Searching for mother&father results no events *Searching for "mother&father" (with quotes) returns the expected events When doing the same thing from code -with or without quotes- doesn't return the events. The code works fine when searching for events without ampersands in the summary. So question is: how can the q parameter be used from code, to retrieve events with ampersands in the name? EDIT 17 Dec 2019: Provide more details SET UP : google calendar with id , with an event on 19 dec 2019 with title "mother&father child1" CASE1: Looking for "mother&father", result ("items": look at the end of the response) is empty: _api_list_args['q'] = 'mother&father' GoogleConfig.service.events().list(**_api_list_args).execute() GET https://www.googleapis.com/calendar/v3/calendars/<my_cal_id>%40group.calendar.google.com/events?singleEvents=true&q=father&orderBy=startTime&maxResults=8&timeMin=2019-12-17T14%3A47%3A17.205463Z&timeMax=2020-06-16T00%3A00%3A00.000Z&alt=json {'kind': 'calendar#events', 'etag': '"p334fb5lauquec0g"', 'summary': 'SWD local', 'updated': '2019-12-17T14:46:39.117Z', 'timeZone': 'Europe/Brussels', 'accessRole': 'writer', 'defaultReminders': [], 'items': []} CASE2: Looking for "father", result is also empty: _api_list_args['q'] = 'father' GoogleConfig.service.events().list(**_api_list_args).execute() URL being requested: GET https://www.googleapis.com/calendar/v3/calendars/<my_cal_id>%40group.calendar.google.com/events?singleEvents=true&q=father&orderBy=startTime&maxResults=8&timeMin=2019-12-17T14%3A47%3A17.205463Z&timeMax=2020-06-16T00%3A00%3A00.000Z&alt=json {'kind': 'calendar#events', 'etag': '"p328ajglquuuec0g"', 'summary': 'SWD local', 'updated': '2019-12-17T14:51:41.818Z', 'timeZone': 'Europe/Brussels', 'accessRole': 'writer', 'defaultReminders': [], 'items': []} CASE3: Looking for "child1", now it finds the event: _api_list_args['q'] = 'child1' GoogleConfig.service.events().list(**_api_list_args).execute() URL being requested: GET https://www.googleapis.com/calendar/v3/calendars/<my_cal_id>%40group.calendar.google.com/events?singleEvents=true&q=child1&orderBy=startTime&maxResults=8&timeMin=2019-12-17T14%3A47%3A17.205463Z&timeMax=2020-06-16T00%3A00%3A00.000Z&alt=json {'kind': 'calendar#events', 'etag': '"p338fbacsvauec0g"', 'summary': 'SWD local', 'updated': '2019-12-17T15:04:03.810Z', 'timeZone': 'Europe/Brussels', 'accessRole': 'writer', 'defaultReminders': [], 'items': [{'kind': 'calendar#event', 'etag': '"3153190087620000"', 'id': 'p939brcc2r83cu9q52sjagcua4_20191219T200000Z', 'status': 'confirmed', 'htmlLink': 'https://www.google.com/calendar/event?eid=cDkzOWJyY2MycjgzY3U5cTUyc2phZ2N1YTRfMjAxOTEyMTlUMjAwMDAwWiBnNXJ1cTl1Z2xlNWc2ZTFhMms1cmZyM2hjY0Bn', 'created': '2019-11-29T16:58:45.000Z', 'updated': '2019-12-17T15:04:03.810Z', 'summary': 'mother&father child1', 'description': 'my nice description<br><a href="<mysite>" id="ow2358" __is_owner="true"><mysite></a>', 'location': '#MYLOCATION', 'creator': {'email': '<myemail>'}, 'organizer': {'email': '<my_cal_id>@group.calendar.google.com', 'displayName': 'SWD local', 'self': True}, 'start': {'dateTime': '2019-12-19T21:00:00+01:00', 'timeZone': 'Europe/Brussels'}, 'end': {'dateTime': '2019-12-19T22:00:00+01:00', 'timeZone': 'Europe/Brussels'}, 'recurringEventId': 'p939brcc2r83cu9q52sjagcua4', 'originalStartTime': {'dateTime': '2019-12-19T21:00:00+01:00', 'timeZone': 'Europe/Brussels'}, 'iCalUID': 'p939brcc2r83cu9q52sjagcua4@google.com', 'sequence': 0, 'extendedProperties': {'shared': {'course_162': '1'}}, 'reminders': {'useDefault': True}}]} BUT: This one also fails: look for "chil" ie part of a word... CASE 4: Look for "chil" _api_list_args['q'] = 'chil' GoogleConfig.service.events().list(**_api_list_args).execute() URL being requested: GET https://www.googleapis.com/calendar/v3/calendars/<my_cal_id>%40group.calendar.google.com/events?singleEvents=true&q=chil&orderBy=startTime&maxResults=8&timeMin=2019-12-17T14%3A47%3A17.205463Z&timeMax=2020-06-16T00%3A00%3A00.000Z&alt=json {'kind': 'calendar#events', 'etag': '"p338fbacsvauec0g"', 'summary': 'SWD local', 'updated': '2019-12-17T15:04:03.810Z', 'timeZone': 'Europe/Brussels', 'accessRole': 'writer', 'defaultReminders': [], 'items': []} Does google 'q' parameter only searches for whole words?? A: My guess is that google removes the "&" due to a security reason. Most of xss attacks are prevented when removing special charecters of url like "&". Try replacing the "&" with "&amp" or with "%26"
doc_23528033
I have obtained several derived copies in various formats and resolutions from these yuv files using FFmpeg transcoding. (YUVs ----> X Derived Copies) What I have also done is, transcode the yuv's into same resolution AVIs, and now obtained the same set of derived (transcoded) videos treating the AVIs as master. (AVIs ----> X Derived Copies) Now I wish to compare the quality of transcoded videos, when derived from AVIs to those derived from YUVs. Is there any way for me to do this using FFmpeg. How? If not, can you please suggest some good open source software to do this. Thanks A: If you have the time this is what I've done in the past. 1. Use ffmpeg to split both the video files into their component frames (make sure that you have the disk space first): ffmpeg -i file1.avi -f image2 file1-%015d.bmp ffmpeg -i file2.avi -f image2 file2-%015d.bmp *Use imagemagick compare to determine the differences in each frame (Replace NNNNNN with the number of frames that ffmpeg gave you): for FNAME in {1..NNNNNN}; do compare file1-$FNAME.bmp file2-$FNAME.bmp tmp.png compare -metric PSNR file1-$FNAME.bmp file2-$FNAME.bmp tmp.png >> results done *Open the file results in a spreadsheet and work out the average, std-dev, etc ... this will tell you how much the files differ.
doc_23528034
template <typename> void (T arg){ } Such that I could pass in any container, like vector or list, but not any type that isn't a container. How would I achieve this? Is this not possible? A: Use a template template parameter, eg: template <template<class...> class Container, class... Args> void func(const Container<Args...> &arg) { ... } Online Demo
doc_23528035
Failed to add resource to index Exception caught during execution of add command this is my log: !ENTRY org.eclipse.egit.ui 4 0 2023-01-25 20:38:42.622 !MESSAGE Failed to add resource to index !STACK 1 org.eclipse.core.runtime.CoreException: Failed to add resource to index at org.eclipse.egit.core.op.AddToIndexOperation.execute(AddToIndexOperation.java:78) at org.eclipse.egit.ui.internal.actions.AddToIndexActionHandler$1.run(AddToIndexActionHandler.java:59) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) Caused by: org.eclipse.jgit.api.errors.JGitInternalException: Exception caught during execution of add command at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:225) at org.eclipse.egit.core.op.AddToIndexOperation.execute(AddToIndexOperation.java:74) ... 2 more Caused by: org.eclipse.jgit.errors.LockFailedException: Cannot lock C:\Users\motah\.git\index. Ensure that no other process has an open file handle on the lock file C:\Users\motah\.git\index.lock, then you may delete the lock file and retry. at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:221) at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:292) at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:258) at org.eclipse.jgit.lib.Repository.lockDirCache(Repository.java:1285) at org.eclipse.egit.core.RepositoryHandle.lockDirCache(RepositoryHandle.java:319) at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:122) ... 3 more !SUBENTRY 1 org.eclipse.egit.core 4 0 2023-01-25 20:38:42.622 !MESSAGE Failed to add resource to index !STACK 0 org.eclipse.jgit.api.errors.JGitInternalException: Exception caught during execution of add command at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:225) at org.eclipse.egit.core.op.AddToIndexOperation.execute(AddToIndexOperation.java:74) at org.eclipse.egit.ui.internal.actions.AddToIndexActionHandler$1.run(AddToIndexActionHandler.java:59) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) Caused by: org.eclipse.jgit.errors.LockFailedException: Cannot lock C:\Users\motah\.git\index. Ensure that no other process has an open file handle on the lock file C:\Users\motah\.git\index.lock, then you may delete the lock file and retry. at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:221) at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:292) at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:258) at org.eclipse.jgit.lib.Repository.lockDirCache(Repository.java:1285) at org.eclipse.egit.core.RepositoryHandle.lockDirCache(RepositoryHandle.java:319) at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:122) ... 3 more Can anyone help me here how I can solve it? I have deleted my project and made another one and it did not work. I did with other projects that I have and I get the same error. I am learning how to push in eclipse to github. I only had this problem at class and we could not solve it. A: I just found the solution. I had to delete .lock file. Now it works fine.
doc_23528036
Right now, I have something like this: print *, root1, root2 open(unit=10,file='result.txt' write(10,*), root1, root2 close(10) I feel like I'm wasting lines and making the code longer that it should be. I actually want to print/write much more lines that these, so that's why I'm looking for a cleaner way to do it. A: Writing to standard output and writing to file are two different things, so you will always need separate instructions. But you don't have to open and close the file for every line you write. Honestly, I don't think it's that much more of an effort: open(unit=10, file='result.txt', status='replace', form='formatted') .... write( *, *) "Here comes the data" write(10, *) "Here comes the data" .... write( *, *) root1, root2 write(10, *) root1, root2 .... close(10) this is only one line more than what you would have to do anyway per write statement. If you really think that you have too many write statements in your code, here are a few ideas that you might try: If you are running on a Linux or Unix system (including MacOS), you can write a program that only writes to standard out, and pipe the output into a file, like this: $ ./my_program | tee result.txt This will both output the data to the screen, and write it into the file result.txt Or you could write the output to a file in the program, and 'follow' the file externally: $ ./my_program & $ tail -f result.txt I just had another idea: If you really often have the issue that you need to write data to both the screen and the file, you can place that into a subroutine: program my_program implicit none real :: root1, root2, root3 .... open(10, 'result.txt', status='replace', form='formatted') .... call write_output((/ root1, root2 /)) .... call write_output((/ root1, root2, root3 /)) .... call write_output((/ root1, root2 /)) .... close(10) .... contains subroutine write_output(a) real, dimension(:), intent(in) :: a write( *, *) a write(10, *) a end subroutine write_output end program my_program I am passing the values to be written here as an array because that gives you more flexibility in the number of variables that you might want to print. On the other hand, you can only use this subroutine to write real values, for others (integer, character, etc) or combinations thereof you'd need to still have two write statements, or write other specific 'write to both' routines.
doc_23528037
name Country ... 1 Paul Germany 2 Paul Germany 3 George Italy 3 George Italy 3 George Italy ... N John USA I'm looking for the occurence of each element of the name column, such has name Country Count 1 Paul Germany 2000 2 George Italy 500 ... N John USA 40000 Any idea what is the most optimal way to do it ? Because this is quite long df['count'] = df.groupby(['name'])['name'].transform(pd.Series.value_counts) A: you can do it like this: df.groupby(['name', 'Country']).size() example: import pandas as pd df = pd.DataFrame.from_dict({'name' : ['paul', 'paul', 'George', 'George', 'George'], 'Country': ['Germany', 'Italy','Germany','Italy','Italy']}) df output: Country name 0 Germany paul 1 Italy paul 2 Germany George 3 Italy George 4 Italy George Group by and get count: df.groupby(['name', 'Country']).size() output: name Country George Germany 1 Italy 2 paul Germany 1 Italy 1 A: If you just want to the counts with respect to the name column, you don't need to use groupby, you can just use select the name column from the DataFrame (which returns a Series object) and call value_counts() on it directly: df['name'].value_counts()
doc_23528038
So how do I do it? I will be really thankful for that. A: You have added NavigationBar from the controls to your ViewController ie the reason it is looking like this. To solve the problem remove that NaviagtionBar from your controller and embed the NavigationController to embed to NavigationController follow this steps. * *Select Your ViewController. *Go to the "Editor" menu and select "Embed in" inside that select "Navigation Controller". So it should like Editor->Embed In->Navigation Controller. Edit: To change the color and title pragmatically add below code in viewDidLoad. navigationController.navigationBar.barTintColor = [UIColor redColor];//Set your color //To set title self.navigationItem.title = @"YourTitle"; A: From the link you posted to the screenshot, looks like you need to keep the uiview "Status bar View". One thing you can do is to extend the top constraint for the Status bar view should have a value of zero with "Constrain to margins" unchecked in the Add new constraints pop up in the storyboard designer. Something like Notice that the top constraint is with Superview and not with Top Layout Guide
doc_23528039
I want to show two values in the UI. The values are retrieved from the API Server, and I am using the Retrofit to get them. Here is my ApiService interface(Retrofit): interface ApiService { @Get fun getData1(): Observable<String> @Get fun getData2(): Observable<String> } And below is my Presenter code: val data1 = apiService.getData1().map { "d1" to it } val data2 = apiService.getData1().map { "d2" to it } Observable.just(data1, data2) .flatMap { it } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { (type, data) -> when (type) { "d1" -> view.showData1(data) "d2" -> view.showData2(data) } } It works fine. But this works sequentially. After the first request "getData1()" is done, the second request "getData2()" is sent. I want to send them concurrently. How can I do this? A: You can achieve concurrent connection using zip operator with RxKotlin. Example) val data1 = apiService.getData1() val data2 = apiService.getData1() Observables.zip(data1, data2) .subscribe { data -> view.showData1(data.first) view.showData2(data.second) }.addTo(compositeDisposable)
doc_23528040
NSArray *captureDeviceType = @[AVCaptureDeviceTypeBuiltInWideAngleCamera,AVCaptureDeviceTypeBuiltInMicrophone]; AVCaptureDeviceDiscoverySession *captureDevice = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:captureDeviceType mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified]; NSArray *deviceList = [captureDevice devices]; AVCaptureDevice *selectedCamera = [deviceList objectAtIndex:(NSUInteger)currentCameraDeviceIndex]; if ( [selectedCamera isFlashModeSupported:AVCaptureFlashModeAuto] ){ [selectedCamera setFlashMode:AVCaptureFlashModeAuto]; // AVCaptureFlashModeAuto } But in iOS 10 isFlashModeSupported and setFlashMode methods are deprecated. Xcode suggest to use AVCapturePhotoOutput's -supportedFlashModes instead. Is any idea how to use the above method? Thanks in advance A: Use this code. This works perfectly. AVCaptureSession *session = [[AVCaptureSession alloc] init]; [session setSessionPreset:AVCaptureSessionPresetPhoto]; AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; if ([device hasFlash]) { [device lockForConfiguration:nil]; device.flashMode = AVCaptureFlashModeAuto; [device unlockForConfiguration]; } A: How is it with this? AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if ([device hasFlash]) { if ([self.stillImageOutput.supportedFlashModes containsObject:[NSNumber numberWithInt:AVCaptureFlashModeOn]]) { }
doc_23528041
AttributeError: 'NoneType' object has no attribute 'send_keys' Below is my code. Any help is greatly appreciated! from webdriver_manager.chrome import ChromeDriverManager from selenium import webdriver from selenium.webdriver.common.keys import Keys def get_data(self): driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get("https://www.tradingview.com/#signin") driver.find_element_by_xpath('//*[@title="Linked In"]').click() # Switch to new window window_after = driver.window_handles[1] driver.switch_to.window(window_after) # Click into password field, send password element = driver.find_elements_by_class_name("form__input--floating")[1].click() element.send_keys("TestPassword") A: This error message... AttributeError: 'NoneType' object has no attribute 'send_keys' ...implies that your program is trying to invoke click() on a NoneType object. click() doesn't returns anything. So element remains NoneType object. Hence you see the error. Solution To sign into TradingView website through linkedin credentials you have to: * *Switch to the newly opened window *Induce WebDriverWait for the element_to_be_clickable() *You can use the following Locator Strategies: driver.get("https://www.tradingview.com/#signin") parent_window = driver.current_window_handle WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@title='Linked In']"))).click() WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) windows_after = driver.window_handles new_window = [x for x in windows_after if x != parent_window][0] driver.switch_to_window(new_window) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='password']"))).send_keys("BorangeOrange1337") *Browser Snapshot: A: click returns None, see source code here. Instead of selecting the element, you assign the return code (None) to your element. You probably want to first select your element and then in a separate statement click on it. Try the following snippet instead of the last two lines. element = driver.find_elements_by_class_name("form__input--floating")[1] element.click() element.send_keys("TestPassword")
doc_23528042
https://msdn.microsoft.com/en-us/library/jj819740(v=sql.120).aspx for learning SSDT now when i install first SSDT this setupd "SSDTBI_x86_ENU" then when i open visual studio and perform all setup but i stuck on task 7 i try to create DQS cleaning connection manager but this shows an error Failed to connect to DQS server the connection manager 'DQS Cleansing Connection Manager.local' as a result of the following value: A connection could not be made. Ensure that the server is running. System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): The network path was not found at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.Open() at Microsoft.Ssdqs.Proxy.Database.DBAccessClient..ctor(IDictionary`2 connectionData) at Microsoft.Ssdqs.Proxy.Database.DatabaseMetadataUtility..ctor(String instanceName, Boolean useEncryption) at Microsoft.Ssdqs.Component.Common.Utilities.ComponentUtility.GetDQDataBases(String connectionString) at Microsoft.Ssdqs.Component.Common.Utilities.ComponentUtility.IsDatabaseExist(String connectionString) at Microsoft.Ssdqs.Component.Common.UI.Common.DataCorrectionForm.ConnectionManagerChanged(Object sender, EventArgs e) ClientConnectionId:00000000-0000-0000-0000-000000000000 Error Number:53,State:0,Class:20 from SQL server configuration manager all services are up and running and when i try to run DQSInstaller from this path C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Binn this shows an error Microsoft (R) DQS Installer Command Line Tool Copyright (c) 2014 Microsoft. All rights reserved. [8/1/2017 12:33:06 PM] DQS Installer started. Installation log will be written to C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Log\DQS_install.log [8/1/2017 12:33:06 PM] Setting the collation to default value: SQL_Latin1_General_CP1_CI_AS [8/1/2017 12:33:06 PM] Failed to connect to local instance 'abc-user'. System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'CORP\my.name'. at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.Open() at Microsoft.Ssdqs.DqsInstaller.Utilities.InstallerUtility.TestConnection(String instance, Exception& exception) ClientConnectionId:13cdade8-344f-43f2-a968-931d2f37fcc5 Error Number:18456,State:1,Class:14 Press any key to continue... when i click SQL Server Data quality client and try to connect this shows an error image2 how i resolve this
doc_23528043
I am doing the SOAP call with the regular way: self::$client = new SoapClient($wsdl_url); self::$session = self::$client->login( $wsdl_usr, $wsdl_key ); self::$client->call( self::$session, 'product.list', $args ); I've searched about asynchronous SOAP calls in PHP, but I don't know how I would do it, because I need that data to be shown to the user. I have wsdl cache activated but still. Should I use ajax calls to have the client ready with a loader while calling for the content to free Apache? How other ways of handling this could I use? This SOAP call is made through a local IP already pointing in a private network, I thought this way the time would be much lesser. A: If the problem is Apache, then tweak Apache to handle more concurrent requests and not your PHP code. Then think how to make your SOAP Service faster rather changing PHP code.
doc_23528044
On the tab Project Summary enable LandscapeLeft mode, so I have to disable the rotation this way in the rest of the Viewcontroller, except in the VC of the image gallery. I want to keep the rotation in Portrait mode, to do this and to block all the VC portrait, I used the following code -(BOOL)shouldAutorotate{ return YES; } -(NSInteger)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskPortrait; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation } return UIInterfaceOrientationPortrait; } This, keep me the landscape mode in the previous VC , when it should be rotated to Portrait. Any idea do? A: For Portrait Mode VC, #pragma mark iOS 5 Orientation Support - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return UIInterfaceOrientationIsPortrait(interfaceOrientation); } #pragma mark iOS 6 Orientation Support -(NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } For Landscape mode VC, #pragma mark - iOS 5.0 and up Rotation Methods - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return UIInterfaceOrientationMaskLandscape; } #pragma mark - iOS 6.0 and up Rotation Methods - (NSUInteger)supportedInterfaceOrientations; { return UIInterfaceOrientationMaskLandscape; } If you are using navigationController, Create a category like this, @interface UINavigationController (Rotation_IOS6) @end @implementation UINavigationController (Rotation_IOS6) -(BOOL)shouldAutorotate { if([self.visibleViewController isMemberOfClass:NSClassFromString(@"YourLandscapeViewController")]) { return UIInterfaceOrientationMaskLandscape } return NO; } - (NSUInteger)supportedInterfaceOrientations { return [[self topViewController] supportedInterfaceOrientations]; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { if([self.visibleViewController isMemberOfClass:NSClassFromString(@"YourLandscapeViewController")]) { return UIInterfaceOrientationMaskLandscape } return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation]; } @end
doc_23528045
var regex = /^[0-9]+$/; if (myInput.val().match(regex)) { console.log("number"); } else { console.log("bad"); } It works well, but if I add text, then backspace all the way, I get "bad". How can I make it log "good" when there isn't anything in the text input? I don't want to allow spaces, but I want to allow an empty input. I tried: var regex = /\s ^[0-9]+$/; But then whatever I insert in the input, I always get "bad". A: This might fit , either you test for your Exp (^[a-zA-Z0-9]+$) or for an empty string (^$). var regex = /(^$)|(^[a-zA-Z0-9]+$)/; if (myInput.val().match(regex)) { console.log("number"); } else { console.log("bad"); } A: try this (* in place of +) var regex = /^[0-9]*$/; if (myInput.val().test(regex)) { console.log("number"); } else { console.log("bad"); }
doc_23528046
I have a ListBox populated by an XML file. I have managed to get a "Delete All" working, but I cannot manage to get a "Delete Single" working. Not sure how to get the attribute values from a node in a nodelist. I need to match the title attribute for the Bookmark Elements with lstBookmarks.Text which holds the text of the listbox selected item. Highlighted where the delete needs to take place( at least for my code). I will gladly accept totally rewritten code as long as it is explained. My XML looks like this <Data> <Bookmark title="Page 1" link="Some File Path Here" /> <Bookmark title="Page 2" link="Some Other File Path Here" /> </Data> My Delete Looks like this Private Sub DeleteToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DeleteToolStripMenuItem.Click If lstBookmarks.SelectedIndex = -1 Then MessageBox.Show("There are no bookmarks to clear!") ElseIf lstBookmarks.SelectedValue.ToString() = "" Then MessageBox.Show("There are no bookmarks to clear!") Else Dim xmlFile As String = filePath & "Resources\bookmark.xml" Dim XMLDoc As XmlDocument = New XmlDocument Dim nodes As XmlNodeList XMLDoc.Load(xmlFile) nodes = XMLDoc.SelectNodes("Data") Dim RootElement As XElement = XElement.Load(xmlFile) Dim DataElement As XmlElement = XMLDoc.DocumentElement Dim NewElement As XmlElement = XMLDoc.CreateElement("Bookmark") Dim FindElement = RootElement.<Bookmark>.Attributes("title") If DataElement.HasChildNodes Then For Each Attribute In FindElement If Attribute = lstBookmarks.Text Then '************************************************ 'Match found, delete node or XML Element here '************************************************ Else 'No Match in XML, no need to delete End If Next End If End If End Sub A: To find the element using the XmlDocument class, you can do so easily with XPath, like this: Dim xPath As String = String.Format("/Data/Bookmark[@title='{0}']", lstBookmarks.Text) Dim theNode As XmlNode = XMLDoc.SelectSingleNode(xPath) Or, you can find it using the XDocument or XElement class using LINQ to XML like this: Dim theElement As XElement = RootElement.<Bookmark>.First(Function(x) x.@title = lstBookmarks.Text) Or: Dim theElement As XElement = (From i As XElement In RootElement.<Bookmark> Where i.@title = lstBookmarks.Text Select i).First() You can use XPath to find nodes in XDocument / XElement objects as well.
doc_23528047
Basically the idea is use some copmpression method to reduce the amount of memory but without losing many precision. This thing needs to run in hardware so the computation overhead cannot be very high. In my algorithm I have to access to one value of the table do some operations with it and after update the value. In the end what I should have is a function which I pass an index to it and then I get a value, and after I have to use another function to write a value in the table. I found one called tile coding , this one is based on several look up tables, does anyone know any other method?. Thanks. A: I'd look at the types of numbers you need to store and pull out the information that's common for many of them. For example, if they're tightly clustered, you can take the mean, store it, and store the offsets. The offsets will have fewer bits than the original numbers. Or, if they're more or less uniformly distributed, you can store the first number and then store the offset to the next number. It would help to know what your key is to look up the numbers. A: I need more detail on the problem. If you cannot store the real value of the integers but instead an approximation, that means you are going to reduce (throw away) some of the data (detail), correct? I think you are looking for a hash, which can be an artform in itself. For example say you have 32 bit values, one hash would be to take the 4 bytes and xor them together, this would result in a single 8 bit value, reducing your storage by a factor of 4 but also reducing the real value of original data. Typically you could/would go further and perhaps and only use a few of those 8 bits , say the lower 4 and reduce the value further. I think my real problem is either you need the data or you dont, if you need the data you need to compress it or find more memory to store it. If you dont, then use a hash of some sort to reduce the number of bits until you reach the amount of memory you have for storage. A: Read http://www.cs.ualberta.ca/~sutton/RL-FAQ.html "Function approximation" refers to the use of a parameterized functional form to represent the value function (and/or the policy), as opposed to a simple table." Perhaps that applies. Also, update your question with additional facts -- don't merely answer in the comments. Edit. A bit array can easily store a bit for each of your millions of numbers. Let's say you have numbers in the range of 1 to 8 million. In a single megabyte of storage you can have a 1 bit for each number in your set and a 0 for each number not in your set. If you have numbers in the range of 1 to 32 million, you'll require 4Mb of memory for a big table of all 32M distinct numbers. See my answer to Modern, high performance bloom filter in Python? for a Python implementation of a bit array of unlimited size. A: If you are merely looking for the presence of the number in question a bloom filter, might be what you are looking for. Honestly though your question is fairly vague and confusing. It would help to explain what Q values are, and what you do with them once you find them in the table. A: If your set of integers is homongenous, then you could try a hash table, because there is a trick you can use to cut the size of the stored integers, in your case, in half. Assume the integer, n, because its set is homogenous can be the hash. Assume you have 0x10000 (16k) buckets. Each bucket index, iBucket = n&FFFF. Each item in a bucket need only store 16 bits, since the first 16 bits are the bucket index. The other thing you have to do to keep the data small is to put the count of items in the bucket, and use an array to hold the items in the bucket. Using a linked list will be too large and slow. When you iterate the array looking for a match, remember you only need to compare the 16 bits that are stored. So assuming a bucket is a pointer to the array and a count. On a 32 bit system, this is 64 bits max. If the number of ints was small enough we might be able to do some fancy things and use 32 bits for a bucket. 16k * 8 bytes = 524k, 2 million shorts = 4mb. So this gets you a method to lookup the ints and about 40% compression.
doc_23528048
For example, when working with inputs of size n, we typically assume that integers are represented by c lg n bits for some constant c 1. why do they assume it...? why c lg n...? Sorry for asking very easy question. Thank you in advance. A: So the n depends on the data you operate on. E.g. you have a value of 212, the value of lg n will be 8 (or 9). But this doesn't account for the actual data and machine type you operate on. It wouldn't be correct to assume that the word size is exactly 8 bits here. The constant c is for the case where you're working with small inputs on a huge word-size machine. The added factor of c allows us to assume that the machine word size is at least lg n, but possibly a lot larger, without messing up the analysis. To summarize n depends on the implementation independent numerical value. The amount of work a processor has to do for an operation does not depend on this value, but on how many bits are needed. Therefore the logarithm. The constant c refers to machine or implementation specific complexity. Does that help?
doc_23528049
Is it possible only using tailwind? I can't use animation-bounce since it's a bad user experience, because user needs to be able to click on the OK button. I also know that you can use a lot of animations and transitions, on hover: or other pseudo classes. But in my case, I want it to only appear from the bottom, without user interaction. Can I do that? A: Yes you can, you will need to use keyframes to create the custom animation. This is what I coded for a line which moves from left to right: // Inside theme.extend in tailwind.config.js keyframes: { 'moving-line': { from: { width: '0px', opacity: '0', }, to: { width: '30%', opacity: '0.6', }, }, }, animation: { 'moving-line': 'moving-line .8s ease .5s forwards', }, }, }, Then you can use it as animate-moving-line in the element's className. To make it appear from bottom, use translate-y property and create your own animation like above.
doc_23528050
* *I am getting the following error when i use mode as 'popup' as soon as i click on the editable link. TypeError: this.getCalculatedOffset is not a function *If i switch from popup to inline at-least the page appears however, the buttons dont appear correctly. Any feedback would be appreciated. Page Source is below:- <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>X-Editable Bootstrap Hello World!</title> <link rel="stylesheet" href="twitter-bootstrap/css/bootstrap.css" type="text/css"/> <link href="bootstrap-editable/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"> </head> <body> <div class="container"> <h1><a href="#">Hello World Bootstrap</a></h1> <div class="hero-unit"> <p>Hey.. this is my very first XEdit-able Bootstrap site.</p> <!-- <a href="#" id="username" data-type="text" data-placement="right" data-title="Enter username">superuser</a> --> <a href="#" id="username">superuser</a> </div> </div> <script src="http://code.jquery.com/jquery-2.0.3.js"></script> <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <script src="twitter-bootstrap/js/bootstrap.js"></script> <script src="bootstrap-editable/bootstrap3-editable/js/bootstrap-editable.js"></script> <script type="text/javascript"> $.fn.editable.defaults.mode = 'inline'; $(document).ready( function(){ //$('#username').editable(); $('#username').editable( { type: 'text', pk: 1, url: '/post', title: 'Enter username' }); } ); </script> </body> </html> A: Your bootstrap css and js files must be from 2.xx version of bootstrap, that's a problem. Use x-editable for bootstrap 2 or update your bootstrap to version 3+. A: I had the same issue after upgrading from Bootstrap 2 to Bootstrap 3. I had upgraded Bootstrap's CSS, X-Editable's CSS and JS, but had forgotten to upgrade Bootstrap's JS which was still for v2. Don't forget to update all files: * *Bootstrap 3 .css and .js *X-Editable for Bootstrap 3 .css and .js Probably a bit late, but hopefully that can still help someone.
doc_23528051
id market_id shows clicks event data 1 158 1000 300 on 2012-03-01 2 158 1500 600 off 2012-03-14 3 158 1500 600 on 2012-03-14 4 158 2500 700 off 2012-03-20 I want to select it and get array like this: $array = array ( array('from 2012-03-01 to 2012-03-14' => array('shows' => 500, 'clicks' => 300) array('from 2012-03-14 to 2012-03-20' => array('shows' => 1000, 'clicks' => 100) How to do that? Have I do that in Mysql or have I do that in php? edit: 'shows' in array calculates like that 1500 - 1000, 1500 is from table where 'event' is off and 1000 is from table where 'event' is on, click's calculate same. A: Caveat: I can't really work out what your intention is and hence there may be much better solutions that this but... Here's a query that works on your sample data. SELECT t2.data as from_date, t1.data as to_date, (t1.shows-t2.shows) as shows, (t1.clicks - t2.clicks) as clicks FROM `market` t1 inner join market t2 on (t1.market_id=t2.market_id and t1.event='off' and t2.event='on' and t1.data>t2.data) left join market t3 on (t1.data>t3.data and t3.event='on' and t3.data>t2.data) WHERE t3.id is null To explain a little bit: the query joins the table onto it self to find all pairs of rows where one represents an "off" event that is later than an "on" event. This picks up all pairs (even 2012-03-20 'off' and 2012-03-01 'on') so then we do a LEFT JOIN again to check there are no other 'on' events between the 'on' row and the 'off' row. btw, I think there's an error in your sample results. The values for "shows" in your second result should be 1000.
doc_23528052
Here is my Java code for the applet: import java.applet.*; import javax.swing.*; import netscape.javascript.*; import java.net.*; import java.io.*; import java.awt.*; public class JavaSocketBridge extends JApplet { // Instance variables JSObject browser = null; // The browser Socket socket = null; // The current socket PrintWriter out = null; // Output Listener listener = null; // Listens for input boolean running = false; // Am I still running? String address = null; // Where you will connect to int port = -1; // Port boolean connectionDone = false; // Thread synchronization public String message = ""; // Initialize public void init(){ try { browser = JSObject.getWindow(this); //see bottom of code for comment } catch(Exception e) { message += "EXCEPTION: " + e.getMessage() + " THIS: " + this; } } // Stop and destroy public void stop(){ running = false; disconnect(); } public void destroy(){ running = false; disconnect(); } public void start(){ //other code here } } I have tried moving the browser = JSObject.getWindow(this); line to the beginning of the start() method as suggested here, but I still remain without luck. And the text contained in the message variable is: Message: EXCEPTION: null THIS: JavaSocketBridge[panel50,0,0,0x0,invalid,layout=java.awt.BorderLayout,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,f,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true] Here is my PHP file: <!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 charset="utf-8"> <script type="text/javascript" src="JavaSocketBridge/java_socket_bridge.js"></script> </head> <body> <applet id="JavaSocketBridge" code="HelloWorldApplet.class" archive="./JavaSocketBridge/JavaSocketBridge.jar" height="200" width="2000"></applet>; <?php echo " <script> console.log('Applet is connected: ' + socket_connect('".$_SESSION['ip']."', '".$_SESSION['port']."')); console.log('Flag Status: ' + is_ready()); </script>"; ?> </body> </html>
doc_23528053
SELECT * FROM ( SELECT c.CompanyName, p.ProductName, od.Quantity FROM Customers as c INNER JOIN Orders as o ON c.CustomerID = o.CustomerID INNER JOIN [Order Details] as od ON o.OrderID = od.OrderID INNER JOIN Products as p on od.ProductID = p.ProductID ) as QuantityOrdered pivot ( (CASE WHEN SUM(Quantity) is NULL THEN 0 ELSE SUM(Quantity) END) for ProductName in ([Alice Mutton], [Aniseed Syrup], [Boston Crab Meat], [Camembert Pierrot], [Carnarvon Tigers]) ) as crossTabTable order by CompanyName A: PIVOT only allows simple aggregation functions and a single column, no other expressions. You can instead use conditional aggregation, which is more wordy but much more flexible. SELECT c.CompanyName, [Alice Mutton] = ISNULL(SUM(CASE WHEN p.ProductName = 'Alice Mutton' THEN od.Quantity END), 0), [Aniseed Syrup] = ISNULL(SUM(CASE WHEN p.ProductName = 'Aniseed Syrup' THEN od.Quantity END), 0), [Boston Crab Meat] = ISNULL(SUM(CASE WHEN p.ProductName = 'Boston Crab Meat' THEN od.Quantity END), 0), [Camembert Pierrot] = ISNULL(SUM(CASE WHEN p.ProductName = 'Camembert Pierrot' THEN od.Quantity END), 0), [Carnarvon Tigers] = ISNULL(SUM(CASE WHEN p.ProductName = 'Carnarvon Tigers' THEN od.Quantity END), 0) FROM Customers as c INNER JOIN Orders as o ON c.CustomerID = o.CustomerID INNER JOIN [Order Details] as od ON o.OrderID = od.OrderID INNER JOIN Products as p on od.ProductID = p.ProductID GROUP BY c.CompanyName ORDER BY c.CompanyName;
doc_23528054
Current Dockerfile: FROM maven:3.6.2-jdk-11 AS maven WORKDIR /tmp/ # Set the local repository to /tmp/.m2/repository RUN echo \ "<settings xmlns='http://maven.apache.org/SETTINGS/1.0.0\' \ xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \ xsi:schemaLocation='http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd'> \ <localRepository>/tmp/.m2/repository</localRepository> \ <interactiveMode>true</interactiveMode> \ <usePluginRegistry>false</usePluginRegistry> \ <offline>false</offline> \ </settings>" \ > /usr/share/maven/conf/settings.xml; # TODO: How to perform -v ~/.m2/:/tmp/.m2/ but only using `docker build`? COPY pom.xml /tmp/ RUN mvn dependency:resolve RUN mvn dependency:resolve-plugins COPY src /tmp/src/ RUN mvn package FROM openjdk:11-jre-slim EXPOSE 8080 RUN apt update RUN apt -y install curl WORKDIR /usr/app ENV TARGET="<target name>.jar" COPY --from=maven "/tmp/target/$TARGET" . CMD ["java", "-jar", "$TARGET"] And of course this doesn't work: Update: I'm able to mount a folder pointing to the local .m2 repo and copy the whole folder into the docker image. However, now I cannot make mvn use that local repo. Then COPY pom.xml /tmp/ RUN mvn -o -s /usr/share/maven/conf/settings.xml dependency:resolve -X results in the error: Cannot access central (https://repo.maven.apache.org/maven2) in offline mode and the artifact com.myapp:somename:pom:1.0.4 has not been downloaded from it before. A: An idea, that you can do is caching the maven dependencies in the docker. You can make use of mvn dependency-offline (https://maven.apache.org/plugins/maven-dependency-plugin/), doing the dependency-offline maven resolve the dependencies needed in preparation for going offline and reuse them as long as the pom.xml still be the same
doc_23528055
I have tried a lot of ways and read many things online. But, it seems like this is not supported in jersey yet. Any help will be greatly appreciated. One of the Sample Code that i tried. ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true); clientConfig.getClasses().add(ProtobufMessageBodyReaderWriter.class); CLIENT = Client.create(clientConfig); CLIENT.resource(BASE_URL); webResource = CLIENT.resource(BASE_URL); T response = null; ClientResponse cResponse = null; cResponse = webResource.type(MediaType.APPLICATION_JSON).method("PATCH",ClientResponse.class, requestObject); This gives "java.net.ProtocolException: HTTP method PATCH doesn't support output" . Can anyone suggest me on how to get this done the above way or any other way A: From quickly reading on Jersey's forum, there seems to be a bug. Can you use an HTTP client instead of webResource.type(...).method("PATCH")? Use Apache HTTP Commons for instance.
doc_23528056
The PreparedStatement is a slightly more powerful version of a Statement, and should always be at least as quick and easy to handle as a Statement. The Prepared Statement may be parametrized Most relational databases handles a JDBC / SQL query in four steps: * *Parse the incoming SQL query *Compile the SQL query *Plan/optimize the data acquisition path *Execute the optimized query / acquire and return data A Statement will always proceed through the four steps above for each SQL query sent to the database. A Prepared Statement pre-executes steps (1) - (3) in the execution process above. Thus, when creating a Prepared Statement some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time. Now here is my question: If I use hundreds or thousands of Statement, will it be cause performance problems in database? (I don't mean that they will perform slower because of more jobs to do every time). Will all those statements be cached in database or they will be lost in space as soon as they are executed? A: Since there is no restictions on using prepared statements, you should work carefully with them. As you said you need hundreds of prepaired, think twice may be you are using it wrong. The pattern it should be used is having an application that doing a haevy inserts/updates/select hundred or thousand times a second which only differs in variables. So in real world it would be like, connecting, creating session, sending statement, and sending bunch of variables to that statement. But if your plan is to create prepared on each single operations, it's just better to use common queries. On your questions: * *Hundreds of statements will not kill mysql or drive you to performance degradation *The prepared are stored in memory while client session is up and running. As soon as you close session the prepared die. To be sure you need it: * *Your app able to execute statements fast so you get speed value of using them *Your query will not have a variable number of arguments, otherwise you can kill you app by creating objects and storing in memory on every statement
doc_23528057
*.sitename.com And one of white label client using it's website with https://subdomain.whitelabel.com And he is getting certificate error. What is best practice to avoid this?
doc_23528058
I have to call error function if any error is detected in a bit. My solution is the following: const int arrSize = 3; void bitComparator() { uint8_t myArr[arrSize] = {0, 1, 64}; //array storing system status uint8_t mask; //bit mask uint8_t maskResult; for(int i=0; i<arrSize; i++) { mask = 1; // mask is 0000 0001 for(int j=0; j<8; j++) { maskResult = mask & myArr[i]; if(maskResult != 0) errFunc(i, j); mask <<= 1; } } If myArr is as wide as n, then the solution is O(n) complexity. Could you suggest any improvement on the solution regarding complexity or efficiency? It might as well be already OK, but I am not sure. Note: I need to know the position having error. A: Since you need to call errFunc for each set bit then you need an O(N) solution since you have to visit every bit. You can make life a little easier and use a std::bitset which would make the code look like void errFunc(int index, int bit) { std::cout << "Error in index " << index << " bit " << bit << "\n"; } const int arrSize = 3; void bitComparator() { uint8_t myArr[arrSize] = {0, 1, 64}; //array storing system status for(int i=0; i<arrSize; i++) { std::bitset<8> bitset{myArr[i]}; for(int j=0; j<8; j++) { if(bitset[j]) errFunc(i, j); } } } int main() { bitComparator(); } which has the output of Error in index 1 bit 0 Error in index 2 bit 6 A: How common are errors? That is, will there be a bunch of bits set most of the time? If not, divide and conquer: if (myArr[i] != 0) if(myArr[i] & 0x0F) // process low 4 bits if (myArr[i] & 0xF0) // process high 4 bits
doc_23528059
Can anyone give me some hints :D?
doc_23528060
This didn't help me. I'm trying to match momentaneousVehicleSpeedKmph= followed by anything but 9 in a gz file. These don't match: $zgrep "momentaneousVehicleSpeedKmph=\[\^9\]" file.gz $zgrep "momentaneousVehicleSpeedKmph=\(\^9\)" file.gz $zgrep "momentaneousVehicleSpeedKmph=\^\[9\]" file.gz $zgrep "momentaneousVehicleSpeedKmph=\^\(9\)" file.gz This does: $zgrep "momentaneousVehicleSpeedKmph=\(9\)" file.gz I now there're lines in the file containing momentaneousVehicleSpeedKmph=89. A: simply try $zgrep "momentaneousVehicleSpeedKmph=[^9]" file.gz if you don't want to match the single 9. /edit If you also need speeds with 2 digits and more, try: momentaneousVehicleSpeedKmph=([0-8]|[0-9]{2,})\b
doc_23528061
In other words, is there a better way to write the following code: df.loc[df['A'] >5].index Thanks! A: Yes, better is filter only index values, not all DataFrame and then select index: #filter index df.index[df['A'] >5] #filter DataFrame df[df['A'] >5].index Difference is in performance too: np.random.seed(1245) df = pd.DataFrame({'A':np.random.randint(10, size=1000)}) print (df) In [40]: %timeit df.index[df['A'] >5] 208 µs ± 11.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [41]: %timeit df[df['A'] >5].index 428 µs ± 6.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [42]: %timeit df.loc[df['A'] >5].index 466 µs ± 40.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) If performance is important use numpy - convert values of index and column by values to numpy array: In [43]: %timeit df.index.values[df['A'] >5] 157 µs ± 8.71 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [44]: %timeit df.index.values[df['A'].values >5] 8.91 µs ± 196 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
doc_23528062
I could do: $notifications = $user->notifications() ->where('type', MyNotification::class) ->get(); Is it the right way to do this? Did I miss something? A: Since there are no any option to change the type in the notification this is the best option you've got.
doc_23528063
So I want to make an if statement that if the messagebox is displayed, then stop the timer, until the button is clicked once again. I tried using this: private void button1_Click(object sender, EventArgs e) { timer1.Start(); if (errormsg) { timer1.Stop(); } data(); } private void data() { //code Now here's what's in my timer1 code: private void timer1_Tick(object sender, EventArgs e) { int value; if (int.TryParse(textBox1.Text, out value)) { if (value > 0) { timer1.Interval = value; } } button1.PerformClick(); } here's the error message: private void errormsg() { MessageBox.Show("Sorry, there was an error. Please, try again."); } I will also note that I'm using errormsg in an else statement on my //code //code else { errormsg(); } So my question is: How can I make the timer stop, if a wrong value is displayed on my textbox (//code) causing a messagebox to appear. Then, when a correct value is displayed on a textbox, and I click the button, the timer would start again? A: Stop the timer in your errormsg() function. When you clicked the button1 it starts again. private void button1_Click(object sender, EventArgs e) { timer1.Start(); data(); } private void errormsg() { timer1.stop(); MessageBox.Show("Sorry, there was an error. Please, try again."); }
doc_23528064
public static String evaluateJavaScriptExpression(String expression) throws ScriptException { if (expression == null) { return null; } ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine javaScriptEngine = scriptEngineManager.getEngineByName(JAVASCRIPT_ENGINE); return String.valueOf(javaScriptEngine.eval(expression)); } for which I created some unit tests. One of them goes like this: String expression = "var arr = [1, 3, 2, 5, 4]; arr.indexOf(0);"; assertEquals("-1", ExpressionEvaluatorUtil.evaluateJavaScriptExpression(expression)); It worked fine for me while I was using java version "1.8.0_91". But someone who used java version "1.8.0_92" reported that the test is failing. I switched my version to build 92 and it failed for me as well. The actual result for it is "-1.0". Also, i tried the same js code in Chrome console and it is returning "-1" as in build 91. Does anyone know why there is such difference in results between the two jdk versions? Is this a bug or it was purposely changed? A: Well, if you know the precise version number of the change, you know where to look: the list of 1.8u92 bugfixes lists some fixes regarding Nashorn, the most interesting being JDK-8144020: Remove long as an internal numeric type ECMA defines double as the only number type in JavaScript. In Nashorn, we internally represent numbers as int, long and double. Use of long is problematic because it adds extra precision to the 53 bits provided by double. … At the first glance, this seems to be an internal change only, but the picture changes, if you realize that your former result stemmed from the fact that previously, eval returned a Long for this code, being formatted to "-1". Now consider the first sentence of this bug report: “ECMA defines double as the only number type in JavaScript”. This leads to the conclusion that returning a Long was not a specified result type, but an implementation artifact. So apparently, when long was removed from the internal usage, the possibility to return Long was eliminated and the engine now doesn’t return Integer instead, but Double, as a byproduct of the change. This explains, why there are other scripts like "var str = 'abcd'; str.indexOf('x');" which still produce an output without fractional digits. The latter script evaluated to Integer and still does. Since the change of the output type was a byproduct of removing internal long usage, not an intentional action to change all non-Double numeric results, places internally using int were not affected. When comparing the result with Chrome’s engine, you have to consider that you are only comparing formatted output, with the number to string conversion not being part of the script. So the outcome is unspecified. The browser may take the freedom to present all numeric values matching an integer value without fractional digits. A: If we take a look at the java documentation for ScriptEngine.eval(String input) method, it returns an object, then it is upto the developer using to typecast the object to correct type as per return type of javascript. So, I think the the problem is with String.valueOf() method call, Evaluation of expression returns a floating point number. I think you will have to change your code to do Integer.valueOf(javaScriptEngine.eval(expression)); Hope this helps :)
doc_23528065
The problem is that the Do Loop i wrote, can not catch the file and hangs. It just works well when i debug it through F8. Then i thought maybe by application.wait method I can let the sub to wait till the workbook appears, like what happens in debug mode but it didnt help as well. Also i need to add that since everytime the file gets downloaded its name changes by the webiste then i used Like operator. Sub Test() Dim wb As Workbook Dim wbName As String Dim Cnt As Integer wbName = "transactions_history_" 'Application.Wait Now + TimeValue("00:00:10") ' it didnt help so i commented it Do Application.Wait Now + TimeValue("00:00:01") For Each wb In Application.Workbooks If wb.Name Like wbName & "*" Then Cnt = 1 Exit Do End If Next wb Loop Until Cnt = 1 wb.Close End Sub Anybody has any idea? thanks. FaneDuru, I copy here the code which downloads the workbook from the website. it worked very well until the website changed something and when the file gets downloaded it gets opened too. I need to close it to let the rest of the programms work without problem but i coudlnt manage it so far. Sub TBC() ' declerations Dim myBrowser As Selenium.ChromeDriver Dim FindBy As New Selenium.by Dim objFSO As Object Dim objFolder As Object Dim objFile As Object Dim A, I As Integer Dim FileName, BankFolderAddress As String Dim N As Byte ' initializations BankFolderAddress = "D:\Projects\Excel\Main Program\Bank Statements\" Set FindBy = New Selenium.by Set myBrowser = New WebDriver I = 0 A = 0 Sheet2.Cells.ClearContents Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.GetFolder(BankFolderAddress) For Each objFile In objFolder.Files Sheet2.Cells(I + 1, 1) = objFile.Name Sheet2.Cells(I + 1, 2) = objFile.Path I = I + 1 Next objFile If Sheet2.Cells(1, 1) <> "" Then For N = 1 To I Kill Sheet2.Cells(N, 2).value Next N End If Start: myBrowser.SetProfile Environ("LOCALAPPDATA") & "\GOOGLE\CHROME\USER DATA" myBrowser.AddArgument "profile-directory=Default" myBrowser.Start "chrome" Application.DisplayAlerts = False 'Address e website myBrowser.Get "https://tbconline.ge/tbcrd/login?t=false" myBrowser.Window.Maximize A = 0 Do Application.Wait Now + TimeValue("00:00:01") A = A + 1 If A = 10 Then GoTo Finish Loop Until myBrowser.IsElementPresent(FindBy.XPath("//button")) If myBrowser.IsElementPresent(FindBy.Css("input[formcontrolname='username']")) Then myBrowser.FindElementByXPath("//button").Click Else GoTo JMP End If JMP: 'For removing PopUps If myBrowser.IsElementPresent(FindBy.XPath("//div[@id='mainLoadingLayer']/ui-view/ui-view/div/div[2]/div/div/div/div/div[3]/button")) Then myBrowser.FindElementByXPath("//div[@id='mainLoadingLayer']/ui-view/ui-view/div/div[2]/div/div/div/div/div[3]/button").Click End If ' Choosing Transaction Menu A = 0 Do Application.Wait Now + TimeValue("00:00:01") A = A + 1 If A = 10 Then GoTo Finish Loop Until myBrowser.IsElementPresent(FindBy.XPath("//a[contains(text(),'Transactions')]")) If myBrowser.IsElementPresent(FindBy.XPath("//a[contains(text(),'Transactions')]")) Then myBrowser.FindElementByXPath("//a[contains(text(),'Transactions')]").Click End If 'choosing Transaction submenu A = 0 Do Application.Wait Now + TimeValue("00:00:01") A = A + 1 If A = 10 Then GoTo Finish Loop Until myBrowser.IsElementPresent(FindBy.XPath("//span[contains(.,'Transactions')]")) If myBrowser.IsElementPresent(FindBy.XPath("//span[contains(.,'Transactions')]")) Then myBrowser.FindElementByXPath("//span[contains(.,'Transactions')]").Click End If 'Clicking on Download icon Do Application.Wait Now + TimeValue("00:00:01") Loop Until myBrowser.IsElementPresent(FindBy.XPath("//ib-controls/div/div[2]/div[2]")) If myBrowser.IsElementPresent(FindBy.XPath("//ib-controls/div/div[2]/div[2]")) Then myBrowser.FindElementByXPath("//ib-controls/div/div[2]/div[2]").Click End If ' clicking on excel option to download it Do Application.Wait Now + TimeValue("00:00:01") Loop Until myBrowser.IsElementPresent(FindBy.XPath("//a[contains(.,'Excel')]")) If myBrowser.IsElementPresent(FindBy.XPath("//a[contains(.,'Excel')]")) Then myBrowser.FindElementByXPath("//a[contains(.,'Excel')]").Click End If 'checking if the file is downloaded Do Application.Wait Now + TimeValue("00:00:02") Loop Until Dir(BankFolderAddress & "transactions_history_*.xlsx") <> "" ' get the file name FileName = Dir(BankFolderAddress & "transactions_history_*.xlsx", vbDirectory) ' check if the downloaded file size Do Application.Wait Now + TimeValue("00:00:05") '03 bood Loop Until FileLen(BankFolderAddress & FileName) > 10000 Finish: ' close the Browser myBrowser.close ' ## I added this code to close the workbook but failed ' call Test() Dim wb As Workbook Dim wbName As String Dim Cnt As Integer wbName = FileName Do Application.Wait Now + TimeValue("00:00:01") For Each wb In Application.Workbooks If wb.Name=FileName Then Cnt = 1 wb.Close Exit Do End If Next wb Loop Until Cnt = 1 call BankDataExtraction() End Sub the problem is that if i do not stop the sub before the loop in debug mode, the downloaded workbook neither appears on the screen nor in task manager, and the loop can not catch it and close it, it hangs then. wait methode doesnt help too. I tried you code but it gave me automation error invalid syntax, while executing Set sessEx = GetObject(wbFullName).Application I passed the complete file address to it, If Not sameExSession(FileName). A: If you are sure that the wbName is the name of the workbook searching for, your code must do what you need, but only if the workbook in discussion is open IN THE SAME EXCEL SESSION. I asked about the code opening it, but no clarification received. Please, use the next function to check if the workbook is open in the same session (with the workbook keeping the checking code). If its second parameter is True, it closes the workbook, even in a different session and quit that session. Many codes searches for an existing Excel session and use it, but open a new session if no such a session has been found. Others, uses a new session: Function sameExSession(wbFullName As String, Optional boolClose As Boolean) As Boolean Dim sessEx As Excel.Application, wb As Workbook Set sessEx = GetObject(wbFullName).Application If sessEx.hwnd = Application.hwnd Then sameExSession = True Else sameExSession = False If boolClose Then sessEx.Workbooks(Right(wbFullName, Len(wbFullName) - InStrRev(wbFullName, "\"))).Close False sessEx.Quit: Set sessEx = Nothing End If End If End Function It can be called from your existing code in this way: Sub Test() Dim wb As Workbook, wbName As String, Cnt As Integer wbName = "transactions_history_" If Not sameExSession Then Exit Sub 'take care to use the workbook FULL NAME! Do Application.Wait Now + TimeValue("00:00:01") For Each wb In Application.Workbooks If wb.Name Like wbName & "*" Then Cnt = 1 Exit Do End If Next wb Loop Until Cnt = 1 wb.Close End Sub If you do not know the workbook extension (since you do not use it in your above code), you can obtain the workbook name using: Dim strFullName As String, foldName As String foldName = "path to the folder where the workbook is downloaded" strFullName = dir(foldName & "\" & vbname & "*.*") If strFullName <> "" Then If Not sameExSession Then Exit Sub Else MsgBox "Strange...": Stop 'Just in case. It must be found, if foldName and vbName are correct... End If It may fail if in the same folder there are more then one such a workbook having a name containing the used string. It will return the first of them, in alphabetical order. But, if such a case, you are the one who is needed to bring some clarifications... Of course, if opening in the other session is the correct assumption. In such a case a piece of code can iterate between all those workbooks having the same string in their name, to determine the last saved one. You can be sure about this aspect (other session), manually searching for the workbook, copying its Full name and create a testing Sub which only calls the function I supplied, using the determined its full name.
doc_23528066
now i finished devloping of my web site using visual studio 2013 and start to publish it 1- here i choose to import publish settings file that i get it from the Hosting web site 2- then add the conniction configuration and vakidate it 3- then i registered the Data base connecion connection string and validate it 4- but after finish i get the below message could any one tell me may be where i the problem ??? A: Our SQL Server doesn't have the Data-Tier Application Framework (DACfx). As such, you can't deploy your database along with your files. Feel free to deploy your files via Web Deploy, then create your database inside WebsitePanel. You can export the database from your project and import it by clicking on the Database inside WebsitePanel.
doc_23528067
def mem_test(): printMemUsed("before r list") r = ['Supporter'] * 100000000 printMemUsed("after r list") r_arr = np.array(r) printMemUsed("after nd_array") tf.convert_to_tensor(r_arr) printMemUsed("after tensor conversion") def printMemUsed(discript): print("{}:\t{}".format(discript, psutil.virtual_memory().used)) Here's the ouput: before r list: 727310336 -> 727 Mb after r list: 1528782848 -> 1.5 GB after nd_array: 2430574592 -> 2.4 GB after tensor conversion: 8925667328 -> 8.9 GB edit: r_arr had a dtype of 'S9' (null terminated string). After changing the input array element to type 'unicode' (U9), the virtual memory consumption bumped up to 5 GB after nd_array A: tf.convert_to_tensor uses a _tensor_conversion_func_registry were conversions functions are registered for different input types. For Python list, tuple and numpy nd.arrays this happens in constant_op.py. And according to this answer tf.constant creates at least two copies. Why is the value of a tf.constant() stored multiple times in memory? Because data for a constant tensor is embedded into graph definition. This means this data is stored both in the client, which maintains the graph definition, and in the runtime, which allocates it's own memory for all tensors: Edit: According to this answer one option is to use tf.Variable and initialize it with a tf.placeholder.
doc_23528068
int main(int argc, char** argv) { //Initialize Random Seed once here! //Declare Variables int choose, cColor, rDraw, board, draw;//Choose //Initialize variables here do{ //List of Problems which can be run by the program cout<<" ****************************"<<endl; cout<<" * Welcome to Sorry! *"<<endl; cout<<" ****************************"<<endl; cout<<"Enter 0 to Start Game"; cout<<"\tEnter 1 for How To Play"<<endl; cout<<" Press Any Key to Exit"<<endl; cin>>choose; switch(choose){ case 0:cout<<"******************************"<<endl; cout<<"What color would you like to be?"<<endl; cout<<"1. Red"<<endl; cout<<"2. Blue"<<endl; cout<<"3. Yellow"<<endl; cout<<"4. Green"<<endl; cin>>cColor; switch(cColor){ case 1: cout<<"You have chosen Red."<<endl; break; case 2: cout<<"You have chosen Blue."<<endl; break; case 3: cout<<"You have chosen Yellow."<<endl; break; case 4:cout<<"You have chosen Green."<<endl; break; default: cout<<"ERROR Please only choose 1-4"<<endl; } cout<<endl; do{ srand(static_cast<unsigned int>(time(0))); //seed the random number rDraw = rand() % 11 + 1; if(rDraw== 1){ //this is the trouble and downwards implenting until 50 and displaying it. board++; cout<<board; cout<<endl; cin>>draw; cout<<endl; break; } else if(rDraw== 2){ board=board+2; cout<<board; cout<<endl; cin>>draw; cout<<endl; break; } else if(rDraw== 3){ if (board== 0) { cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl; break; } else{ board=board+3; cout<<board; cout<<endl; cin>>draw; cout<<endl; } break; } else if(rDraw== 4){ if (board== 0) { cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl; break; } else{ board--; cout<<board; cout<<endl; cin>>draw; cout<<endl; } break; } else if(rDraw== 5){ if (board== 0) { cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl; break; } else{ board=board+5; cout<<board; cout<<endl; cin>>draw; cout<<endl; } break; } else if(rDraw== 6){ if (board== 0) { cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl; break; } else{ board=board+7; cout<<board; cout<<endl; cin>>draw; cout<<endl; } break; } else if(rDraw== 7){ if (board== 0) { cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl; break; } else{ board=board+8; cout<<board; cout<<endl; cin>>draw; cout<<endl; } break; } else if(rDraw== 8){ if (board== 0) { cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl; break; } else{ board=board+10; cout<<board; cout<<endl; cin>>draw; cout<<endl; } break; } else if(rDraw== 9){ if (board== 0) { cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl; break; } else{ board=board+11; cout<<board; cout<<endl; cin>>draw; cout<<endl; } break; } else if(rDraw== 10){ if (board== 0) { cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl; break; } else{ board=board+12; cout<<board; cout<<endl; cin>>draw; cout<<endl; } break; } else{ cout<<"11"<<endl; break; } }while(board !=50 && draw== 1); break; case 1:cout<<"Place Problem 1 here"<<endl;break; default:cout<<"Exiting the Menu"<<endl; } }while(choose>=0 && choose<=2); //Exit the program return 0; } A: Excessive use of nesting is usually a bad practice. Try to remove the hierarchy and make it as flat as possible. It will also help you to better visualize your code and catch bugs. For these show menu-read input type of code, the loop and a half pattern is usually the best coding style.
doc_23528069
A: If you are using a RecyclerView with GridLayoutManager, then you can get the firstVisisbleItem and lastVisibleItem. This should give you the number of visibleItems with which you can decide the index in the grid where you should not show any item. This would require you to take care of some implementation level details, but the basic logic should be like this only. Hope it helps.
doc_23528070
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Stack Trace: [NullReferenceException: Object reference not set to an instance of an object.] Microsoft.SharePoint.WebControls.CompositeField.get_Visible() +41 System.Web.UI.Control.PreRenderRecursiveInternal() +22 System.Web.UI.Control.PreRenderRecursiveInternal() +223 System.Web.UI.Control.PreRenderRecursiveInternal() +223 System.Web.UI.Control.PreRenderRecursiveInternal() +223 System.Web.UI.Control.PreRenderRecursiveInternal() +223 System.Web.UI.Control.PreRenderRecursiveInternal() +223 System.Web.UI.Control.PreRenderRecursiveInternal() +223 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3393 The errors started occurring after I started using <SharePoint:CompositeField> in my form. I may be wrong, but I'm attempting to use this control as I thought it would automatically adapt to the different field types of my various fields as well as adjusting to the page mode (new, edit, or display). I suspect I'm using it incorrectly, but the MSDN documentation and any documentation I can find from surfing the web is rather sparse... How should I use this control? Or should I just break-down and manually deal with each individual field using basic asp.net controls? Are there better options? Amongst the couple dozen fields, a few need custom work - if not for them, the rest of the fields would be handled fine with SharePoint's default list item forms. In my *.aspx page, under the PlaceHolderMain content element, I'm using the control like this: <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server"> <!-- more content --> <div id="main-form"> <!-- more content --> <div> <asp:Label runat="server" ID="LTSAttachmentsLabel" AssociatedControlID="LTSAttachmentsCompositeField" Text="Attach File" CssClass="label"></asp:Label> <SharePoint:CompositeField runat="server" ID="LTSAttachmentsCompositeField" FieldName="LTS Attach File" /> </div> <!-- about two dozen <div> tags; much of it similar to the above with Label and CompositeField controls --> </div> <!-- more content --> </asp:Content> I started with strictly declarative use, but after a series of errors and attempts to fix them, I'm now performing the following in my page PreInit and Load events: protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); _currentWeb = SPContext.Current.Web; // page-scoped property string listGuid = Request.QueryString["List"]; _formList = _currentWeb.Lists[new Guid(listGuid)]; // page-scoped property string itemGuid = Request.QueryString["Item"]; if (!itemGuid.IsNullOrEmptyTrimmed()) { _itemID = itemGuid.ToIntegerNullSafe(); // page-scoped property _item = _formList.GetItemById(_itemID.Value); // page-scoped property } _pageMode = (SPControlMode)Enum.Parse(typeof(SPControlMode), Request.QueryString["ControlMode"]); // page-scoped property if (SPContext.Current.FormContext.FormMode == SPControlMode.Invalid && _pageMode != SPControlMode.Invalid) { SPContext.Current.FormContext.FormMode = _pageMode; } if (Request.QueryString["IsDlg"] != null) { _formIsDialog = Request.QueryString["IsDlg"] == "1"; // page-scoped property } if (Request.QueryString["ID"] != null) { _itemID = int.Parse(Request.QueryString["ID"]); // page-scoped property, unnecessary redundancy? } } protected void Page_Load(object sender, EventArgs e) { // unrelated code var spControls = from c in this.GetChildControlsRecursive() where c is CompositeField select c; foreach (CompositeField cf in spControls) { cf.ListId = _formList.ID; cf.ItemId = _itemID ?? -1; } // unrelated code } For the curious, GetChildControlsRecursive returns all child controls as a flat enumerable collection rather than a hierarchical collection. // extension class in separate file public static class ControlExtensions { public static IEnumerable<Control> GetChildControlsRecursive(this Control parentControl) { Stack<Control> todo = new Stack<Control>(); HashSet<Control> results = new HashSet<Control>(); todo.Push(parentControl); results.Add(parentControl); while (todo.Count > 0) { Control parent = todo.Pop(); foreach (Control child in parent.Controls) if (results.Add(child)) todo.Push(child); } return results; } } A: Initially I dropped the whole idea of using the SharePoint:CompositeField and similar controls. I went back to using basic ASP.Net controls. Except for handling attachments, this worked fine. But I couldn't figure out how to handle the attachments, but in my research for solutions I noticed that I might be able to resume using the default SharePoint list forms. So that is what I tried, but then I ran into problems with the lookup fields. I could not get them working with declarative XML, the fields had to be created during feature activation. This in turn led to problems with the field sequence. The lookup fields all appeared at the end of the form instead of their proper place amongst the rest of the fields. I attempted to fix this by using the FieldLinksCollection.Reorder(string[]) method, but this failed to update the list with the new field sequence. Eventually, I used a combination of declarative XML to define my site columns, content types, list definitions, and list instances. I then used the default list forms. Though the lookup fields were present in the XML, they did not bind properly, I found some code suggesting a way to programmatically fix the broken binding: https://stackoverflow.com/a/18192756/1075980. This combination of actions resolved my problems. A: Im not sure if this applied to your situation, but it might help other googlers troubleshooting this error. I got the same error and found that the cause was that I accidentally snuck a <SharePoint:CompositeField runat="server" /> into my form template below my ListFieldIterator. I believe the composite field belongs either in a field control or must have a property defined that tells it which field to render.
doc_23528071
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell cell.bottomView.isHidden = true } internal func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.width, height: collectionView.frame.height) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.lableArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell let item = lableArray[indexPath.row] cell.imageView.backgroundColor = UIColor.randomColor() cell.lable.text = item return cell } A: Resolved it by updating let cell=collectionView.dequeueReusableCell(withReuseIdentifier:reuseIdentifier, for: indexPath) as! CollectionViewCell in didSelectItemAt with let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell and adding the UICollectionViewDelegate with class.
doc_23528072
What do I need to do to fix it? var body: some View { ZStack() { Color.black .ignoresSafeArea(.all) VStack(alignment: .leading, spacing: 0) { List(eventFields) { eventField in HStack() { Spacer(minLength: 10) if let iconName = eventField.iconName { Button(action: { print("edit \(eventField.name)") }, label: { Image(uiImage: UIImage(named: iconName)!.colorizeMask(eventField.iconColor!)) .frame(width: 27, height: 27) self.background(.black) }).background(.black) } else { Text("") .frame(width: 27) } Text(eventField.iconName == nil ? "" : eventField.name) .font(.system(size: eventField.labelFontSize)) .foregroundColor(eventField.labelFontColor) .frame(width: 50, alignment: .trailing) Spacer(minLength: 3) Text(eventField.stringValue) .font(.system(size: eventField.fontSize)) .foregroundColor(eventField.fontColor) .frame(width: 200, alignment: .leading) Spacer(minLength: 10) }.background(.black) }.background(.black) } } } } A: I believe the color specification for your hstack and frames is supposed to be "(Color.black)" instead of just "(.black)". Which type of color you use isn't consistent across all Swift objects. Some objects, such as UITableView use "UI colors" which are in the form ".black", while others, like frames, vstacks, hstacks and other objects, use SwiftUI colors in the form "Color.black". I recommend this very informative page for a very accessible explanation of using color in a view and a stack. A: instead of putting .background on the HStack, use .listRowBackground(Color.black) and for separator use .listRowSeparator(.hidden) Keep in mind, this is on the HStack not the List Full Code: var body: some View { ZStack() { Color.black .ignoresSafeArea(.all) VStack(alignment: .leading, spacing: 0) { List(eventFields) { eventField in HStack() { Spacer(minLength: 10) if let iconName = eventField.iconName { Button(action: { print("edit \(eventField.name)") }, label: { Image(uiImage: UIImage(named: iconName)!.colorizeMask(eventField.iconColor!)) .frame(width: 27, height: 27) self.background(.black) }).background(.black) } else { Text("") .frame(width: 27) } Text(eventField.iconName == nil ? "" : eventField.name) .font(.system(size: eventField.labelFontSize)) .foregroundColor(eventField.labelFontColor) .frame(width: 50, alignment: .trailing) Spacer(minLength: 3) Text(eventField.stringValue) .font(.system(size: eventField.fontSize)) .foregroundColor(eventField.fontColor) .frame(width: 200, alignment: .leading) Spacer(minLength: 10) } .listRowBackground(Color.black) .listRowSeparator(.hidden) } } } } }
doc_23528073
of each item in the array. If any item occurs more than or equal to 3 times, then I have to show an alert. Below is the code I have tried: var countries = ['India', 'Australia', 'Bangladesh', 'India', 'India', 'New Zealand', 'New Zealand', 'Pakistan', 'Pakistan', 'West Indies']; var recipientsArray = countries.sort(); var reportRecipientsDuplicate = []; for (var i = 0; i < recipientsArray.length; ++i) { if (!reportRecipientsDuplicate[recipientsArray[i]]) { reportRecipientsDuplicate[recipientsArray[i]] = 0; } ++reportRecipientsDuplicate[recipientsArray[i]]; } How to check if any item has occurred more than or equal to 3 times? Thanks A: You can use reduce method for a easy way to solve this problem. reduce method creates a new array or object by applying a provided callback function. The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. var countries = ['India' , 'Australia' , 'Bangladesh' , 'India' , 'India' , 'New Zealand' , 'New Zealand' , 'Pakistan' , 'Pakistan' , 'West Indies']; var statistics=countries.reduce(function(obj,elem){ obj[elem]=obj[elem] || 0; obj[elem]++; return obj; },{}); for(country in statistics){ if(statistics[country]>=3) console.log(country); } A: const array = ['India' , 'Australia' , 'Bangladesh' , 'India' , 'India' , 'New Zealand' , 'New Zealand' , 'Pakistan' , 'Pakistan' , 'West Indies']; _.each(_.uniq(_.filter(array, function(v) { return _.filter(array, function(v1) { return v1 === v; }).length > 2; })), function(i) { console.log(i); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script> Using UnderscoreJS: _.uniq(_.filter(array, v => _.filter(array, v1 => v1 === v).length > 2)); Code _.each(_.uniq(_.filter(array, function(v) { return _.filter(array, function(v1) { return v1 === v; }).length > 2; })), function(i) { console.log(i); }); Demo https://jsfiddle.net/sumitridhal/e9yf3txg/3/ A: Try this code: var countries = ["India" , "Australia" , "Bangladesh" , "India" , "India" , "New Zealand" , "New Zealand" , "Pakistan" , "Pakistan" , "West Indies","New Zealand"]; var recipientsArray = countries.sort(); checkedWords = []; for (var i = 0; i < recipientsArray.length; ++i) { var count = 0; for(var j=i;j<recipientsArray.length;j++){ if(checkedWords.indexOf(recipientsArray[i]) > -1){ continue; } if(recipientsArray[i] == recipientsArray[j]){ count = count+1; } } console.log(count); if(count >= 3){ alert(recipientsArray[i]); } checkedWords.push(recipientsArray[i]); } https://jsfiddle.net/74bzzze3/ I hope this answers your question :)
doc_23528074
I've tried to scale it using glScalef, but the image is still deformed. (almost always on Z) and here is how i set my window: gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); float w = gLDrawable.getWidth(); float h = gLDrawable.getHeight(); if(w > h) gl.glOrtho(-1.0*(w/h), 1.0*w/h, -1.0, 1.0, -1.0, 1.0); else gl.glOrtho(-1.0, 1.0, -1.0*(h/w), 1.0*h/w, -1.0, 1.0); Here is my Scale attempt if(m.getXVertexMax() - m.getXVertexMin() > w) gl.glScalef(w/(m.getXVertexMax() - m.getXVertexMin()), 1, 1); else gl.glScalef(1/(m.getXVertexMax() - m.getXVertexMin()), 1, 1); if(m.getYVertexMax() - m.getYVertexMin() > h) gl.glScalef(1, h/(m.getYVertexMax() - m.getYVertexMin()), 1); else gl.glScalef(1, 1/(m.getYVertexMax() - m.getYVertexMin()), 1); gl.glScalef(1, 1, (1/(m.getZVertexMax() - m.getZVertexMin()))); No mater what i try, the image is always either short on the x or very large on the z! Can someone please give a hand here? Thanks :-) A: You need to scale uniformly, if you scale the X axis, scale the Y and Z by the same amount.
doc_23528075
<ListView android:id="@+id/products_list" android:layout_width="match_parent" android:descendantFocusability="afterDescendants" android:layout_height="0dp" android:layout_weight="1" /> Every row has some image, text and an EditText. I achived the functionality of gaining/loosing focus in EditTexts, but I have problem, when I enter the view, and click some EditText. Always the first click on any EditText changes the focus from the one clicked, to the first in the list. My holder for that view has implemented methods: @Override public void bindValues(CatalogsProducts item) { note.addTextChangedListener(this); note.setOnFocusChangeListener(this); } @Override public void onFocusChange(View v, boolean hasFocus) { if(v instanceof EditText && !hasFocus) { if(item != null && !TextUtils.isEmpty(note.getText().toString())) { item.setCertainNote(note.getText().toString()); } } } @Override public void afterTextChanged(Editable s) { item.setCertainNote(s.toString()); } Any ideas how to not loose focus from the first clicked EditText? A: In layout XML : <ListView android:id="@+id/products_list" android:layout_height="0dp" android:layout_weight="1" android:layout_width="fill_parent" android:descendantFocusability="beforeDescendants" /> In Mainfest.xml: <activity android:name= ".yourActivity" android:windowSoftInputMode="adjustPan"/> Hope this help you !!
doc_23528076
git clone --mirror Git repo URL git remote add NEW-REMOTE Git Lab repo URL git push NEW-REMOTE --mirror finally it through an error remote: fatal: Error in object error: pack-objects died of signal 13 any help would be appreciated. A: I believe gitlab has it's own git import tool built into the interface. When creating a new project you can import an existing git repo with it. Any history and branches will be included. screenshot:
doc_23528077
My directory structure: todo/ todo.py static/ style.css My todo.py: import sqlite3 from bottle import Bottle, route, run, debug, template, request, validate, static_file, error, SimpleTemplate # only needed when you run Bottle on mod_wsgi from bottle import default_app app = Bottle() default_app.push(app) appPath = '/Applications/MAMP/htdocs/todo/' @app.route('/todo') def todo_list(): conn = sqlite3.connect(appPath + 'todo.db') c = conn.cursor() c.execute("SELECT id, task FROM todo WHERE status LIKE '1';") result = c.fetchall() c.close() output = template(appPath + 'make_table', rows=result, get_url=app.get_url) return output @route('/static/:filename#.*#', name='css') def server_static(filename): return static_file(filename, root='./static') My html: %#template to generate a HTML table from a list of tuples (or list of lists, or tuple of tuples or ...) <head> <link href="{{ get_url('css', filename='style.css') }}" type="text/css" rel="stylesheet" /> </head> <p>The open items are as follows:</p> <table border="1"> %for row in rows: <tr style="margin:15px;"> %i = 0 %for col in row: %if i == 0: <td>{{col}}</td> %else: <td>{{col}}</td> %end %i = i + 1 %end <td><a href="/todo/edit/{{row[0]}}">Edit</a></td> </tr> %end </table> A: I don't quite understand your deployment. The /Applications/MAMP/htdocs/ path, along with the lack of app.run in your code, suggest that you're running this under Apache. Is it a production deployment? For dev tasks you are supposed to use Bottle's built-in dev server, you know. Add a single app.run() towards the end of your todo.py, and you're done. Now if you are using Apache, the most probably root cause is this line: static_file(filename, root='./static'). With mod_wsgi, you are not guaranteed that the working directory is equal to the directory where your todo.py is placed. In fact, it will almost never be. You are using absolute paths for the database and the template, do so for the static files: @route('/static/:filename#.*#', name='css') def server_static(filename): return static_file(filename, root=os.path.join(appPath, 'static')) Next, I don't understand where your app is mounted. The URL http://localhost:8888/todo/static/style.css suggests that the mount point is /todo, but the route for the todo_list handler is again /todo. Is the full path supposed to be http://localhost/todo/todo? Does your app have a / handler? I'd also suggest to avoid hard-coding paths and concat'ing the path fragments together. This would be cleaner: from os.path import join, dirname ... appPath = dirname(__file__) @app.route('/todo') def todo_list(): conn = sqlite3.connect(join(appPath, 'todo.db')) ... A: It turns out that it had nothing to do with Bottle and everything to do with my wsgi file that loaded the application. I did not change my os.path to the correct path; it was pointing to the folder where the wsgi script was located. Obviously, there was no css file there. Once I corrected my directory in the sgi script, everything worked. In other words: os.chdir(os.path.dirname(__file__)) needed to be os.chdir('Applications/MAMP/htdocs/todo') because my wsgi script was in a different directory than the application itself (mod_wsgi recommends this approach). Thanks for all the help everyone!
doc_23528078
type Signature struct{ Name string Signed bool } path := "Document.Signatures.1.Name" map := map[string]interface{}{ "Document": map[string]interface{}{ "Signatures": []interface{}{ Signature{ Name: "Hugo", Signed: false }, Signature{ Name: "Walter", Signed: false }, }, "Otherstuff": "asadwa", }, "AlsoOtherStuff": "adwaw", } // map.giveMe(path) // even better (if possible:) map.change(path,"ToThisNewValue") I have searched for solutions, but I can't find any on the internet. Maybe one of you knows how to do this or knows a library to use for me. Thank you so much in advance! A: Quite a lot of reflect calls will be needed if there is no predefined struct. That being said, you can do it by iterating through the map with type checking on every iteration and handling cases accordingly. // Splitting the path into keys keys := strings.Split(path, ".") var value interface{} = map1 for _, key := range keys { if value, err = Get(key, value); err != nil { break } } if err == nil { fmt.Println("Value:", value) } else { fmt.Println("Error:", err) } func Get(key string, s interface{}) (v interface{}, err error) { var ( i int64 ok bool ) switch s.(type) { case map[string]interface{}: if v, ok = s.(map[string]interface{})[key]; !ok { err = fmt.Errorf("Key not present. [Key:%s]", key) } case []interface{}: if i, err = strconv.ParseInt(key, 10, 64); err == nil { array := s.([]interface{}) if int(i) < len(array) { v = array[i] } else { err = fmt.Errorf("Index out of bounds. [Index:%d] [Array:%v]", i, array) } } case Signature: r := reflect.ValueOf(s) v = reflect.Indirect(r).FieldByName(key) } //fmt.Println("Value:", v, " Key:", key, "Error:", err) return v, err } Playground code
doc_23528079
My config file is as follows: [miscellany] enable-auto-props = yes [auto-props] *.php = svn:keywords=Id *.js = svn:keywords=Id And I have ran: find . \( -name "*.php" -o -name "*.js" \) -exec svn propset svn:keywords Id {} \; Still, it is not updating the $Id$ tags. Do I have to reset these somehow? A: Is there a svn:keywords property on the file itself inside your source repository? The autoproperties [auto-props] is only for new files and not files already in your Subversion repository. The idea of autoproperties is to automatically attach a property to a new file when you do an svn add. To add the svn:keywords property, do the following: $ svn propset svn:keywords "Id" $FILE_NAME $ svn commit -m"Added Id Keyword to file"
doc_23528080
HTML: <html> <head> <title></title> </head> <body> <p><img height="600" id="map_img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Hsi-h000.png/600px-Hsi-h000.png" style="display: none;" width="600" /> <input id="Mapred" onclick="showImg()" type="submit" value="Mapred" /></p> <p><img height="800" id="map_img2" src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Sandro_Botticelli_-_La_nascita_di_Venere_-_Google_Art_Project_-_edited.jpg/800px-Sandro_Botticelli_-_La_nascita_di_Venere_-_Google_Art_Project_-_edited.jpg" style="display: none;" width="502" /> <input id="Map" onclick="showImg2()" type="submit" value="Map" /></p> </body> </html> A: Is this what you need? Because I don't fully understand your question. function showImg() { document.getElementById("map_img").style.display = ""; } function showImg2() { document.getElementById("map_img2").style.display = ""; } <p><img height="600" id="map_img"src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Hsi-h000.png/600px-Hsi-h000.png" style="display: none;" width="600" /> <input id="Map" onclick="showImg()" type="submit" value="Map" /></p> <p><img height="600" id="map_img2"src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Hsi-h000.png/600px-Hsi-h000.png" style="display: none;" width="600" /> <input id="Map" onclick="showImg2()" type="submit" value="Map" /></p> A: JavaScript function showImg() { document.getElementById("map_img").style.display = "block"; } function hideImg() { document.getElementById("map_img").style.display = "none"; } JQuery I've seen the tag of JQuery for the post, I would recommend Javascript since it's faster and doesnot require to load JQuery, but still. $("#map_img").toggle(); $("#map_img").hide(); $("#map_img").show(); For map_img: $(document).ready(function(){ $("#button-link").click(function(event){ //Your actions here }); }); A: you can simply use style.display == 'block' to block any image or use style.display == 'none' i am showing you a full example so you can understand.. <html> <body> <h1>What Can JavaScript Do?</h1> <div id="myDiv"> <img id="myImage" src="pic_bulboff.gif" style="width:100px"> </div> <button onclick="LightOn()">Turn On</button> <button onclick="LightOff()">Turn Off</button> <button id="button" onclick="toggle_visibility('myDiv')">Toggle</button> <script type="text/javascript"> function LightOn(){ document.getElementById('myImage').src='pic_bulbon.gif' } function LightOff(){ document.getElementById('myImage').src='pic_bulboff.gif' } function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; } </script> </body> </html>
doc_23528081
type Runnable interface { Run() } type T struct { Z struct { A int } } func (t T) Run() { t.Z.A = 1 } func main() { t := reflect.TypeOf( T{} ) var v reflect.Value v = reflect.New(t).Elem() runnable := v.Interface().(Runnable) runnable.Run() Is there a way, at the end, to retrive Z and its field values as set by the Run() method? I am implementing an API command pattern, so T could be RegisterCommand, LoginCommand, LogoutCommand etc. Z is the 'output doc' - a JSON doc returned by the API command - which I want to specify declaratively and have written to the network after the command is run. A: Got it! Thank you to synful for the 'pointer' :-) z := v.Elem().FieldByName("Z").Interface()
doc_23528082
But, the iterating process only seems to work from within a loop. If it isn't in a loop, then it seems to start over immediately before all values have been read. From the Perl docs: In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted. http://perldoc.perl.org/functions/glob.html However, in scalar context the operator returns the next value each time it's called, or undef when the list has run out. http://perldoc.perl.org/perlop.html#I/O-Operators Example code: use warnings; use strict; my $filename; # in scalar context, <*> should return the next file name # each time it is called or undef when the list has run out $filename = <*>; print "$filename\n"; $filename = <*>; # doesn't work as documented, starts over and print "$filename\n"; # always returns the same file name $filename = <*>; print "$filename\n"; print "\n"; print "$filename\n" while $filename = <*>; # works in a loop, returns next file # each time it is called In a directory with 3 files...file1.txt, file2.txt, and file3.txt, the above code will output: file1.txt file1.txt file1.txt file1.txt file2.txt file3.txt Note: The actual perl script should be outside the test directory, or you will see the file name of the script in the output as well. Am I doing something wrong here, or is this how it is supposed to work? A: Here's a way to capture the magic of the <> glob operator's state into an object that you can manipulate in a normal sort of way: anonymous subs (and/or closures)! sub all_files { return sub { scalar <*> }; } my $iter = all_files(); print $iter->(), "\n"; print $iter->(), "\n"; print $iter->(), "\n"; or perhaps: sub dir_iterator { my $dir = shift; return sub { scalar glob("$dir/*") }; } my $iter = dir_iterator("/etc"); print $iter->(), "\n"; print $iter->(), "\n"; print $iter->(), "\n"; Then again my inclination is to file this under "curiosity". Ignore this particular oddity of glob() / <> and use opendir/readdir, IO::All/readdir, or File::Glob instead :) A: The following code also seems to create 2 separate instances of the iterator... for ( 1..3 ) { $filename = <*>; print "$filename\n" if defined $filename; $filename = <*>; print "$filename\n" if defined $filename; } I guess I see the logic there, but it is kind of counter intuitive and contradictory to the documentation. The docs don't mention anything about having to be in a loop for the iteration to work. A: Also from perlop: A (file)glob evaluates its (embedded) argument only when it is starting a new list. Calling glob creates a list, which is either returned whole (in list context) or retrieved one element at a time (in scalar context). But each call to glob creates a separate list. A: (Scratching away at my rusty memory of Perl...) I think that multiple lexical instances of <*> are treated as independent invokations of glob, whereas in the while loop you are invoking the same "instance" (whatever that means). Imagine, for instance, if you did this: while (<*>) { ... } ... while (<*>) { ... } You certainly wouldn't expect those two invocations to interfere with each other.
doc_23528083
We are using Spring 3.1.4.RELEASE, JBoss 7.1.3.AS and Hibernate 4.1.0.Final. A: HAProxy does not manage read/write splitting with MySQL. It is a very efficient and lightweight load balancing solution, but when used with MySQL, it has no protocol awareness like it does with http (where it can manipulate headers, route based on patterns, etc.) HAProxy will load balance your read connections to a healthy replica, but that's all it will do for you on this setup... you still have to do read/write splitting in the application.
doc_23528084
Here is the content of my sample.batch file cd C:\Program Files\MyApplication "C:\Program Files\MyApplication\Application.exe" -e -p "Application Projects/Testing/General/Notepad" -rm "Close Notepad" Here I need to change my current working directory to the folder where Application.exe lives so that It finds certain required JARs which is located in that folder.Is it best practice to do so?Changing the current work directory before executing a batch file. A: Try pushd C:\Program Files\MyApplication ... popd as another choice. best practice is a matter of both opinion and circumstance A: One method is what Magoo and Stephan have suggested already: pushd "%ProgramFiles%\MyApplication" rem Other commands. popd This solution works even for UNC paths with command extensions enabled as by default as PUSHD temporarily maps the network share to a drive letter and makes this network drive the current directory. Another solution is using SETLOCAL, CD and ENDLOCAL which has the advantage of all modifications of environment variables, command extensions and delayed expansion done by the commands between setlocal and endlocal don't matter for the commands after endlocal command line. setlocal EnableExtensions DisableDelayedExpansion cd /D "%ProgramFiles%\MyApplication" rem Other commands running in their own environment, here running with command rem extensions explicitly enabled and delayed expansion explicitly disabled. endlocal The command ENDLOCAL restores also the current directory as being set on execution of SETLOCAL. See the answer on change directory command cd ..not working in batch file after npm install with more details about PUSHD (push directory), POPD (pop directory), SETLOCAL (setup local environment), CD (change directory) and ENDLOCAL (end local environment). For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully. * *cd /? *endlocal /? *rem /? *setlocal /? *popd /? *pushd /?
doc_23528085
For example, could these data be backed up and stored on-prem? I imagine a Lambda function could be created to access say S3 data and fetch it through the Gateway API, but are CloudWatch data stored in S3? A: Log data on CloudWatch is stored in S3 which we can not access. However, you can export log to S3. Doc says.. You can export log data from your log groups to an Amazon S3 bucket and use this data in custom processing and analysis, or to load onto other systems. ... To begin the export process, you must create an S3 bucket to store the exported log data. You can store the exported files in your Amazon S3 bucket and define Amazon S3 lifecycle rules to archive or delete exported files automatically. Then you can simply download from S3 or use services as you like. A: The raw metrics stored in CloudWatch Metrics are not accessible. For example, when each Amazon EC2 instance sends CPUUtilization to CloudWatch. Instead, aggregated metrics can be queried, such as "Average CPU Utilization over a 5-minute period". This is different to CloudWatch Logs, which can be exported to Amazon S3.
doc_23528086
Date Line Qty RN 15-03-18 1 10 1 16-03-18 1 10 2 17-03-18 1 10 3 18-03-18 1 10 4 15-03-18 2 10 5 16-03-18 2 10 6 17-03-18 2 10 7 I have a combobox which has options 5,6 and 7 If user selects 5, I wish to make qty for rownum 6 and 7= 0 If user selects 6, I wish to make qty for rownum 7= 0 If user selects 7, I wish to keep qty as it is (for each line) Meaning select qty for dates 5, 6 or 7 days make rest 0 But my row numbers are 1,2, mabbe upto 100. I need to convert them in range of 7(weekly) and then accordingly make the qty 0. Trying something like this: If 5 is selected from combobox: SELECT date,line,(CASE when rn=6 then 0 when rn=7 then 0 else qty end) as qty from above table I am selecting date, line and changing qty according to the rn(rownum) Appreciate any help. A: Use functions mod() and sign(), this construction gave me desired values: select tbl.*, decode(sign(5 - mod(rn - 1, 7)), 1, qty, 0) from tbl demo In place of hardcoded 5 put your parameter.
doc_23528087
Third column first. But! As shown below, the first and third operations seem to be incorrect. The fourth column is not sorted by value! Is it a "sort" bug? moasm@moasm-pc ~ $ cat ~/Desktop/10.log ain.log.237.1999 ain.log.237.298 moasm@moasm-pc ~ $ sort -b -t. -k3n,4n ~/Desktop/10.log ain.log.237.1999 ain.log.237.298 moasm@moasm-pc ~ $ sort -b -t. -k4n ~/Desktop/10.log ain.log.237.298 ain.log.237.1999 moasm@moasm-pc ~ $ sort -b -t. -k3n ~/Desktop/10.log ain.log.237.1999 ain.log.237.298 moasm@moasm-pc ~ $ sort -b -t. -k3V ~/Desktop/10.log ain.log.237.298 ain.log.237.1999 moasm@moasm-pc ~ $ sort -b -t. -k3V,4V ~/Desktop/10.log ain.log.237.298 ain.log.237.1999 moasm@moasm-pc ~ $ sort -b -t. -k3V,3V ~/Desktop/10.log ain.log.237.1999 ain.log.237.298 A: To use secondary sorting column, you need to specify -k several times: sort -t. -k3,3n -k4,4n
doc_23528088
when I try this code I get a type error Thanks for any help to anyone who decides to find what I am doing wrong so I can know in the future, kudos JAVASCRIPT: window.addEventListener('load', () => { const form = document.querySelector("#new-task-form"); const input = document.querySelector("new-task-input"); const list_el = document.querySelector("#tasks"); form.addEventListener('submit', (e) => { e.preventDefault(); const task = input.value; if (!task) { alert("Please fill out the task"); } else { console.log("Success"); } }) }) HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Task List 2023</title> <link rel="stylesheet" href="main.css"> <script src="main.js"></script> </head> <body> <header> <h1>Task List 2023</h1> <form id="new-task-form"> <input type="text" id="new-task-input" placeholder="What do you have planned?" /> <input type="submit" id="new-task-submit" value="Add Task" /> </form> </header> <main> <section class="task-list"> <h2>Tasks</h2> <div id="tasks"> <!-- <div class="task"> <div class="content"> <input type="text" class="text" value="My shiny task" readonly /> </div> <div class="actions"> <button class="edit">Edit</button> <button class="delete">Delete</button> </div> </div> --> </div> </section> </main> </body> </html> CSS: :root { --dark: #374151; --darker: #1F2937; --darkest: #111827; --gray: #6B7280; --light: #EEE; --pink: #EC4899; --purple: #8B5Cf6; } * { box-sizing: border-box; margin: 0; font-family: 'Fire sans', sans-serif } body { display: flex; flex-direction: column; min-height: 100vh; background: var(--dark); color: #FFF; } header { padding: 2rem 1rem; max-width: 800px; width: 100%; margin: 0 auto; } header h1 { font-size: 2.5rem; font-weight: 300; color: var(--gray); margin-bottom: 1rem; } #new-task-form { display: flex; } input, button { appearance: none; border: none; outline: none; background: none; } #new-task-input { flex: 1 1 0%; background-color: var(--darker); padding: 1rem; border-radius: 1rem; margin-right: 1rem; color: var(--light); font-size: 1.25rem; } #new-task-input::placeholder { color: var(--gray); } #new-task-submit { color: var(--pink); font-size: 1.25rem; font-weight: 700; background-image: linear-gradient(to right, var(--pink), var(--purple)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; cursor: pointer; transition: 0.4s; } #new-task-submit::hover { opacity: 0.8; } #new-task-submit::active { opacity: 0.6; } main { flex: 1 1 0%; padding: 2rem 1rem; max-width: 800px; width: 100%; margin: 0 auto; } .task-list { padding: 1rem; } .task-list h2 { font-size: 1.5rem; font-weight: 300; color: var(--gray); margin-bottom: 1rem; } #tasks .task{ display: flex; justify-content: space-between; background-color: var(--darkest); padding: 1rem; border-radius: 1rem; margin-bottom: 1rem; } #tasks .task .content .text { color: var(--light); font-size: 1.125rem; width: 100%; display: block; transition: 0.4s; } #tasks .task .content .text:not(:read-only) { color: var(--pink) } #tasks .task .actions { display: flex; margin: 0 -0.5rem; } .task .actions button { cursor: pointer; margin: 0 0.5rem; font-size: 1.125rem; font-weight: 700; text-transform: uppercase; transition: 0.4s; } .task .actions button:hover { opacity: 0.8; } .task .actions button:active { opacity: 0.6; } .task .actions .edit { background-image: linear-gradient(to right, var(--pink), var(--purple)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .task .actions .delete { color: crimson; } ERROR: main.js:5 Uncaught TypeError: Cannot read properties of null (reading 'value') at main.js:5:24 (anonymous) @ main.js:5 load (async) (anonymous) @ main.js:1 A: The reason why you are getting this error TypeError: Cannot read properties of null (reading 'value') is because you are trying to read a property specifically value from an object that is currently null. From what you provided in the javascript code, there is only 1 place that you are trying to access property value from an object. It is const task = input.value; If this is the case, it means that your input object is currently null according to the above reason. To find the root cause of why the input is null, I tracked back to where it is declared and initialized, which is this line const input = document.querySelector("new-task-input"); This is where the input is declared and initialized to some value. It is presumably expected to be this input just from looking at your HTML code. <input type="text" id="new-task-input" placeholder="What do you have planned?" /> To use document.querySelector to select an element by its id property, you need to specify by prepending the id with a # just like what you already did for the other variables here. const form = document.querySelector("#new-task-form"); const input = document.querySelector("new-task-input"); const list_el = document.querySelector("#tasks"); As you can see, form and list_el do have # in front of the id, whereas input does not. Therefore, it will not find the element, which results to a null. To fix this, you just need to put # in front the value there. So that it will find the element. To fix it in your code, change the code from const input = document.querySelector("new-task-input"); to const input = document.querySelector("#new-task-input");
doc_23528089
#include <iostream> class ClassA { public: bool foo(); void foo2(); }; bool ClassA::foo() { int var1 = 100; var1++; } void ClassA::foo2() { foo(); } int main() { ClassA a; a.foo2(); printf("end of code"); return 0; } Note that the return type of foo() is bool but implementation doesn't return anything. The crash is 100% reproducible on Android NDK-version r19. Also same code works fine on NDK-r15c. A: I got a crash when a non void function like this didn't return anything: Because this is Undefined Behavior. §8.6.3 of the draft C++20 standard: flowing off the end of a [non-void] function other than main results in undefined behavior. Note that this is unrelated to how the function is actually called. So even when the return value is ignored (as in the case of the OP), it's the "flowing off the end" that results in UB. A: You are invoking Undefined Behavior: If a function is declared to return a value, and fails to do so, the result is undefined behavior (in C++). One possible result is seeming to work, which is pretty much what you're seeing here. A: Your program was always broken. The function must have a return, and your compiler should have warned you about this. In C++, whether you use the resulting value at the callsite is irrelevant (though this isn't the case in C). It is just that you got unlucky with previous toolchains that just so happened to produce code that just so happened not to cause a crash as its symptom. That's unlucky because it would have prompted you to correct the bug at the time.
doc_23528090
def __init__(self): self.g = [] self.t = [] self.d = [] self.fft = [] self.freq = [] A: Some options: def __init__(self): for att in ('g','t','d','fft','freq'): setattr(self,att,[]) or def __init__(self): attrs = ('g','t','d','fft','freq') self.__dict__.update(zip(attrs,([] for _ in range(len(attrs))))) But honestly? The explicit method is fine. I suppose this method gets better when you have some unwieldy number of attributes (10+ maybe) but in that case I'd reexamine whether you can package some of them together into their own collection. A: Well, you can also do: def __init__(self): self.g, self.t, self.d, self.fft, self.freq = [], [], [], [], [] That's shorter but I'm not sure it's really better... A: You can do this: def __init__(self): attr_names = ['g', 't', 'd', 'fft', 'freq'] for attr_name in attr_names: setattr(self, attr_name, []) But if you set object attributes in this way the code will be too dynamic and if IDE or other static analyzer used then it can't give good results. A: Use this module $ python -m this|grep Readability Readability counts Your code snippet seems to me the neatest way to do what you need.
doc_23528091
$table = explode(' ', $my_string); $key = array_search($int_to_delete, $table); array_splice($table, $key, 1); $my_string = implode(' ', $table); Is there a function to do that? :) Something like "delete $needle if it's at the beginning, the end or surrounded by $delimiter (in my example ' ')" ? Thx all :D A: Have a try using regular expression based string substitution: <?php $subject = '8 9 10 11 12 13 14 15 16 17'; $pattern = sprintf('/\s?(%s)\s?+/Uu', 12); $output = preg_replace($pattern, ' ', $subject); var_dump($output); The output obviously is: string(38) "8 9 10 11 13 14 15 16 17"
doc_23528092
I'm also including a snippet from this tutorial, so maybe you get me better: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Annual Sales Data (With Fancy JavaScript!) </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server"> <script type="text/javascript"> $(document).ready(function () { // Populate the Categories and Years DDLs with the values from the server $.getJSON('/Api/Years', // URL that returns data of interest function (result) { // The function that executes once the data has been returned var years = $("#years"); $.each(result, function (index, year) { years.append($("<option />").val(year).text(year)); }); $.getJSON('<%=Page.ResolveClientUrl("~/Api/Categories")%>', // URL that returns data of interest function (result) { // The function that executes once the data has been returned var categories = $("#categories"); $.each(result, function (index, categoryName) { categories.append($("<option />").val(categoryName).text(categoryName)); }); // Load the image UpdateImage(); }); }); // Add client-side event handlers to these DDLs $("#years").change(UpdateImage); $("#categories").change(UpdateImage); }); function UpdateImage() { var selectedYear = $("#years").val(); var selectedCategory = $("#categories").val(); $("#chart").fadeOut(function () { $(this).attr('src', '/Charts/SalesByYear?CategoryName=' + escape(selectedCategory) + '&OrderYear=' + escape(selectedYear) + '&showTitle=false') .attr('alt', 'Sales for ' + selectedCategory + ' in ' + selectedYear) .attr('title', 'Sales for ' + selectedCategory + ' in ' + selectedYear); $(this).fadeIn(); }); } </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Annaul Sales Data (With Fancy JavaScript)</h2> <p> This demo shows how to gussy up the sales data charting example using a tad of JavaScript and jQuery. </p> <div style="text-align: center"> <h2 style="text-align: center">Sales For <select id="categories"></select> In <select id="years"></select></h2> <img id="chart" style="display:none" /> </div> </asp:Content> Could anyone recommend me any tutorial in which I'd be able to ee how can I implement a mvc-based web app with using flotcharts? Thank you! A: I would look at something like flot http://www.flotcharts.org/ Rather than generate an image on the server side. A: You might want to check jqPlot. Its a very good graph plugin using jQuery.
doc_23528093
[Serializable] [StructLayout(LayoutKind.Sequential)] public struct Byte4 { public byte R, G, B, A; public Byte4(byte[] input) { R = input[0]; G = input[1]; B = input[2]; A = input[3]; } public uint ToUInt32() { byte[] temp = new byte[] { this.R, this.G, this.B, this.A }; return BitConverter.ToUInt32(temp, 0); } } [Serializable] [StructLayout(LayoutKind.Sequential)] public struct VertexInterleaved { // data section is exactly 36 bytes long??? - need padding to get multiple of 32? public Vector3 vertex; // Vertex public Vector3 normal; // Normal Vector public Vector2 textureCoord; // First Texture Coordinates public Byte4 rgbaColor; // RGBA value of this vertex //public byte[] padding; public static int VertexStride() { // if I'm using the padding I have to add the appropriate size to this... return (8 * sizeof(float) + 4 * sizeof(byte)); } } public class VertexBufferObject { private uint[] _VBOid; private int _vertexStride; private int _totalIndices; private int _totalVertices; public VertexBufferObject () { _VBOid = new uint[2]; GL.GenBuffers(2, _VBOid); } public bool DeleteVBO() { GL.DeleteBuffers(2, _VBOid); } private void BindBuffers() { GL.BindBuffer(BufferTarget.ArrayBuffer, _VBOid[0]); GL.BindBuffer(BufferTarget.ElementArrayBuffer, _VBOid[1]); } private void ReleaseBuffers() { GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); } public void BufferMeshData(Mesh3DCollection mesh3Ds) { _vertexStride = VertexInterleaved.VertexStride(); _totalIndices = mesh3Ds.TotalIndices(); _totalVertices = mesh3Ds.TotalVertices(); VertexInterleaved[] vboVertices = new VertexInterleaved[_totalVertices]; uint[] vboIndices = new uint[_totalIndices]; int vertexCounter = 0; int indexCounter = 0; foreach (Mesh3D m in mesh3Ds) { foreach (VertexInterleaved v in m.vertices) { vboVertices[vertexCounter] = v; vertexCounter++; } foreach (uint i in m.indices) { vboIndices[indexCounter] = i; indexCounter++; } } BindBuffers(); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr) (_totalIndices * sizeof(uint)), vboIndices, BufferUsageHint.StaticDraw); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(_totalVertices * _vertexStride), vboVertices, BufferUsageHint.StaticDraw); ReleaseBuffers(); } public void RenderVBO() { GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.EnableClientState(ArrayCap.ColorArray); BindBuffers(); GL.VertexPointer(3, VertexPointerType.Float, _vertexStride, (IntPtr) (0)); GL.NormalPointer(NormalPointerType.Float, _vertexStride, (IntPtr) (3 * sizeof(float))); GL.TexCoordPointer(2, TexCoordPointerType.Float, _vertexStride, (IntPtr) (6 * sizeof(float))); GL.ColorPointer(4, ColorPointerType.Byte, _vertexStride, (IntPtr) (8 * sizeof(float))); GL.DrawElements(BeginMode.Quads, numIndices, DrawElementsType.UnsignedInt, startLocation); ReleaseBuffers(); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); GL.DisableClientState(ArrayCap.ColorArray); { } Specific Questions: 1.) Should my interleaved vertex data structure be a struct or a class? Does this make a difference as far as the VBO and/or memory footprint is concerned? (I decided to use a struct, even though it felt wrong, because the vertices aren't going to be altered once they're in memory.) 2.) Does this data structure really need to be a multiple of 32 bytes in size? (i.e., do I need a "dummy" padding member to force a correct size? All of the examples I found online were in C++, so I am particularly interested in whether the same ideas/motivations carry over to C#. 3.) Is the [Serializable] [StructLayout(LayoutKind.Sequential)] really necessary? I copied this from an example that I found online, so... A: 1.) If the data within the structure is going to change regularly then it is more advisable to use a class, that is a reference to the memory location. If it is pretty much static, as i imagine this will be, it is better to use structs, that is value type. 2.) I have heard that aligning blocks of interleaved vertex data on 32-byte-aligned boundaries has a performance gain, good cache line coherence but I have yet to see a good example of any performance gain. 3.)yes it is, it specifies that the fields of the type should be laid out in memory in the same order they are declared in your source code. Which is obviously important for interleaved data.
doc_23528094
I tried everything I could think of, I could not solve this issue. Below a minimal code to reproduce the problem. Anyone has any idea, how to get around this problem SelectionList.swift struct SelectionList: View { @State var dudes: [String] = ["Tim", "Craig", "Phil"] @State var selectedRow = Set<String>() var body: some View { return List(selection: $selectedRow) { ForEach(self.dudes, id: \.self) { item in SelectionRow() } } } } SelectionRow.swift struct SelectionRow: View { @State var selectedFruit = 0 let fruits = ["Apples", "Oranges", "Bananas", "Pears"] var body: some View { Picker(selection: self.$selectedFruit, label: EmptyView()) { ForEach(0 ..< fruits.count, id: \.self) { Text(self.fruits[$0]) } } } }
doc_23528095
Reading on SO I tried UNION, which is very fast, but very inconvenient for the script I am using. So two questions: * *Why is UNION so much faster? (Or why is OR so slow)? *Is there any way I can force MSSQL to use a different approach for the OR statement that is fast? A: There is currently no way in SQL Server to force a UNION execution plan if no UNION statement was used. If the only difference between the two parts is the WHERE clause, create a view with the complex query. The UNION query then becomes very simple: SELECT * FROM dbo.MyView WHERE <cond1> UNION ALL SELECT * FROM dbo.MyView WHERE <cond2> It is important to use UNION ALL in this context when ever possible. If you just use UNION SQL Server has to filter out duplicate rows, which requires an expensive sort operation in most cases. A: The reason is that using OR in a query will often cause the Query Optimizer to abandon use of index seeks and revert to scans. If you look at the execution plans for your two queries, you'll most likely see scans where you are using the OR and seeks where you are using the UNION. Without seeing your query it's not really possible to give you any ideas on how you might be able to restructure the OR condition. But you may find that inserting the rows into a temporary table and joining on to it may yield a positive result. Also, it is generally best to use UNION ALL rather than UNION if you want all results, as you remove the cost of row-matching.
doc_23528096
c:\Code\whatever> git mergetool merge tool candidates: tortoisemerge emerge vimdiff No known merge resolution program available. This used to work, so why is it broken now? A: According to this post, in version 1.8 TortoiseGit renamed tortoisemerge.exe to tortoisegitmerge.exe because the old version could not handle spaces in file names so well. According to this blog post, you'll need to enter the following commands: git config --global merge.tool tortoisemerge git config --global mergetool.tortoisemerge.cmd '"C:/Program Files/TortoiseGit/bin/TortoiseGitMerge.exe" -base:"$BASE" -theirs:"$REMOTE" -mine:"$LOCAL" -merged:"$MERGED"' However, that didn't work for me so I added the following to my .gitconfig (which just changes the path to TortoiseGitMerge.exe: [merge] tool = tortoisemerge [mergetool "tortoisemerge"] path = C:\\Program Files\\TortoiseGit\\bin\\tortoisegitmerge.exe
doc_23528097
#Navigation li ul { position: static; display: none; } My test page: http://ulrichbangert.de/indexr3.php (Resize the viewport to a small width until the menu has one column.) I've used this tutorial: http://www.menucool.com/ddmenu/create-mobile-friendly-responsive-menu.aspx where it works just as I want it to. However I cannot use this one-by-one as I wanted to keep the layout of my existing menu. Best regards - Ulrich A: In the meantime I was able to solve this problem on my own: Apparently some CSS attributes cannot be changed when they are in a nested list and not on top level. In this case the attribute position. Afterwards I had the same problem with the attribute width which I could not change to 100% and the attribute padding-left which I could not change either. And some years ago when I implemented the initial version of this menu with the attribute height, which I could not change to auto on hover after setting it to 0 initially. Only setting to a fixed height worked. How can this be? Is it intended or is it a bug in the browsers implementation? (I tested with firefox). Anyway my menu works fine now, just as I figured it.
doc_23528098
If a function called decimalToFraction had been written for this purpose, then decimalToFraction(0.0002) would return the string "2/10000". A: A little googling with the term "decimal to fraction js" the first yielded this: http://wildreason.com/wildreason-blog/2010/javascript-convert-a-decimal-into-a-simplified-fraction/ It seems to work: http://jsfiddle.net/VKfHH/ function HCF(u, v) { var U = u, V = v while (true) { if (!(U%=V)) return V if (!(V%=U)) return U } } //convert a decimal into a fraction function fraction(decimal){ if(!decimal){ decimal=this; } whole = String(decimal).split('.')[0]; decimal = parseFloat("."+String(decimal).split('.')[1]); num = "1"; for(z=0; z<String(decimal).length-2; z++){ num += "0"; } decimal = decimal*num; num = parseInt(num); for(z=2; z<decimal+1; z++){ if(decimal%z==0 && num%z==0){ decimal = decimal/z; num = num/z; z=2; } } //if format of fraction is xx/xxx if (decimal.toString().length == 2 && num.toString().length == 3) { //reduce by removing trailing 0's decimal = Math.round(Math.round(decimal)/10); num = Math.round(Math.round(num)/10); } //if format of fraction is xx/xx else if (decimal.toString().length == 2 && num.toString().length == 2) { decimal = Math.round(decimal/10); num = Math.round(num/10); } //get highest common factor to simplify var t = HCF(decimal, num); //return the fraction after simplifying it return ((whole==0)?"" : whole+" ")+decimal/t+"/"+num/t; } // Test it alert(fraction(0.0002)); // "1/5000" A: I used this site Link to build a function but as the article mentions you will get an unreasonable large number for radicals or pi. Hope it helps though. function Fraction(){} Fraction.prototype.convert = function(x, improper) { improper = improper || false; var abs = Math.abs(x); this.sign = x/abs; x = abs; var stack = 0; this.whole = !improper ? Math.floor(x) : 0; var fractional = !improper ? x-this.whole : abs; /*recursive function that transforms the fraction*/ function recurs(x){ stack++; var intgr = Math.floor(x); //get the integer part of the number var dec = (x - intgr); //get the decimal part of the number if(dec < 0.0019 || stack > 20) return [intgr,1]; //return the last integer you divided by var num = recurs(1/dec); //call the function again with the inverted decimal part return[intgr*num[0]+num[1],num[0]] } var t = recurs(fractional); this.numerator = t[0]; this.denominator = t[1]; } Fraction.prototype.toString = function() { var l = this.sign.toString().length; var sign = l === 2 ? '-' : ''; var whole = this.whole !== 0 ? this.sign*this.whole+' ': sign; return whole+this.numerator+'/'+this.denominator; } //var frac = new Fraction() //frac.convert(2.56, false) //console.log(frac.toString()) //use frac.convert(2.56,true) to get it as an improper fraction If you just want a self-contained function that only returns the numerator and denominator then use the function below. var toFraction = function (dec) { var is_neg = dec < 0; dec = Math.abs(dec); var done = false; //you can adjust the epsilon to a larger number if you don't need very high precision var n1 = 0, d1 = 1, n2 = 1, d2 = 0, n = 0, q = dec, epsilon = 1e-13; while (!done) { n++; if (n > 10000) { done = true; } var a = parseInt(q); var num = n1 + a * n2; var den = d1 + a * d2; var e = (q - a); if (e < epsilon) { done = true; } q = 1 / e; n1 = n2; d1 = d2; n2 = num; d2 = den; if (Math.abs(num / den - dec) < epsilon || n > 30) { done = true; } } return [is_neg ? -num : num, den]; }; //Usage: //var frac = toFraction(0.5); //console.log(frac) //Output: [ 1, 2 ] A: Very old question but maybe someone can find this useful. It's iterative, not recursive and doesn't require factorization function getClosestFraction(value, tol) { var original_value = value; var iteration = 0; var denominator=1, last_d = 0, numerator; while (iteration < 20) { value = 1 / (value - Math.floor(value)) var _d = denominator; denominator = Math.floor(denominator * value + last_d); last_d = _d; numerator = Math.ceil(original_value * denominator) if (Math.abs(numerator/denominator - original_value) < tol) break; iteration++; } return {numerator: numerator, denominator: denominator}; }; A: There is a very simple solution using string representation of numbers string = function(f){ // returns string representation of an object or number return f+""; } fPart = function(f){ // returns the fraction part (the part after the '.') of a number str = string(f); return str.indexOf(".")<0?"0":str.substring(str.indexOf(".") + 1); } wPart = function(f){ // returns the integer part (the part before the '.') of a number str = string(f); return str.indexOf(".")<0?str:str.substring(0, str.indexOf(".")); // possibility 1 //return string(f - parseInt(fPart(f))); // just substract the fPart } power = function(base, exp){ var tmp = base; while(exp>1){ base*=tmp; --exp; } return base; } getFraction = function(f){ // the function var denominator = power(10, fPart(f).length), numerator = parseInt(fPart(f)) + parseInt(wPart(f))*denominator; return "[ " + numerator + ", " + denominator + "]"; } console.log(getFraction(987.23)); which will just check how many numbers are in the fraction and then expands the fraction of f/1 until f is an integer. This can lead to huge fractions, so you can reduce it by dividing both numerator and denominator by the greatest common divisor of both, e.g. // greatest common divisor brute force gcd = function(x,y){ for(var i = Math.min(x, y);i>0;i--) if(!(x%i||y%i)) return i; return 1; } A: You can use Erik Garrison's fraction.js library to do that and more fractional operations. var f = new Fraction(2, 10000); console.log(f.numerator + '/' + f.denominator); To to do .003 you can just do var f = new Fraction(.003); console.log(f.numerator + '/' + f.denominator); A: The good news is that it's possible, but you'll have to convert it to code. Let's go with 2.56 for no reason at all. Use the decimal portion of the number .56 There are 2 digits in .56, write .56 as 56/100. So we have 2 + 56/100 and need to reduce this fraction to lowest terms by dividing both the numerator and denominator by the greatest common divisor, which is 4 in this case. So, this fraction reduced to lowest terms is 2 + 14/25. To add those whole 2, we multiply by the divisor and add to the 14 (2*25 + 14)/25 = 64/25 A: Have tried something like this? var cnum = 3.5, deno = 10000, neww; neww = cnum * deno; while (!(neww % 2 > 0) && !(deno % 2 > 0)) { neww = neww / 2; deno = deno / 2; } while (!(neww % 3 > 0) && !(deno % 3 > 0)) { neww = neww / 3; deno = deno / 3; } while (!(neww % 5 > 0) && !(deno % 5 > 0)) { neww = neww / 5; deno = deno / 5; } while (!(neww % 7 > 0) && !(deno % 7 > 0)) { neww = neww / 7; deno = deno / 7; } while (!(neww % 11 > 0) && !(deno % 11 > 0)) { neww = neww / 11; deno = deno / 11; } while (!(neww % 13 > 0) && !(deno % 13 > 0)) { neww = neww / 13; deno = deno / 13; } while (!(neww % 17 > 0) && !(deno % 17 > 0)) { neww = neww / 17; deno = deno / 17; } while (!(neww % 19 > 0) && !(deno % 19 > 0)) { neww = neww / 19; deno = deno / 19; } console.log(neww + "/" + deno); A: I did what popnoodles suggested and here it is function FractionFormatter(value) { if (value == undefined || value == null || isNaN(value)) return ""; function _FractionFormatterHighestCommonFactor(u, v) { var U = u, V = v while (true) { if (!(U %= V)) return V if (!(V %= U)) return U } } var parts = value.toString().split('.'); if (parts.length == 1) return parts; else if (parts.length == 2) { var wholeNum = parts[0]; var decimal = parts[1]; var denom = Math.pow(10, decimal.length); var factor = _FractionFormatterHighestCommonFactor(decimal, denom) return (wholeNum == '0' ? '' : (wholeNum + " ")) + (decimal / factor) + '/' + (denom / factor); } else { return ""; } } A: I just want a leave one alternative that I found to convert decimal numbers into fractions and reducing fractions, it's a JS library. The library calls fraction.js, it was really helpful for me and save me a lot time and work. Hope can be useful to somebody else! A: This may be a little old but the code that was posted fails on 0 values I have fixed that error and will post the updated code below //function to get highest common factor of two numbers (a fraction) function HCF(u, v) { var U = u, V = v while (true) { if (!(U%=V)) return V if (!(V%=U)) return U } } //convert a decimal into a fraction function fraction(decimal){ if(!decimal){ decimal=this; } whole = String(decimal).split('.')[0]; decimal = parseFloat("."+String(decimal).split('.')[1]); num = "1"; for(z=0; z<String(decimal).length-2; z++){ num += "0"; } decimal = decimal*num; num = parseInt(num); for(z=2; z<decimal+1; z++){ if(decimal%z==0 && num%z==0){ decimal = decimal/z; num = num/z; z=2; } } //if format of fraction is xx/xxx if (decimal.toString().length == 2 && num.toString().length == 3) { //reduce by removing trailing 0's // ' decimal = Math.round(Math.round(decimal)/10); num = Math.round(Math.round(num)/10); } //if format of fraction is xx/xx else if (decimal.toString().length == 2 && num.toString().length == 2) { decimal = Math.round(decimal/10); num = Math.round(num/10); } //get highest common factor to simplify var t = HCF(decimal, num); //return the fraction after simplifying it if(isNaN(whole) === true) { whole = "0"; } if(isNaN(decimal) === true) { return ((whole==0)?"0" : whole); } else { return ((whole==0)?"0 " : whole+" ")+decimal/t+"/"+num/t; } } A: I know this is an old question, but I have created a function that has been greatly simplified. Math.fraction=function(x){ return x?+x?x.toString().includes(".")?x.toString().replace(".","")/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length))+"/"+("1"+"0".repeat(x.toString().split(".")[1].length))/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length)):x+"/1":NaN:void 0; } Call it with Math.fraction(2.56) It will: * *return NaN if the input is not a number *return undefined if the input is undefined *reduce the fraction *return a string (use Math.fraction(2.56).split("/") for an array containing the numerator and denominator) Please note that this uses the deprecated arguments.callee, and thus may be incompatible in some browsers. Test it here A: Intro & explanation Although old, I see this question has had some edits recently and its still the first thing that came up on search engines for me when I was looking into this. For that reason I wanted to share: if anyone comes to this looking for a simple (naive) solution that doesn't require pulling in a library, this is what I ended up using for my purpose. Its a simple brute-force that first looks if 1/⌊1/x⌉ is a good approximation, if not it checks 2/⌊2/x⌉, 3/⌊3/x⌉ and so on until the first result within the given error bound. Code function getFrac(x, maxErr){ let s = x<0?-1:1 x = Math.abs(x), i = Math.floor(x), d = x-i, maxErr = maxErr ? maxErr : Math.pow(10,-6); if(d<maxErr) return [i,1]; let n = 1, nmax = Math.ceil(d*Math.min( Math.pow(10,Math.ceil(Math.abs(Math.log10(maxErr)))), Number.MAX_SAFE_INTEGER )), min = Infinity, best = [0,0]; while(n <= nmax){ let err = Math.abs(d - n/Math.round(n/d)); if(err < maxErr) return [s*(n+i*Math.round(n/d)), Math.round(n/d)]; else if(err < min){ min = err; best = [s*(n+i*Math.round(n/d)), Math.round(n/d)]; } n++; } return best[1] == 0 ? false : best; } Example output: getFrac(0) // [0, 1] getFrac(0.28) // [7, 25] getFrac(0.28282828) // [28, 99] getFrac(2.56) // [64, 25] getFrac(-1.33333333) // [-4, 3] getFrac(Math.E) // [2721, 1001] getFrac(Math.PI) // [355, 113] getFrac(Math.PI, 0.01) // [22, 7] getFrac(Math.PI, 0.001) // [201, 64] getFrac(Math.PI, 10**-4) // [333, 106] getFrac(Math.PI, 10**-12) // [4272943, 1360120] Performance Although this is the naive approach, it runs surprisingly well, fast enough for most needs. Both JSbench and tests in my console using performance.now() indicate getFrac takes ~4 microseconds to return on average when fed random input using the default error level of 6 decimal places. The linked JSBench was giving me a result of ~200 ops/sec on my machine when calling getFrac 1000 times each op. I include below the timer script I used in the console. let N = 10000, nums = new Array(N).fill(0).map(v=>Math.random()*(Math.random()<2/3?1:100)), t = 0; for(let n of nums){ const t0 = performance.now(); getFrac(n); const t1 = performance.now(); t += t1-t0; } console.log((t/N)*1000,'micros'); // 4.039999999850989 micros
doc_23528099
Here's how my handler looks like: @RequestMapping(value = TEST_HANDLER_PATH, method = RequestMethod.POST) public ResponseEntity<String> handleTest(HttpServletRequest request, @RequestParam("parma1") String param) throws Exception { String ret = ... ... HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "text/plain;charset=utf-8"); return new ResponseEntity<String>(ret, headers, HttpStatus.CREATED); } I also tried annotating method with @ResponseBody with return ret; at the end. In both cases, when I hit the service, I get extra quotes around String value (e.g. "This is a test"). I'm guessing this is due to message conversion. That's why I tried defining Content-Type header, to hit StringHttpMessageConverter explicitly, to no avail. A: Had the same problem. Just make sure you register a org.springframework.http.converter.StringHttpMessageConverter as well as your Jackson one so that Strings are treated literally and not attempted to be converted to JSON (with extra quotes). Just instantiate with default constructor or constructor with your preferred Charset. The media types should be set for you with the standard internal defaults. If you're configuring via code extending WebMvcConfigurerAdapter then you just add the converters in the configureMessageConverters(List<HttpMessageConverter<?>> converters) method. A: In my case, I had over-engineered =) Had introduced a converter for bean's toString Operations like this: class SerializableToString implements Converter<Serializable, String> restricting that (only to my beans), resolved the issue X) Note: debugging with a breakpoint @ org.springframework.core.convert.support.GenericConversionService.getConverter helped. A: In a related scenario, I had an IntegrationFlow for a GET that incorrectly requested a transform. Basically the target service would receive the @PathVariable as a quote escaped string return IntegrationFlows.from("getThing") .transform(Transformers.toJson()) .handle( The .transform(Transformers.toJson()) was forcing the strings to be escaped in the URI, so simply removing it - it shouldn't have been there - fixed the issue. A: Turns out there was a JSON message converter registered in one of the imports.