_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
21
37k
language
stringclasses
1 value
title
stringclasses
1 value
d18423
test
I reckon this'll solve it: char* ptr = (char*)&t; *(int*)(ptr+sizeof(string)) = 10; sizeof will return the size in bytes. Pointer increments will go for the size of the object its pointing at. char is a byte in size. If you want to read up on it: C pointer arithmetic article Just to reiterate what I think you've said: you're just hacking around as a point of learning, and you know there's no way you should ever do this in real life... !! A: Why it doesn't work Really just never write code like this. There is a way to set private data and that is via public members on the class. Otherwise, it's private for a reason. This being C++, there are actually non-UB ways of doing this but I'm not going to link them here because don't. Why it doesn't work, specifically Hint: What does ptr + sizeof(string) actually mean, for ptr being an int*? What is ptr pointing to after this line? A: The pointer arithmetic should be done with byte pointers, not integer pointers. #include <iostream> #include <string> using namespace std; class Test { private: string s; int data; public: Test() { s = "New", data = 0; } int getData() { return data; } }; int main() { Test t; char* ptr = (char*)&t; *(int*)(ptr+sizeof(string)) = 10; cout << t.getData(); return 0; }
unknown
d18427
test
Giving this answer for completeness - even though your case was different. I've once named my django project test. Well, django was importing python module test - which is a module for regression testing and has nothing to do with my project. This error will occur if python finds another module with the same name as your django project. Name your project in a distinct way, or prepend the path of the parent directory of your application to sys.path. A: I think mod_python is looking for settings in the MKSearch module which doesn't exist in side the /home/user/django/MyDjangoApp directory. Try adding the parent dir to the PythonPath directive as below: <Location "/MyDjangoApp/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE MKSearch.settings PythonOption django.root /MyDjangoApp PythonPath "['/home/user/django/', '/home/user/django/MyDjangoApp,'/var/www'] + sys.path" PythonDebug On </Location> Or remove the module name from the DJANGO_SETTINGS_MODULE env var as below: <Location "/MyDjangoApp/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE settings PythonOption django.root /MyDjangoApp PythonPath "['/home/user/django/MyDjangoApp,'/var/www'] + sys.path" PythonDebug On </Location> A: The following example, located in my Apache configuration file, works. I found it very hard to get mod_python to work despite good answers from folks. For the most part, the comments I received all said to use mod_wsgi, instead of mod_python. Comments I've seen including from the Boston Python Meetup all concur mod_wsgi is easier to use. In my case on Red Hat EL 5 WS, changing from mod_python is not practical. <Location /> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE settings PythonOption django.root /home/amr/django/amr PythonPath "['/home/amr/django', '/home/amr/django/amr', '/usr/local/lib /site-packages/django'] + sys.path" PythonDebug On </Location>
unknown
d18429
test
It's actually unclear what your problem is. If you want the form submit to be idempotent/bookmarkable, then just remove method="post" from the HTML <form> element if you want the request to be bookmarkable. Don't forget to remove doPost() method from the servlet as well. Or if you actually want to let the form submit to a different servlet, then just create another servlet, register/map it the same way but on a bit different URL pattern and finally change the action URL of the HTML <form> element.
unknown
d18431
test
this.name represents the instance variable while the name variable is a parameter that is in the scope of the function (constructor in this case). With this assignment, the value of the local variable is assigned to the instance variable. A: This is not a javascript thing, it's an OOP thing. You want to leave the properties of an object isolated from other scopes. var Animal = function(name) { this.name = name; }; var name = "foo"; var dog = new Animal("bar"); // shows "foo" console.log(name); // shows "bar" console.log(dog.name); A: As use of the pronoun “he.” We could have written this: “John is running fast because John is trying to catch the train.” We don’t reuse “John” in this manner, . In a similar graceful manner, in JavaScript, we use the this keyword as a shortcut, a referent; it refers to an object; that is, the subject in context, or the subject of the executing code. Consider this example: var person = { firstName: "Penelope", lastName: "Barrymore", fullName: function () ​// Notice we use "this" just as we used "he" in the example sentence earlier?:​ console.log(this.firstName + " " + this.lastName); ​ // We could have also written this: console.log(person.firstName + " " + person.lastName); } } A: Well... you are working with an object constructor and prototype not just a function with two parameters where example: function Animals(pet1, pet2) { var pets = "first pet " + pet1 + " second pet " + pet2; console.log(pets); } Animals("Tiger", "Lion"); so referencing to your parameter as 'this.name' is a prototype of the sayName() if you know what i mean. FOR MORE.
unknown
d18433
test
We found the same problem. There is one more report here: https://mail-archives.apache.org/mod_mbox/subversion-users/201201.mbox/%[email protected]%3E Basically, if you have different ways to refer to the subversion server, for example, server and server.domain.com, you checkout a working copy from "server", but in the Maven root POM the SVN configuration points to server.domain.com, you will find this error. You have to enter the same name in the elemento in the root POM, and in the svn command used to check-out a project from the Subversion sever.
unknown
d18439
test
DISCLAIMER: Following answer is purely speculative * *I think key_file param of SSHHook is meant for this purpose *And the idiomatic way to supply it is to pass it's name via extra args in Airflow Connection entry (web UI) * *Of course when neither key_file nor credentials are provided, then SSHHook falls back to identityfile to initialize paramiko client. *Also have a look how SFTPHook is handling this
unknown
d18441
test
I would create a g element for entry in myData: groups = d3.select('body').append('svg') .selectAll('g').data(myData).enter() .append('g'); and append shapes to those group elements individually: groups.append('rect') groups.append('circle') A: Perhaps, what you want here is the .datum() function in d3. One of it's specific use-cases is to bind the same datum to multiple DOM elments (i.e. bind one datum to an entire d3 selection). For example, d3.selectAll('div').datum({foo: 'bar'}) would bind the same object {foo: 'bar'} to all of the <div>...</div> elements currently existing on the document. Quoting directly from https://github.com/mbostock/d3/wiki/Selections#datum selection.datum([value])...If value is specified, sets the element's bound data to the specified value on all selected elements. If value is a constant, all elements are given the same data [sic] (Somewhat ironically, he refers to the constant datum as "data" in the explanation of the .datum() function!) However, this is a literal answer to your question; there may be a more design-oriented answer to your question which might explain the "conventional" d3-way of handling your overall objective... In which case, you should probably consult some tutorials like http://mbostock.github.io/d3/tutorial/circle.html A: TLDR; Use Selection.data "key" argument function. A key function may be specified to control which datum is assigned to which element «This function is evaluated for each selected element, in order, […] The key function is then also evaluated for each new datum in data, […] the returned string is the datum’s key. (Search «If a key function is not specified…» paragraph) More details … D3 binds data to elements. By default is uses the «join-by-index» method (first found element maps to datum at index 0 and so forth…). If join-by-index is not enough to appropriately identify elements, Selection.data "key" should be used in order for D3 to appropriately synchronise input dataset during rendering phases: "update" (result of data() method call), "creation" enter selection, "removal" (exit selection). Let's say we need to draw some legend, given the following dataset … const dataSet = [ [ 15, "#440154" ] [ 238.58, "#414487" ] // ... ] we first decide to draw the coloured square using <rect> element. const updateSelection = d3.select('rect').data(dataSet); // join-by-index strategy is enough here so there is no need to supply the key fn arg // Key function could be `d => d[0]` (given data source cannot produce two entries // with value at index 0 being the same, uniqness is garanteed) updateSelection.enter() .append('rect') .attr('width', 15).attr('height', 15) .merge(updateSelection) .style('fill', d => d[1]) ; // Dispose outdated elements updateSelection.exit().remove(); We now need a <text> element to be drawn for each given datum to visually expose numeric values. Keeping join-by-index (default) strategy would cause D3 to first draw both rect and text elements but since there can only be a single element bound to a specific datum key, only the first found element will be considered upon update phase and any other element having same datum key will end up in the exit selection and removed from the DOM as soon as the Selection remove method is called. … If multiple elements have the same key, the duplicate elements are put into the exit selection … A solution is to concatenate the numeric value with the element nodeName. // Notice how the selector has changed const updateSelection = d3.select('rect, text').data(dataSet, function(d) { // Concatenate the numeric value with the element nodeName return `${d[0]}:${this.nodeName}`; }) , enterSelection = updateSelection.enter() ; // Add rect element enterSelection .append('rect').attr('width', 15).attr('height', 15) .merge(updateSelection) .style('fill', d => d[1]) ; // Add text label enterSelection .append('text') .merge(updateSelection) .text(d => d[0]) ; // Dispose outdated elements updateSelection.exit().remove();
unknown
d18443
test
The problem is that your class is called Math, so the compiler is looking for a method round() on your class, which doesn't exist. Rename your class to MyJavaLesson or somesuch, and then the compiler will know you want methods from java.lang.Math. You should never name your own classes with the same name as a class from anything under the java package, because it usually leads to confusion (as it has here). A: See if replacing double doubleValue to float doubleValue helps you.The Math.round() functions takes float as its arguements. Dont forget to add f after the float number assignment i.e float doubleValue = -3.999f. A: The main problem here is that this class is named Math (at the very top: public class Math {). Which overwrites the Math toolkit provided by java. If you name your class and file to something else it should be fine. p.s. generally by convention, we don't use capital letters in class and file names; to avoid these from happening. A: Thanks everyone for the help on this. Also, not sure if asking this question is allowed on this forum but was just curious how others learned Java? I am considering take a class at a community college but wondering if I am just better off learning from Lynda.com, Udemy, and Coursera.
unknown
d18445
test
You're looking for the function minimumBy in the Data.List module. It's type is minimumBy :: (a -> a -> Ordering) -> [a] -> a In your case, it would also be useful to import comparing from the Data.Ord module, which has the type comparing :: Ord a => (b -> a) -> b -> b -> Ordering And this lets you give it an "accessor" function to create an ordering. So in this case you can do minimumSnd :: [(String, Int)] -> (String, Int) minimumSnd = minimumBy (comparing ???) I'll let you fill in the ???, it should be quite easy at this point. What would your accessor function passed to comparing be for your type? If you wanted to write a custom function for this instead, I would suggest using the fold pattern. We can also take this opportunity to make it safer by returning a Maybe type, and more general by not requiring it to be a list of (String, Int): minimumSnd :: (Ord b) => [(a, b)] -> Maybe (a, b) minimumSnd = go Nothing where -- If the list is empty, just return our accumulator go acc [] = acc -- If we haven't found a minimum yet, grab the first element and use that go Nothing (x:xs) = go (Just x) xs -- If we have a minimum already, compare it to the next element go (Just currentMin) (x:xs) -- If it's <= our current min, use it | snd x <= snd currentMin = go (Just x) xs -- otherwise keep our current min and check the rest of the list | otherwise = go (Just currentMin) xs A: Try this: foldl1 (\acc x -> if snd x < snd acc then x else acc) <your list> You fold your list by comparing the current element of the list to the next one. If the second value of the next element if smaller than the value of the current element, it is the new value for the accumulator. Else the accumulator stays the same. This process is repeated until the entire list has been traversed. A: I am Haskell beginner but I wanted to find a working solution anyway and came up with: minTup' :: [(String, Int)] -> Maybe (String, Int) -> (String, Int) minTup' [] (Just x)= x minTup' (x:xs) Nothing = minTup' xs (Just x) minTup' ((s,n):xs) (Just (s',n')) | n < n' = minTup' xs (Just (s,n)) | otherwise = minTup' xs (Just (s',n')) minTup :: [(String, Int)] -> (String, Int) minTup [] = error "Need a list of (String,Int)" minTup x = minTup' x Nothing main = do print $ minTup [("CHURCH",262),("PENCIL",311),("FLOUR",175),("FOREST",405),("CLASS",105)] print $ minTup [("CHURCH",262)] print $ minTup []
unknown
d18447
test
Problem was with JDK/JRE. They were installed separately. Deleted them and installed from a bundle. Although they were the same version, project building kept on crashing.
unknown
d18451
test
When using file functions to access remote files (paths starting with http:// and similar protocols) it only works if the php.ini setting allow_url_fopen is enabled. Additionally, you have no influence on the request sent. Using CURL is suggested when dealing with remote files. If it's a local file, ensure that you have access to the file - you can check that with is_readable($filename) - and that it's within your open_basedir restriction if one is set (usually to your document root in shared hosting environments). Additionally, enable errors when debugging problems: ini_set('display_errors', 'on'); error_reporting(E_ALL);
unknown
d18453
test
Your input is very strange. Usually, I see matched square brackets. That aside, what you want is something like this: # This assumes you have Perl 5.10 or autodie installed: failures in open, readline, # or close will die automatically use autodie; # chunks of your input to ignore, see below... my %ignorables = map { $_ => 1 } qw( [notice mpmstats: rdy bsy rd wr ka log dns cls bsy: in ); # 3-arg open is safer than 2, lexical my $fh better than a global FH glob open my $error_fh, '<', 'error_log'; # Iterates over the lines in the file, putting each into $_ while (<$error_fh>) { # Only worry about the lines containing [notice if (/\[notice/) { # Split the line into fields, separated by spaces, skip the %ignorables my @line = grep { not defined $ignorables{$_} } split /\s+/; # More cleanup s/^\[//g for @line; # remove [ from [foo # Output the line print join(",", @line); # Assuming the second line always has "in" in it, # but this could be whatever condition that fits your data... if (/\bin\b/) { # \b matches word edges, e.g., avoids matching "glint" print "\n"; } else { print ","; } } } close $error_fh; I did not compile this, so I can't guarantee that I didn't typo somewhere. The key here is that you do the first print without a newline, but end with comma. Then, add the newline when you detect that this is the second line. You could instead declare @line outside the loop and use it to accumulate the fields until you need to output them with the newline on the end. A: One way using perl. It omits lines that don't contain [notice. For each line matching it increments a variable and saves different fields in an array depending if it is odd or even (first ocurrence of [notice or the second one). perl -ane ' next unless $F[5] eq q|[notice|; ++$notice; if ( $notice % 2 != 0 ) { push @data, @F[0..4, 8, 10, 12, 14, 16, 18, 20, 22]; next unless eof; } push @data, (eof) ? 0 : $F[8]; $data[0] =~ s/\A\[//; printf qq|%s\n|, join q|,|, @data; @data = (); ' infile Assuming infile has content of your question, output would be: Wed,Jun,13,01:41:34,2012,786,14,0,11,3,0,0,0,11
unknown
d18461
test
If you are asking if the Google .net client Library is thread safe. I am pretty sure that it is. It is noted in at least one place in the documentation that it is thread safe. Google APIs Client Library for .NET UserCredential is a thread-safe helper class for using an access token to access protected resources. An access token typically expires after 1 hour, after which you will get an error if you try to use it. A: It isn't. I've tried writing some code assuming it was, and my code would sometimes randomly crash at the "request.Execute()"s... I tried using a mutex and so only one thread was using a singleton service at a time: that reduced the crashes but it didn't eliminate them. Leaving the mutex in, I changed it to a singleton UserCredential and use a new service for each thread and it hasn't crashed since. (I don't know if I need the mutex anymore or not, but the google api calls aren't critical path for my application, I just needed to get the calls out of the main thread.)
unknown
d18465
test
This is a little late, but I just googled this exact problem (and ended here). I found the above solution did fix it, but then it could also be fixed by just adding "using System.Linq;" to the top resolved the issue. A: If you are certain UsersSet is some kind of a collection of User instances then you can try var t = from User e in entity.UsersSet where e.Id == 1 select e;
unknown
d18469
test
Typically you would not store this data in a table, you have all the data needed to generate the report. SQL Server does not have an easy way to generate a comma-separated list so you will have to use FOR XML PATH to create the list: ;with cte as ( select id, studentid, date, '#'+subject+';'+grade+';'+convert(varchar(10), date, 101) report from student ) -- insert into studentreport select distinct studentid, STUFF( (SELECT cast(t2.report as varchar(50)) FROM cte t2 where c.StudentId = t2.StudentId order by t2.date desc FOR XML PATH ('')) , 1, 0, '') AS report from cte c; See SQL Fiddle with Demo (includes an insert into the new table). Give a result: | ID | STUDENTID | REPORT | ------------------------------------------------------------------------------------ | 10 | 1 | #Biology;B;05/01/2013#Literature;B;03/02/2013#Math;A;02/20/2013 | | 11 | 2 | #Math;C;03/10/2013#Biology;A;01/01/2013 | | 12 | 3 | #Biology;A;04/08/2013 | A: If you are looking to insert the data from 'Students' into 'Student Report', try: INSERT INTO StudentReport (ID, StudentID, Report) SELECT ID, StudentID, '#' + subject + ';' + grade + ';' + date AS report FROM Students A: Without using CTE.Improve performance. FOR XML (select min(ID) as ID, StudentId, STUFF((select ', '+'#'+s2.Subject+';'+s2.Grade+';'+convert(varchar(25),s2.Date) from student s2 where s2.StudentId=s1.StudentId FOR XML PATH ('')) ,1,2,'') as report into t from student s1 group by StudentId) ; select * from t Where t would be new Table Name which doesn't exists in DataBase. SQL Fiddle
unknown
d18471
test
As @assylias mentioned in the comments the documentation for binarySearch I can quote from it Returns: index of the search key, if it is contained in the array within the specified range; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element in the range greater than the key, or toIndex if all elements in the range are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. So basically this is what happens in your attempt to search unsorted array: {6, 12, 3, 9, 8, 25, 10} * *it takes middle element 9 and compares it to your searched element 8, since 8 is lower it takes lower half {6, 12, 3} *in second step it compares 12 to 8 and since 8 is again lower it takes lower half {6} *6 doesn't equal 8 and since it's the last element it didn't find what you wanted *it returns (-(insertion point) - 1) where insertion point is the index of the first element in the range greater than the key *in your case that index is 1 since first element greater then 8 is 12 and it's index is 1 *when you put that into equation it returns (-1 - 1) which equals -2 Hope I have answered your question.
unknown
d18473
test
As Set-LocalGroup fails on that, the only other way I can think of is using ADSI: $group = [ADSI]"WinNT://$env:COMPUTERNAME/Group1,group" $group.Description.Value = [string]::Empty $group.CommitChanges() It's a workaround of course and I agree with iRon you should do a bug report on this. A: Although there are some AD attributes that requires the Putex method, that doesn't count for the Description attribute. Meaning my assumption in the initial comment to the question is wrong, and it is possible to clear the Description attribute with just the Put method`: $Name = 'Group1' New-LocalGroup -Name $Name -Description 'xxx' $Group = [ADSI]"WinNT://./$Name,group" $Group.Put('Description', '') $Group.SetInfo() Get-LocalGroup -Name $Name Name Description ---- ----------- Group1 The issue lays purely in the cmdlet parameter definitions. Without going into the C# programming, you might just pull this from the proxy command: $Command = Get-Command Set-LocalGroup $MetaData = [System.Management.Automation.CommandMetadata]$Command $ProxyCommand = [System.Management.Automation.ProxyCommand]::Create($MetaData) $ProxyCommand [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium', HelpUri='https://go.microsoft.com/fwlink/?LinkId=717979')] param( [Parameter(Mandatory=$true)] [ValidateNotNull()] # <-- Here is the issue [ValidateLength(0, 48)] [string] ${Description}, ... In other words, to quick and dirty workaround this with a proxy command: function SetLocalGroup { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium', HelpUri='https://go.microsoft.com/fwlink/?LinkId=717979')] param( [Parameter(Mandatory=$true)] [AllowEmptyString()] # <-- Modified [ValidateLength(0, 48)] [string] ${Description}, [Parameter(ParameterSetName='InputObject', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNull()] [Microsoft.PowerShell.Commands.LocalGroup] ${InputObject}, [Parameter(ParameterSetName='Default', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNull()] ${Name}, [Parameter(ParameterSetName='SecurityIdentifier', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNull()] [System.Security.Principal.SecurityIdentifier] ${SID}) end { if ($Description) { Set-LocalGroup @PSBoundParameters } elseif ($Name) { $Group = [ADSI]"WinNT://./$Name,group" $Group.Put('Description', '') $Group.SetInfo() } } } SetLocalGroup -Name 'Group1' -Description '' Related bug report: #16049 AllowEmptyString()] for -Description in Set-LocalGroup/SetLocalUser
unknown
d18475
test
OK, after upgrading to 5.2 the problem's gone.
unknown
d18477
test
Android doesn't have any "native" iBeacon capability at all, but you can see iBeacons using my company's open source Android iBeacon Library, which has APIs similar to those native to iOS 7. In the case of iOS, the CLLocationManagerDelegate gives you access to the didEnterRegion and didExitRegion callbacks that you describe. In the Android iBeacon Library, the equivalent is the MonitorNotifier interface that gives you the same callback methods. Making these callbacks successfully fire for apps that aren't in the foreground is a little tricky on both iOS and Android. On Android, you need to start a service of your own that runs when the Android device starts up, and bind to the IBeaconManager in that service. Setting this up isn't super easy, so we developed a Pro Android iBeacon Library that does all this automatically. Examples are here. EDIT: Both libraries above have been discontinued in favor of the free and open source Android Beacon Library which has all the feature of the pro library described above.
unknown
d18481
test
I don't think you need the else after the the first if statement. Something like the following might work, if left!=null: inorder(left) print(current_node.val) if (right!=null): inorder(right)
unknown
d18483
test
If we are using strings, then convert to symbol and evaluate (!!) while we do the assignment with (:=) library(dplyr) library(stringr) col_names <- names(my_data) for (i in seq_along(col_names)) { my_data <- my_data %>% mutate(!! col_names[i] := str_extract(!!rlang::sym(col_names[i]), '.+?(?=[a-z])')) } In tidyverse, we could do this with across instead of looping with a for loop (dplyr version >= 1.0) my_data <- my_data %>% mutate(across(everything(), ~ str_extract(., '.+?(?=[a-z])'))) If the dplyr version is old, use mutate_all my_data <- my_data %>% mutate_all(~ str_extract(., '.+?(?=[a-z])'))
unknown
d18487
test
You can use value_counts with df.stack(): df[['name1','name2']].stack().value_counts() #df.stack().value_counts() for all cols A 7 B 4 C 1 Specifically: (df[['name1','name2']].stack().value_counts(). to_frame('new').rename_axis('name').reset_index()) name new 0 A 7 1 B 4 2 C 1 A: Let us try melt df.melt().value.value_counts() Out[17]: A 7 B 4 C 1 Name: value, dtype: int64 A: Alternatively, df.name1.value_counts().add(df.name2.value_counts(), fill_value=0).astype(int) gives you A 7 B 4 C 1 dtype: int64 A: Using Series.append with Series.value_counts: df['name1'].append(df['name2']).value_counts() A 7 B 4 C 1 dtype: int64 value_counts converts the aggregated column to index. To get your desired output, use rename_axis with reset_index: df['name1'].append(df['name2']).value_counts().rename_axis('name').reset_index(name='new') name new 0 A 7 1 B 4 2 C 1 A: python Counter is another solution from collections import Counter s = pd.Series(Counter(df.to_numpy().flatten())) In [1325]: s Out[1325]: A 7 B 4 C 1 dtype: int64
unknown
d18495
test
Do not use post, use ajax sample: var paperData = 'name=' + sourceFileName + '&' + 'file=' + uploadFileName; var url = encodeURI('/Paper/Create?' + paperData); ajax ({ block: false, url: url, success: function (r) { if (r.success) { var html='<tr><td class="tac">'; html = html + r.displayName; html = html + '</td>'; html = html + '<td class="tac">'; html = html + r.type; html = html + '</td>'; html = html + '<td>'; html = html + '<a class="showPaperEditor" href="/Paper/Edit/'; html = html + r.paperID; html = html + '" w="570" h="340" >修改</a>'; html = html + '<span class="cd">┊</span>' ; html = html + '<a class="a-ajax-delPaper" href="/Paper/Delete/'; html = html + r.paperID; html = html + '">删除</a>'; html = html + '</td></tr>'; $('#tbPaperList').append(html); } else { alert(r.message); //$.unblockUI(); } } });
unknown
d18497
test
You have to add your drawings to your model and make sure your model is rendered, as appropriate, when the view is invalidated. You do not want to be drawing on the view directly without a model around to re-render it when necessary. Jacob
unknown
d18499
test
On function based views you would use decorators, in your particular case permission_required decorator @permission_required('abc.change_shiftchange', raise_exception=True) delete_viewgen(request,id)
unknown
d18503
test
You can mock loops in LESS using a recursive mixin with a guard expression. Here's an example applied to your case: #q1 { background-color: #ccc; } /* recursive mixin with guard expression - condition */ .darker-qs(@color, @index) when (@index < 10) { @darker-color: darken(@color, 10%); /* the statement */ #q@{index} { background-color: @darker-color; } /* end of the statement */ /* the next iteration's call - final expression */ .darker-qs(@darker-color, @index + 1); } /* the primary call - initialization */ .darker-qs(#ccc, 2);
unknown
d18511
test
Try to use {0,number,#} instead of {0}. Edit: More info: https://docs.oracle.com/javase/8/docs/api/java/text/MessageFormat.html
unknown
d18513
test
You've got 2 choices: * *Put the library jar on the classpath. *Assemble\Build the library jar with the regular jar. For option 1, you most likely need the jar located "near" the main jar on the file system; though, this is not necessarily a requirement. When you run the jar you then include the library jar on the classpath. For option 2, you use some type of tool like maven's assembly plugin or the fatjar plugin in Eclipse (sorry, I don't know what the analog is in NB). I hope this helps.
unknown
d18515
test
Let's think of your problem this way: You have a set of balls in 64-dimension space each with radius d, representing the space around each of your input vectors. (Note, I'm assuming that by "distance" you mean Euclidean distance). Now, you want to find the smallest subset of balls that will cover each of your original points, meaning that you need each point to be inside at least one ball in the subset, with the additional restriction that the balls in the cover must have centers also distance d apart. Without this additional restriction, you have an instance of a hard but well-studied one called Geometric set cover, which in turn is a special case of the more famous Set cover problem. It seems intuitively that the additional restriction makes the problem harder, but I don't have a proof for that. The bad news is, the (geometric) set cover problem is NP-hard, meaning that you won't be able to quickly find the exact minimum if there may be many points in the original set. The good news is, there are good algorithms that find approximate solutions, which will give you a set which isn't necessarily as small as possible, but which is close to the smallest possible. Here is Python code for a simple greedy algorithm which will not always find a minimum-size cover, but will always return a valid one: def greedy(V, d): cover = set() uncovered = set(V) # invariant: all(distance(x,y) > d for x in cover for y in uncovered) while uncovered: x = uncovered.pop() cover.add(x) uncovered = {y for y in uncovered if distance(x,y) > d} Note, you could make this greedy solution a little better by replacing the uncovered.pop() call with a smarter choice, for example choosing a vector which would "cover" the most number of remaining points. A: First, we can derive an undirected graph where vertices are the vectors of v and edges are the pairs of points that are no farther apart than r. This doesn't require the distances to be a proper metric: it doesn't have to satisfy the triangle inequality, only that it is symmetrical (dist(a,b) == dist(b,a)) and that it is 0 iff two points are equal. After that step, we can forget about the distances altogether and focus entirely on partitioning the graph. As others have noted, that partition is a Vertex Cover problem. However, it has a twist: we require all the vertices in the cover to be disjoint (i.e.: no vectors in v1 can be within distance r of each other). To obtain the graph, we can use the efficient KDTree to compute just once the nearest-neighbor structure. In particular, we'll use kd.sparse_distance_matrix(kd, r) to obtain all pairs of points separated by r or less: from scipy.spatial import KDTree def get_graph(v, r): kd = KDTree(v) sm = kd.sparse_distance_matrix(kd, r) graph = {i: {i} for i, _ in sm.keys()} for i, j in sm.keys(): graph[i] |= {j} return graph (note: .sparse_distance_matrix() has a parameter p if we want other distances than Euclidean). The partitioning of the graph can be done in various ways. @DanR shows a greedy approach that is very fast, but often suboptimal in the size of v1 that it finds. The following shows instead a brute-force approach that is guaranteed to find a minimal solution if there is one. It is adequate for relatively small number of vectors and can provide a ground-truth for the optimal solution, when researching other heuristics. To speed up the combinatorial search, we first observe that often some points are not within distance r of any other (i.e. the graph found above doesn't represent all the points of v). We can leave those other points aside, since they will necessarily be part of v1 but don't interfere with the rest of the search (below, we call them "singletons"). Second, we cut unpromising "leads" (prefixes in the combinatorial expansion) if they are not fully disjoint. This speeds up considerably the full search, by cutting down entire swathes of search space. If no prefix is cut, the full search is time-exponential. What is the speed of this? It depends on the distribution of the v vectors and (strongly) on the distance r. In fact, it depends on the number of clusters found. To give an idea, with v 20 vectors picked in uniform in 2D, I observe roughly 30ms. For 40 vectors, typically around 100ms, but it can jump to over 2 seconds for certain values of r. We implement a variation of combinations that has a check function to cut down unpromising prefixes: from itertools import combinations def _okall(tup, *args, **kwargs): return True def combinations_all(iterable, n0=1, n1=None, check=None, *args, **kwargs): pool = tuple(iterable) n = len(pool) if n0 > n: return n1 = n if n1 is None else n1 check = _okall if check is None else check if n0 < 1: yield () n0 = 1 seed = list(combinations(range(n), n0-1)) for r in range(n0, n1+1): prev_seed = seed seed = [] for prefix in prev_seed: for j in range(max(prefix, default=-1)+1, n): indices = prefix + (j,) tup = tuple(pool[i] for i in indices) if check(tup, *args, **kwargs): seed.append(indices) yield tup Example: # list all combinations of [0,1,2,3] (of all sizes), excluding those starting # by (0,1) >>> list(combinations_all(range(4), check=lambda tup: tup[:2] != (0,1))) [(0,), (1,), (2,), (3,), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), (0, 2, 3), (1, 2, 3)] Now, we use that to find the minimal disjoint cover and return the indices of v1: def check(tup, graph): # refuses tup if any one is within reach of another # optimization: tup[:-1] has already passed this test, so just check the last one if len(tup) < 2: return True reach_of_last = graph[tup[-1]] prefix = set(tup[:-1]) return prefix.isdisjoint(reach_of_last) def brute_vq(v, r): n = v.shape[0] graph = get_graph(v, r) to_part = set(graph) singletons = set(range(n)).difference(to_part) if not to_part: return sorted(singletons) for tup in combinations_all(to_part, check=check, graph=graph): # here tup are indices that are far apart enough (guaranteed disjoint in reach) # check if they fully cover to_part cover = {j for i in tup for j in graph[i]} if cover == to_part: v1_idx = sorted(singletons.union(tup)) return v1_idx Examples: v = np.random.uniform(size=(20, 2)) r_s = [[0.2, 0.3], [0.4, 0.5]] fig, axes = plt.subplots(nrows=len(r_s), ncols=len(r_s[0]), figsize=(12,12), sharex=True, sharey=True) for r, ax in zip(np.ravel(r_s), np.ravel(axes)): idx = brute_vq(v, r) ax.set_aspect('equal') ax.scatter(v[:, 0], v[:, 1]) for i, p in enumerate(v): ax.text(*p, str(i)) for i in idx: circ = plt.Circle(v[i], radius=r, color='g', fill=False) ax.add_patch(circ) plt.show(); A: My 5c: Create a distance matrix (this is an O*O operation, obviously): A B C D | min,max A 0 3 2 1 | 1,3 B 3 0 5 4 | 3,5 C 2 5 0 6 | 2,6 D 1 4 6 0 | 1,6 # note: D-C violates the triangle inequality Distance matrix, relabelled: A D B C | min,max A 0 1 3 2 | 1,3 D 1 0 4 6 | 1,6 B 3 4 0 5 | 3,5 C 2 6 5 0 | 2,6 Now, per row (or column) take tha max() of the min() (or the min() of the max()...) With a distance of 3, the NW-part is fully connected and the rest is still partially connected (with d=4, B would enter the subset, too) A D | B C | min,max A 0 1 | 3 2 | 1,3 D 1 0 | 4 6 | 1,6 ----+ ---------- B 3 4 | 0 5 | 3,5 C 2 6 | 5 0 | 2,6
unknown
d18519
test
You need to escape the HTML and specifically in this example, & and the character used to quote the attribute value (either " or '): <button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <b>own</b> review"}'></button> or: <button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <span style=&#39;text-decoration:underline&#39;>own</span> review"}'></button>
unknown
d18521
test
Try this : let newDiv = document.createElement("DIV"); newDiv.setAttribute("id", "hide"); document.body.appendChild(newDiv); document.getElementById("hide").style.zIndex = "9"; document.getElementById("hide").style.width = "100%"; document.getElementById("hide").style.height = "100%"; document.getElementById("hide").style.backgroundImage = "url('https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/p5020056.jpg')"; document.getElementById("hide").style.backgroundRepeat = "no-repeat"; document.getElementById("hide").style.backgroundSize = "cover"; document.getElementById("hide").style.top = "0"; document.getElementById("hide").style.position = "fixed"; document.body.style.margin = "0"; document.body.style.padding = "0"; <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
unknown
d18525
test
lFirst does not have any aggregate function (MAX, MIN, SUM, COUNT...) so there is no need to have a GROUP BY clause. Do not confuse between DISTINCT row operator and GROUP BY clause. Second, "BY EMP_PERSONAL.NEW_EMPNO DESC" Does not mean anything ! Is it a compement to GROUP BY or a part of ORDER BY ? To solve the first part, rewrite your query as : SELECT FIRST_NAME, MIDDLE_NAME,LAST_NAME , EMP_MOBILE_NO,NEW_EMPNO , SECTION_NAME, EMP_TYPE, JOINING_DATE FROM EMP_OFFICIAL,EMP_PERSONAL WHERE EMP_PERSONAL.STATUS='Active' AND EMP_OFFICIAL.WORK_ENT='Worker' AND EMP_OFFICIAL.EMPNO=EMP_PERSONAL.EMPNO Also a JOIN must be write with the JOIN operator not as a cartesian product followed by a restriction. So rewrite your query as : SELECT FIRST_NAME, MIDDLE_NAME,LAST_NAME , EMP_MOBILE_NO,NEW_EMPNO , SECTION_NAME, EMP_TYPE, JOINING_DATE FROM EMP_OFFICIAL JOIN EMP_PERSONAL ON EMP_OFFICIAL.EMPNO=EMP_PERSONAL.EMPNO WHERE EMP_PERSONAL.STATUS='Active' AND EMP_OFFICIAL.WORK_ENT='Worker' This will be most optimized by the optimizer because it not spread time and operations to do the translation between false JOIN and real joins...
unknown
d18529
test
One way to make code available across different script scopes is to use a WinJS namespace. For example, in page1.js, you would have: (function(){ function setText(){ var mytext = ""; WinJS.Namespace.define("page1", { text: mytext }); } })(); in page2.js, you'd put the text in that namespace: (function(){ page1.text = "page 2 text!"; })(); Back in page 1, you can retrieve that value later on: (function(){ function setText(){ var mytext = ""; WinJS.Namespace.define("page1", { text: mytext }); } function getText() { document.querySelector("#myTextField").value = page1.text; } })(); I'd suggest being a bit more formal about what you put in namespaces, but that's one way to do it.
unknown
d18531
test
As Evert said, the commit() was missing. An alternative to always specifying it in your code is using the autocommit feature. http://initd.org/psycopg/docs/connection.html#connection.autocommit For example like this: with psycopg2.connect("...") as dbconn: dbconn.autocommit=True A: You forgot to do connection.commit(). Any alteration in the database has to be followed by a commit on the connection. For example, the sqlite3 documentation states it clearly in the first example: # Save (commit) the changes. conn.commit() And the first example in the psycopg2 documentation does the same: # Make the changes to the database persistent >>> conn.commit()
unknown
d18533
test
Make sure that MySQL.Data.dll actually got copied to the output folder. And that you are using right platform (x32 vs x64 bit) and right version of .NET (2,3,3.5 vs 4). If everyhing seems fine, enable Fusion Logging and take a look at this article: For FileNotFoundException: At the bottom of the log will be the paths that Fusion tried probing for this assembly. If this was a load by path (as in Assembly.LoadFrom()), there will be just one path, and your assembly will need to be there to be found. Otherwise, your assembly will need to be on one of the probing paths listed or in the GAC if it's to be found. You may also get this exception if an unmanaged dependency or internal module of the assembly failed to load. Try running depends.exe on the file to verify that unmanaged dependencies can be loaded. Note that if you re using ASP.NET, the PATH environment variable it's using may differ from the one the command line uses. If all of them could be loaded, try ildasm.exe on the file, double-click on "MANIFEST" and look for ".file" entries. Each of those files will need to be in the same directory as the manifest-containing file.
unknown
d18537
test
all_objects only shows you objects you have permissions on, not all objects in the database. You'd need to query dba_objects to see everything, if you have permissions to do that. public_dependency appears to include object IDs for objects you don't have permissions on. The objecct IDs on their own don't tell you much, so it isn't revealing anything about objects you can't see (other than that there are some objects you can't see). So it isn't odd that there is an apparent discrepancy between what the two views reference. Querying all_dependencies might give you a more comsistent picture.
unknown
d18545
test
This took me quite a long time to answer since I had to create my own format currency function. A live demo can be found here: http://jsfiddle.net/dm6LL/ The basic updating each second is very easy and will be done through JavaScript's setInterval command. setInterval(function(){ current += .158; update(); },1000); The update() function you see in the above code is just a simple updater referencing an object with the amount id to put the formatted current amount into a div on the page. function update() { amount.innerText = formatMoney(current); } Amount and current that you see in the update() function are predefined: var amount = document.getElementById('amount'); var current = 138276343; Then all that's left is my formatMoney() function which takes a number and converts it into a currency string. function formatMoney(amount) { var dollars = Math.floor(amount).toString().split(''); var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1]; if(typeof cents == 'undefined'){ cents = '00'; }else if(cents.length == 1){ cents = cents + '0'; } var str = ''; for(i=dollars.length-1; i>=0; i--){ str += dollars.splice(0,1); if(i%3 == 0 && i != 0) str += ','; } return '$' + str + '.' + cents; }​
unknown
d18547
test
You don't need to store the playerID to check identities. Local playerID can be accessed always with: [GKLocalPlayer localPlayer].playerID As to how to use playerID now that it's deprecated, that property was only moved from GKTurnBasedParticipant to GKPlayer. That doesn't affect the code that I pasted before, but it does affect the way you access to match.participants. So, for any given player, the way to access it in iOS8 would be: GKTurnBasedParticipant *p1 = (GKTurnBasedParticipant *)self.match.participants[index]; p1.player.playerID As you can see, you only have to add a .player to your current code.
unknown
d18549
test
Use DataFrame.assign: df = df.assign(result_multiplied = df['result']*2) Or if column result is processing in code before is necessary lambda function for processing counted values in column result: df = df.assign(result_multiplied = lambda x: x['result']*2) Sample for see difference column result_multiplied is count by multiple original df['result'], for result_multiplied1 is used multiplied column after mul(2): df = df.mul(2).assign(result_multiplied = df['result']*2, result_multiplied1 = lambda x: x['result']*2) print (df) index result result_multiplied result_multiplied1 0 AA 2 2 4 1 BB 4 4 8 2 CC 6 6 12
unknown
d18555
test
When you run $ sudo pip install... system pip will be used. So to install flask in current environment just run $ pip install ... or as: $ /path/to/venv/bin/pip install ... Or make your venv able to load global system packages by parameter --system-site-packages, while configure virtual environment. A: If you are having the same trouble even if you have your virtualenv running, just make sure you didn't accidentally delete the files and attempt to execute pip in that folder you created for your venv... Like I did. :D
unknown
d18557
test
You are not really providing too much details of the issue. I can give some generic guidelines: * *Ensure that there is network connectivity. If you are testing Postman and Mule from the same computer it is probably not an issue. *Ensure host, port and certificates (if using TLS) are the same. Pointing an HTTPS request to port 80 could cause a timeout sometimes. *Enable HTTP Wire logging in Mule and compare with Postman code as HTTP to identify any significant difference between the requests. For example: headers, URI, body should be the same, except probably for a few headers. Depends on the API. This is usually the main cause for differences between Postman and Mule, when the request are different.
unknown
d18561
test
Implement this in your appdelegate and show an alert : func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { }
unknown
d18567
test
Are you using apache server? Check if you have mod_rewrite enabled. A: Just in case, if you have created any folder on you live website for your code, than try using below line RewriteBase /yourFolderName/ keep above code just below RewriteEngine On A: This one worked for me: Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / ## don't touch /forum URIs RewriteRule ^forums/ - [L,NC] ## hide .php extension snippet # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R,L] # To internally forward /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*?)/?$ $1.php [L]
unknown
d18573
test
I assume you have a table view with cells that can be swiped left, and that swiping shows a delete button entitled DELETE. Then you could do the following: let firstCell = XCUIApplication().cells.element(boundBy: 0) firstCell().swipeLeft() let deleteButton = firstCell.buttons[„DELETE“] deleteButton.tap() EDIT: Thanks for your edit! Your delete button does not have any title text. Thus, you cannot access the button with firstCell.buttons[„DELETE“]. From your screen shot it looks as if the delete button was the only button in the cell. If so, you could try firstCell.buttons.firstMatch. If you have more buttons, you could access the delete button using firstCell.buttons.element(boundBy: 0) where „0“ had to be replaced by the correct index.
unknown
d18579
test
No, you cannot do that without a loop or equivalent construct. (full stop) You can hide the loop inside some functions, such as std::transform(), but not avoid it. Moreover, compilers are well trained to optimize loops (because they are ubiquotous), so there is no good reason to avoid them. A: Without an explicit loop: std::transform( std::begin(mykeys), std::end(mykeys), std::inserter(myMap, myMap.end()), [] (char c) {return std::make_pair(c, 0);} ); Demo. A range-based for loop would be far more sexy though, so use that if possible: for (auto c : mykeys) myMap.emplace(c, 0); A: You can not do this without a loop. What you can do is to hide a loop under a standard algorithm because you need to convert an object of type char to an object of type std::map<char, int>::value_type that represents itself std::pair<const char, int> For example #include <iostream> #include <vector> #include <map> #include <iterator> #include <algorithm> int main() { std::vector<char> v { 'a', 'b', 'c' }; std::map<char, int> m; std::transform( v.begin(), v.end(), std::inserter( m, m.begin() ), []( char c ){ return std::pair<const char, int>( c, 0 ); } ); for ( const auto &p : m ) { std::cout << p.first << '\t' << p.second << std::endl; } return 0; } The output is a 0 b 0 c 0 A: Using boost: template<class Iterators, class Transform> boost::iterator_range< boost::transform_iterator< typename std::decay_t<Transform>::type, Iterator >> make_transform_range( Iterator begin, Iterator end, Transform&& t ) { return { boost::make_transform_iterator( begin, t ), boost::make_transform_iterator( end, t ) }; } A helper to map keys to pairs: template<class T> struct key_to_element_t { T val; template<class K> std::pair< typename std::decay<K>::type, T > operator()(K&& k) const { return std::make_pair( std::forward<K>(k), val ); } }; template<class T> key_to_element_t< typename std::decay<T>::type > key_to_element( T&& t ) { return { std::forward<T>(t) }; } template<class R> struct range_to_container_t { R r; template<class C> operator C()&& { using std::begin; using std::end; return { begin(std::forward<R>(r)), end(std::forward<R>(r)) }; } }; template<class R> range_to_container_t<R> range_to_container( R&& r ) { return std::forward<R>(r); } after all that mess we get: std::vector<char> mykeys { 'a', 'b', 'c' ]; std::map<char, int> myMap = range_to_container( make_transform_range( begin(mykeys), end(mykeys), key_to_element( 0 ) ) ); which constructs the std::map directly from a transformed sequence of elements in the mykeys vector. Pretty silly.
unknown
d18581
test
You can not align directly on a surface. You have to wrap your content with Column, Row, Box, etc. You can change your code like the following @Composable fun MainScreen(message: String) { Surface { Column { Surface( modifier = Modifier .width(500.dp) .height(250.dp), color = Color.Green ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text(text = message) } } Surface( modifier = Modifier .width(500.dp) .height(250.dp), color = Color.Blue ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text( text = message ) } } } } }
unknown
d18583
test
Have you added a Setup project to the solution? It seems to me that those take much longer to load than other types of projects.
unknown
d18585
test
Firstly page of top you put used db connection related code : $conn = mysql_connect('localhost', 'user', 'pass'); mysql_select_db('details_db'); and then bellow and removed mysql_select_db('details_db'); line after mysql_ $funds = $_POST['funds']; $withdraw_or_add = $_POST['list']; if($withdraw_or_add == "add") { $sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1"; } else { $info = mysql_query("SELECT * FROM users WHERE userId = '1'"); $info = mysql_fetch_assoc($info); $new_fund = $info['userFunds'] - $funds; $sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1"; } //mysql_select_db('details_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not update data: ' . mysql_error()); } echo "Updated data successfully\n"; mysql_close($conn); Note: Please stop using mysql_* functions. mysql_* extensions have been removed in PHP 7. Please used PDO and MySQLi.
unknown
d18587
test
It appears the @angular/core is version ~7.2.0 but the @angular/material is ^9.2.3. You either need to upgrade the Angular or downgrade the Angular Material library. I'd rather downgrade the Material library. Try the following commands in order npm uninstall @angular/material npm uninstall @angular/cdk npm install @angular/[email protected] npm install @angular/[email protected] A: I'm not sure why this happened (normally the dependencies of material 9 are set to angular 9), but you can delete it and resintall the correct version again npm un -S @angular/material @angular/cdk npm add -S @angular/material@7 @angular/cdk@7
unknown
d18589
test
I would use some kind of Java JSON Serializer, there a few of them out there. * *GSON *FlexJson Here is a simple example with FlexJson on how you could convert an object to JSON String. final JSONSerializer serializer = new JSONSerializer(); final String output = serializer.transform(new ProtocolCalculatorTransformer(),ProtocolCalculation.class).exclude("*.class").deepSerialize(this); return output;
unknown
d18591
test
from bs4 import BeautifulSoup import requests url = 'https://bitskins.com/' page_response = requests.get(url, timeout=5) page_content = BeautifulSoup(page_response.content, 'html.parser') skin_list = page_content.findAll('div', class_ = 'panel item-featured panel-default') for skin in skin_list: name = skin.find("div", class_ = "panel-heading item-title") price = skin.find("span", class_ = "item-price hidden") discount = skin.find("span", class_ = "badge badge-info") wear = skin.find("span", class_ = "hidden unwrappable-float-pointer") print("name:", name.text) print("Price", price.text) print("Discount:", discount.text) # Choose which one you want for w in wear.text.split(","): print("Wear:", w) You was trying to find the incorrect class. I added some other data which you can scrape for examples. Wear holds a few values which i outputted. A: In your line of code, you are searching for a tag with a class that has multiple values. wear_box = page_content.find_all('div', attrs={'class': 'text-muted text-center'}) On the page the only tag that fits is: <div class="container text-center text-muted" style="padding-top: 17px;"> In BS4, when you are searching for attributes with multiple values, you either search for a single value eg: wear_box = page_content.find_all('p', attrs={'class': 'text-muted'}) Or you have to search for the exact list of vales eg: wear_box = page_content.find_all('div', attrs={'class': 'container text-center text-muted'})
unknown
d18593
test
options.AcceptAnonymousClients() has no effect on the code flow as client_id is a mandatory parameter in this case (it only affects the token, introspection and revocation endpoints). options.SignInScheme cannot be set to a scheme belonging to OpenIddict. In most cases, it must correspond to a cookie handler (typically the one registered by Identity). You will also want to remove /signin-google from the endpoints managed by OpenIddict, as it will prevent the Google authentication handler from working properly.
unknown
d18601
test
One nuance to be aware of. IsWindowVisible will return the true visibility state of the window, but that includes the visibility of all parent windows as well. If you need to check the WS_VISIBLE flag for a specific window you can do GetWindowLong(hWnd, GWL_STYLE) and test for WS_VISIBLE. ... It sounds like you don't need to do this for your case, but adding this for future reference in case others run across this question. A: Do you have an HWND to the window? If not, then you will need to obtain the window handle somehow, for example through FindWindow() (or FindWindowEx()). Once you have the HWND to the window, call IsWindowVisible().
unknown
d18607
test
Here's the solution. You have to iterate through all option elements, grab the value of every element and push inside an array. function getValues() { var array = document.getElementsByTagName('option'); var arr = []; for (var i = 0; i < array.length; i++) { arr.push(array[i].value) } console.log(arr); }; <select id="options"> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button id="submit" onclick="getValues()">Submit</button> ES6 solution: function getValues() { var array = document.getElementsByTagName('option'); var arr = []; Array.from(array).forEach(v => arr.push(v.value)); console.log(arr); }; <select id="options"> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button id="submit" onclick="getValues()">Submit</button> A: Assuming that ES6 is an option for you, then the following will do as you wish: // using a named function: function grabTextFrom() { // initialising the local variable using 'let', // converting the argument supplied to Array.from() // to convert the Array-like Object (in this case // a NodeList, or HTMLCollection, from // document.querySelectorAll()) into an Array: let texts = Array.from( document.querySelectorAll( // 'this' is passed automatically from the // later use of EventTarget.addEventListener(), // and the dataset.textFrom property value is // the value stored in the data-textfrom attribute: this.dataset.textfrom ) // iterating over that Array of elements using // Array.prototype.map() along with an arrow function: ).map( // 'opt' is a reference to the current Array-element // from the Array of elements over which we're iterating; // and here we return the value property-value of that // current element: opt => opt.value ); // logging to the console for demo purposes: console.log(texts); // returning to the calling context: return texts; } // finding the first element which matches the // supplied CSS selector, and adding the // grabTextFrom() function as the event-handler // for the 'click' event (note the deliberate // lack of parentheses in the function-name): document.querySelector('#submit').addEventListener('click', grabTextFrom); function grabTextFrom() { let texts = Array.from( document.querySelectorAll(this.dataset.textfrom) ).map( opt => opt.value ); console.log(texts); return texts; } document.querySelector('#submit').addEventListener('click', grabTextFrom); <select id="options"> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button id="submit" data-textfrom="option">Submit</button> If, however, you have to provide for ES5 compatibility then the following will work identically: function grabTextFrom() { // here we use Array.prototype.slice(), along // with Function.prototype.call(), to apply // the slice() method to the supplied NodeList: var texts = Array.prototype.slice.call( document.querySelectorAll(this.dataset.textfrom) // here we use the anonymous function of the // Array.prototype.map() method to perform the // same function as above, returning the // opt.value property-value to the created Array: ).map(function(opt) { return opt.value; }); console.log(texts); return texts; } document.querySelector('#submit').addEventListener('click', grabTextFrom); function grabTextFrom() { var texts = Array.prototype.slice.call( document.querySelectorAll(this.dataset.textfrom) ).map(function(opt) { return opt.value; }); console.log(texts); return texts; } document.querySelector('#submit').addEventListener('click', grabTextFrom); <select id="options"> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button id="submit" data-textfrom="option">Submit</button> A: You're close. document.getElementsByTagName('option') returns an array of <option> elements. You can't get .value on an array of elements - you can only call it on a single <option> element. How would you get .value for each element in your array?
unknown
d18609
test
You could make the check like this (todayDate - oldDate) / (1000 * 3600 * 24 * 365) > 1 You can see and try it here: https://jsfiddle.net/rnyxzLc2/ A: This code should handle leap years correctly. Essentially: If the difference between the dates' getFullYear() is more than one, or the difference equals one and todayDate is greater than oldDate after setting their years to be the same, then there's more than a one-year difference. var oldDate = new Date("Oct 2, 2014 01:15:23"), todayDate = new Date(), y1= oldDate.getFullYear(), y2= todayDate.getFullYear(), d1= new Date(oldDate).setFullYear(2000), d2= new Date(todayDate).setFullYear(2000); console.log(y2 - y1 > 1 || (y2 - y1 == 1 && d2 > d1)); A: use getFullYear(): fiddle: https://jsfiddle.net/husgce6w/ var oldDate = new Date("July 21, 2001 01:15:23"); var todayDate = new Date(); var thisYear = todayDate.getFullYear(); var thatYear = oldDate.getFullYear(); console.log(todayDate); console.log(thatYear); if(thisYear - thatYear > 1) { console.log("it has been over one year!"); } else { console.log("it has not gone one year yet!"); }
unknown
d18611
test
One thing to check is that Xcode is searching the library headers properly (especially with LinkingIOS). "This step is not necessary for libraries that we ship with React Native with the exception of PushNotificationIOS and LinkingIOS." Linking React Native Libraries in Xcode A: Is the LinkingIOS.openURL function supposed to run after a response from the server in the fetch block? If so, then you'll want to include it in a another then block. As it is written now, LinkingIOS.openURL will run right after the fetch line. Then, as they resolve or error out, the then and catch blocks of fetch will run.
unknown
d18615
test
Yes, it can be done. There are more possible approaches to this. The first one, which is the cleanest, is to keep a second buffer, as suggested, of the length of the searched word, where you keep the last chunk of the old buffer. (It needs to be exactly the length of the searched word because you store wordLength - 1 characters + NULL terminator). Then the quickest way is to append to this stored chunk from the old buffer the first wordLen - 1 characters from the new buffer and search your word here. Then continue with your search normally. - Of course you can create a buffer which can hold both chunks (the last bytes from the old buffer and the first bytes from the new one). Another approach (which I don't recommend, but can turn out to be a bit easier in terms of code) would be to fseek wordLen - 1 bytes backwards in the read file. This will "move" the chunk stored in previous approach to the next buffer. This is a bit dirtier as you will read some of the contents of the file twice. Although that's not something noticeable in terms of performance, I again recommend against it and use something like the first described approach. A: use the same algorithm as per fgetc only read from the buffers you created. It will be same efficient as strstr iterates thorough the string char by char as well.
unknown
d18617
test
I suggest you read a little bit more about this topic. just as a quick answer. TCP makes sure that all the packages are delivered. So if one is dropped for whatever reason. The sender will continue sending it until the receiver gets it. However, UDP sends a packet and just forgets it, so you might loose some of the packets. As a result of this, UDP sends less number of packets over network. This is why they use UDP for videos because first loosing small amount of data is not a big deal plus even if the sender sends it again it is too late for receiver to use it, so UDP is better. In contrast, you don't want your online banking be over UDP! Edit: Remember, the speed of sending packets for both UDP and TCP is almost same, and depends on the network! However, after handshake is done in TCP, still receiver needs to send the acks, and sender has to wait for ack before sending new batch of data, so still would be a little slower. A: In general, TCP is marginally slower, despite less header info, because the packets must arrive in order, and, in fact, must arrive. In a UDP situation, there is no checking of either.
unknown
d18621
test
No, the bounds of the range both have to be static expressions. But you can declare a subtype with dynamic bounds: X: Integer := some_value; subtype Dynamic_Subtype is Integer range 1 .. X; A: Can type Airplane_ID is range 1..x; be written where x is a variable? I ask this because I want to know if the value of x can be modified, for example through text input. I assume that you mean such that altering the value of x alters the range itself in a dynamic-sort of style; if so then strictly speaking, no... but that's not quite the whole answer. You can do something like this: Procedure Test( X: In Positive; Sum: Out Natural ) is subtype Test_type is Natural Range 1..X; Result : Natural:= Natural'First; begin For Index in Test_type'range loop Result:= Result + Index; end loop; Sum:= Result; end Test; A: No. An Ada range declaration must be constant. A: As the other answers have mentioned, you can declare ranges in the way you want, so long as they are declared in some kind of block - a 'declare' block, or a procedure or function; for instance: with Ada.Text_IO,Ada.Integer_Text_IO; use Ada.Text_IO,Ada.Integer_Text_IO; procedure P is l : Positive; begin Put( "l =" ); Get( l ); declare type R is new Integer range 1 .. l; i : R; begin i := R'First; -- and so on end; end P;
unknown
d18623
test
You can use union all. This returns the most recent image from the two tables combined for each id: with ab as ( select a.* from TableA a union all select b.* from TableB b ) SELECT ID, Image FROM (SELECT ab.*, ROW_NUMBER() OVER (PARTITION BY id ORDER BY DATE DESC, TIME DESC) as seqnum FROM ab ) ab WHERE seqnum = 1; ORDER BY Date DESC, Time DESC LIMIT 5; A: If what you need is the rows with the latest date and time (as your expected results): with cte as ( select * from Tablea union all select * from Tableb ) select * from cte where Date || Time = (select max(Date || Time) from cte) order by id I assume the dates are always in the format MM/YY and the times hh:mm. See the demo. Results: | ID | Image | Date | Time | | --- | ----- | ----- | ----- | | 0 | 5 | 12/03 | 12:35 | | 1 | 3 | 12/03 | 12:35 | | 2 | 7 | 12/03 | 12:35 |
unknown
d18625
test
Use the Key event listener. var key:Object = { onKeyDown:function() { switch(Key.getCode()) { case 49: trace('key 1 is down'); break; case 50: trace('key 2 is down'); break; } } }; Key.addListener(key); Then you can handle actions in the switch statement.
unknown
d18631
test
Use the following code: include_once('Simple/autoloader.php'); $feed = new SimplePie(); $feed->set_feed_url($url); $feed->enable_cache(false); $feed->set_output_encoding('utf-8'); $feed->init(); $i=0; $items = $feed->get_items(); foreach ($items as $item) { $i++; /*You are getting title,description,date of your rss by the following code*/ $title = $item->get_title(); $url = $item->get_permalink(); $desc = $item->get_description(); $date = $item->get_date(); } Download the Simple folder data from : https://github.com/jewelhuq/Online-News-Grabber/tree/master/worldnews/Simple Hope it will work for you. There $url mean your rss feed url. If you works then response. A: Turns out, it's simple by using the PHP xml parer function: $xml = simplexml_load_file ($path . 'RSS.xml'); $channel = $xml->channel; $channel_title = $channel->title; $channel_description = $channel->description; echo "<h1>$channel_title</h1>"; echo "<h2>$channel_description</h2>"; foreach ($channel->item as $item) { $title = $item->title; $link = $item->link; $descr = $item->description; echo "<h3><a href='$link'>$title</a></h3>"; echo "<p>$descr</p>"; }
unknown
d18633
test
I just answered this question here, but the general gist is: I was able to achieve this affect by calling setExpand(true) as the first line of my onCreateView() in my RowsFragment. If you want to lock this effect forever, you can override setExpand(...) in your RowsFragment and just call super.setExpand(true). I believe you'll still need the initial call in onCreateView() though.
unknown
d18639
test
import os, ssl from flask import Flask, request, redirect, url_for from werkzeug import secure_filename UPLOAD_FOLDER = '/home/ubuntu/shared/' certfile = "/home/ubuntu/keys/fullchain.pem" keyfile = "/home/ubuntu/keys/privkey.pem" ecdh_curve = "secp384r1" cipherlist = "ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305" sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) sslcontext.options |= ssl.OP_NO_TLSv1 sslcontext.options |= ssl.OP_NO_TLSv1_1 sslcontext.protocol = ssl.PROTOCOL_TLSv1_2 sslcontext.set_ciphers(cipherlist) sslcontext.set_ecdh_curve(ecdh_curve) sslcontext.load_cert_chain(certfile, keyfile) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'POST': my_data = request.files.getlist('file') my_pass = request.form['password'] if my_data and my_pass == 'yakumo': for file in my_data: my_handler(file) return redirect(url_for('index')) return """ <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form action="" method=post enctype=multipart/form-data> <p><input type=file multiple name=file> <input type="password" name="password" value=""> <input type=submit value=Upload> </form> <p>%s</p> """ % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],)) def my_handler(f): filename = secure_filename(f.filename) f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) if __name__ == "__main__": app.run(host='0.0.0.0', port=8000, ssl_context=sslcontext, threaded=True, debug=False) I made a very rookie mistake and didn't for-loop over the multiple files being uploaded. The code here was tested without issues with 4 simultaneous file uploads. I hope it will be useful to someone. Edit: Code updated with some sweet TLS_1.2 and a password field. Enjoy a reasonably secure upload server. Password is transferred over HTTPS.
unknown
d18641
test
You'll want to use the callback method of $.fn.show, read more at http://api.jquery.com/show/ Here's a fiddle showing the proposed change: http://jsfiddle.net/pewt8/
unknown
d18645
test
First of all, the public methods of UIManager are static. It is incorrect, misleading, and pointless to create an instance of UIManager. The correct way to invoke those methods is: UIManager.put("OptionPane.background", Color.BLUE); UIManager.put("OptionPane.messagebackground", Color.BLUE); UIManager.put("Panel.background", Color.BLUE); This is the whole sample. import javax.swing.event.*; import java.awt.event.*; import javax.swing.*; import java.awt.*; public class Main extends JFrame { public static void main(String []args) { UIManager.put("OptionPane.background", Color.blue); UIManager.put("Panel.background", Color.blue); UIManager.put("Button.background", Color.white); String value = JOptionPane.showInputDialog("Enter your name"); System.out.println("Hello " + value); // exit awt thread System.exit(1); } } A: In nimbus look and feel these all codes are not usable. So solution is, UIManager.put("control", new Color(0, 0, 0)); This is also call "Dark Nimbus" add this top of your main frame's main method. So it will automatically change All JOptionPane's background. And also you can't change button background with UIManager.put("OptionPane.buttonBackground", BLACK); So you should use, UIManager.put("nimbusBase", new Color(0, 0, 0)); Remember - but unfortunately, this code will change all your buttons etcs' background. So you have to add *.setBackground(...); to all other objects. If you want to change foreground of JOptionPane you should use UIManager.put("text", new Color(255, 255, 255)); Again unfortunately this will change your all of text's foreground. These all codes are called Dark Nimbus. If you're using nimbus you can try these UIManager codes to customize nimbus look and feel. UIManager.put("control", new Color(0, 0, 0)); UIManager.put("info", new Color(0, 0, 0)); UIManager.put("nimbusBase", new Color(0, 0, 0)); UIManager.put("nimbusAlertYellow", new Color(248, 187, 0)); UIManager.put("nimbusDisabledText", new Color(255, 255, 255)); UIManager.put("nimbusFocus", new Color(115, 164, 209)); UIManager.put("nimbusGreen", new Color(176, 179, 50)); UIManager.put("nimbusInfoBlue", new Color(66, 139, 221)); UIManager.put("nimbusLightBackground", new Color(0, 0, 0)); UIManager.put("nimbusOrange", new Color(191, 98, 4)); UIManager.put("nimbusRed", new Color(169, 46, 34)); UIManager.put("nimbusSelectedText", new Color(255, 255, 255)); UIManager.put("nimbusSelectionBackground", new Color(18, 134, 175)); UIManager.put("text", new Color(255, 255, 255)); You can try these codes. In my project the nimbus seem as But I always recommend using "Flatleaf" (Search google "FlatLafLookAndFeel" or go to jar.download.com"). It is a professional and you can change all to your own.
unknown
d18647
test
The latter doesn't work because the decimal value is boxed into an object. That means to get the value back you have to unbox first using the same syntax of casting, so you have to do it in 2 steps like this: double dd = (double) (decimal) o; Note that the first (decimal) is unboxing, the (double) is casting. A: This can be done with Convert.ChangeType: class Program { static void Main(string[] args) { decimal dec = new Decimal(33); object o = (object)dec; double dd = GetValue<double>(o); Console.WriteLine(dd); } static T GetValue<T>(object val) { return (T)Convert.ChangeType(val, typeof(T)); } } The reason your code doesn't work has been well explained by others on this post. A: You can only cast boxed value types back to the exact type that was boxed in. It doesn't matter if there is an implicit or explicit conversion from the boxed type to the one you are casting to -- you still have to cast to the boxed type (in order to unbox) and then take it from there. In the example, this means two consecutive casts: double dd = (double) (decimal) o; Or, using the Convert methods: double dd = Convert.ToDouble(o); Of course this won't do for your real use case because you cannot immediately go from a generic type parameter to ToDouble. But as long as the target type is IConvertible, you can do this: double dd = (double)Convert.ChangeType(o, typeof(double)); where the generic type parameter T can be substituted for double.
unknown
d18649
test
There is a extension for that. Simply search for "highlight-matching-tag" in the extension tab or download it here: https://marketplace.visualstudio.com/items?itemName=vincaslt.highlight-matching-tag I recommend to set a custom setting like this: "highlight-matching-tag.style": { "borderWidth": "1px", "borderColor": "orange", "borderStyle": "solid" }
unknown
d18651
test
Yes, you should download the images in the timeline provider and send the timeline when they are all done. Refer to the following recommendation by an Apple frameworks engineer. I use a dispatch group to achieve this. Something like: let imageRequestGroup = DispatchGroup() var images: [UIImage] = [] for imageUrl in imageUrls { imageRequestGroup.enter() yourAsyncUIImageProvider.getImage(fromUrl: imageUrl) { image in images.append(image) imageRequestGroup.leave() } } imageRequestGroup.notify(queue: .main) { completion(images) } I then use SwiftUI's Image(uiImage:) initializer to display the images A: I dont have a good solution, but I try to use WidgetCenter.shared.reloadAllTimelines(), and it make sence. In the following code. var downloadImage: UIImage? func downloadImage(url: URL) -> UIImage { var picImage: UIImage! if self.downloadImage == nil { picImage = UIImage(named: "Default Image") DispatchQueue.global(qos: .background).async { do { let data = try Data(contentsOf: url) DispatchQueue.main.async { self.downloadImage = UIImage.init(data: data) if self.downloadImage != nil { DispatchQueue.main.async { WidgetCenter.shared.reloadAllTimelines() } } } } catch { } } } else { picImage = self.downloadImage } return picImage } Also you have to consider when to delete this picture. This like tableView.reloadData().
unknown
d18653
test
x will receive the null value when the user cancels the prompt, so: var x=prompt("Please enter your name",""); if (x === null) { // User canceled } Live example A: It returns as if you had clicked cancel. It is null not as a string .. alert( prompt('') === null ); will alert true if you press Esc or cancel button
unknown
d18659
test
I was with you till you said you needed it to run in the main thread. I don't think it's possible the way you describe. The problem is that you're going to need at least two threads to perform the timing and the actual work, and neither of those can be the main thread because a timer won't use the main thread, and because you'll want the operation to terminate, which if it were the main thread would shut down the whole app. The way you would do this normally is to set up a wrapper class that is run from the main thread and sets up the background thread for the operation as well as the timer. Why, exactly, does the 3rd party library have to be invoked from the main thread? A: I knocked together a solution similar to the one linked to, except that I used Thread.Interrupt() instead of Thread.Abort(), thinking that would be a little kinder to the main thread. The problem is that Thread.Interrupt() won't interrupt a call that is blocked, so it is unsatisfactory under many cases. Thread.Abort() is a dangerous call and should be avoided where possible. Pick your poison. For what it's worth, this is my implementation: public static class AbortableProc { public static void Execute(Action action, Action timeoutAction, int milli) { Thread currThread = Thread.CurrentThread; object stoppedLock = new object(); bool stopped = false; bool interrupted = false; Thread timer = new Thread(() => { Thread.Sleep(milli); lock (stoppedLock) { if (!stopped) { currThread.Interrupt(); stopped = true; interrupted = true; } } }); timer.Start(); try { action(); lock (stoppedLock) { stopped = true; } } catch (ThreadInterruptedException) { } if (interrupted) { timeoutAction(); } } } For grins, I put in a timeoutAction so that you could use it in this mode: AbortableProc.Execute( () => { Process(kStarting); Process(kWorking); Process(kCleaningUp); }, () => { if (IsWorking()) CleanUp(); } };
unknown
d18661
test
You can use display: inline; inside of display: inline-block;. .header_class_name { display: inline; } .para_class_name { display: inline; word-break: break-word; } <h4 class="header_class_name">my title here</h4> <p class="para_class_name">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> A: edit - adding a solution based on your comment try using white-space: nowrap;, if that doesn't work, you can try setting the containing div size to a higher width. you can try doing several things: * *wrap both divs with <nobr> *make the parent div a flexbox with flex-direction: row; flex-wrap: nowrap; the problem with this solution is that they would 'leak' outside your viewport width, so I would consider allowing line break/making the font smaller/using elipsis A: You can use min-width property, so when window shrinks, layout should stay firm.
unknown
d18667
test
If you are allowed to modify your HTTP request, one way would be to add a ad-hoc HTTP header for the method name : public String getStuffFromUrl() { HttpHeaders headers = new HttpHeaders(); headers.add("JavaMethod", "getStuffFromUrl"); entity = new Entity(headers) ... return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody(); } You could then get back the method name and remove the header from within the ClientHttpRequestInterceptor prior the HTTP request is actualy sent out. ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { String javaMethodName="Unknown"; List<String> javaMethodHeader = request.getHeaders().remove("JavaMethod"); if(javaMethodHeader!=null && javaMethodHeader.size()>0) { javaMethodName = javaMethodHeader.get(0); } log.info("Calling method = "+ javaMethodName); execution.execute(request, body); } (provided code not tested)
unknown
d18673
test
Found a different solution, as I cound not find any way forward. Its a simple direct hot encoding. For this I enter for every word I need a new column into the dataframe and create the encoding directly. vocabulary = ["achtung", "suchen"] for word in vocabulary: df2[word] = 0 for index, row in df2.iterrows(): if word in row["title"].lower(): df2.set_value(index, word, 1)
unknown
d18677
test
Lalit explained the difference between picture size and preview size on camera. You can try this method to get the most optimal size related to the screen size of the device. private Camera.Size getOptimalSize(Camera.Parameters params, int w, int h) { final double ASPECT_TH = .2; // Threshold between camera supported ratio and screen ratio. double minDiff = Double.MAX_VALUE; // Threshold of difference between screen height and camera supported height. double targetRatio = 0; int targetHeight = h; double ratio; Camera.Size optimalSize = null; // check if the orientation is portrait or landscape to change aspect ratio. if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { targetRatio = (double) h / (double) w; } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { targetRatio = (double) w / (double) h; } // loop through all supported preview sizes to set best display ratio. for (Camera.Size s : params.getSupportedPreviewSizes()) { ratio = (double) s.width / (double) s.height; if (Math.abs(ratio - targetRatio) <= ASPECT_TH) { if (Math.abs(targetHeight - s.height) < minDiff) { optimalSize = s; minDiff = Math.abs(targetHeight - s.height); } } } return optimalSize; } A: Picture size This is the size of the image produced when you tell the camera to take a photo. If it is the same aspect ratio as the native resolution then it will be directly scaled from that. If the aspect ratio is different then it will be cropped from the native size. In my experience, the largest size returned by getSupportedPictureSizes is the native resolution of the camera. Preview size This is the size of the image preview that is shown on-screen. It may be a different aspect ratio than either the native size or the picture size, causing further cropping To get the closest match between what you see on screen and the image that is produced when you take a photo try to select a preview size with an aspect ratio as close as possible to the aspect ratio of the picture size that you've selected. I generally try to get both as close as possible to the native size. please also check this link
unknown
d18679
test
All problem were in wrong path to /tmp directory. Docs. Final code for Firebase functions: const fs = require('fs'); const s3 = require('../../services/storage'); const download = require('download'); const saveMediaItemToStorage = async (sourceId, item) => { // * creating file name const fileName = `${item.id}.${item.extension}`; // * saving file to /tmp folder await download(item.originalMediaUrl, '/tmp', { filename: fileName }); const blob = fs.readFileSync(`/tmp/${fileName}`); // * saving file to s3 await s3 .upload({ Bucket: 'name', Key: `content/${sourceId}/${fileName}`, Body: blob, ACL: 'public-read' }) .promise(); // * remove file from temp folder fs.unlink(`/tmp/${fileName}`, function (err) { if (err) return console.log(err); console.log('file deleted successfully'); }); }; module.exports = saveMediaItemToStorage;
unknown
d18681
test
Maybe because there is no param id. If you want to set venue location, use location_id. A: Try doing the same thing with the same parameters here: https://developers.facebook.com/tools/explorer and see what the error message is.
unknown
d18683
test
like this: Objective-C: UIBezierPath* polygonPath = UIBezierPath.bezierPath; [polygonPath moveToPoint: CGPointMake(80.5, 33)]; [polygonPath addLineToPoint: CGPointMake(119.9, 101.25)]; [polygonPath addLineToPoint: CGPointMake(41.1, 101.25)]; [polygonPath closePath]; [UIColor.grayColor setFill]; [polygonPath fill]; UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(58, 56, 45, 45)]; [UIColor.redColor setFill]; [ovalPath fill]; Swift: var polygonPath = UIBezierPath() polygonPath.moveToPoint(CGPointMake(80.5, 33)) polygonPath.addLineToPoint(CGPointMake(119.9, 101.25)) polygonPath.addLineToPoint(CGPointMake(41.1, 101.25)) polygonPath.closePath() UIColor.grayColor().setFill() polygonPath.fill() var ovalPath = UIBezierPath(ovalInRect: CGRectMake(58, 56, 45, 45)) UIColor.redColor().setFill() ovalPath.fill() Both produce this: or this: Objective-C: UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(40, 18, 91, 91)]; [UIColor.redColor setFill]; [ovalPath fill]; UIBezierPath* polygonPath = UIBezierPath.bezierPath; [polygonPath moveToPoint: CGPointMake(85.5, 18)]; [polygonPath addLineToPoint: CGPointMake(124.9, 86.25)]; [polygonPath addLineToPoint: CGPointMake(46.1, 86.25)]; [polygonPath closePath]; [UIColor.grayColor setFill]; [polygonPath fill]; Swift: var ovalPath = UIBezierPath(ovalInRect: CGRectMake(40, 18, 91, 91)) UIColor.redColor().setFill() ovalPath.fill() var polygonPath = UIBezierPath() polygonPath.moveToPoint(CGPointMake(85.5, 18)) polygonPath.addLineToPoint(CGPointMake(124.9, 86.25)) polygonPath.addLineToPoint(CGPointMake(46.1, 86.25)) polygonPath.closePath() UIColor.grayColor().setFill() polygonPath.fill() For this: And with a frame: Objective-C: CGContextRef context = UIGraphicsGetCurrentContext(); CGRect frame = CGRectMake(75, 28, 76, 66); CGContextSaveGState(context); CGContextBeginTransparencyLayer(context, NULL); CGContextClipToRect(context, frame); UIBezierPath* polygonPath = UIBezierPath.bezierPath; [polygonPath moveToPoint: CGPointMake(CGRectGetMinX(frame) + 1.48684 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.42424 * CGRectGetHeight(frame))]; [polygonPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 1.98823 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 1.42424 * CGRectGetHeight(frame))]; [polygonPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 0.98546 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 1.42424 * CGRectGetHeight(frame))]; [polygonPath closePath]; [UIColor.grayColor setFill]; [polygonPath fill]; UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame) + floor((CGRectGetWidth(frame) - 44) * 0.50000 + 0.5), CGRectGetMinY(frame) + floor((CGRectGetHeight(frame) - 44) * 1.00000 + 0.5), 44, 44)]; [UIColor.redColor setFill]; [ovalPath fill]; CGContextEndTransparencyLayer(context); CGContextRestoreGState(context); Swift: let context = UIGraphicsGetCurrentContext() let frame = CGRectMake(75, 28, 76, 66) CGContextSaveGState(context) CGContextBeginTransparencyLayer(context, nil) CGContextClipToRect(context, frame) var polygonPath = UIBezierPath() polygonPath.moveToPoint(CGPointMake(frame.minX + 1.48684 * frame.width, frame.minY + 0.42424 * frame.height)) polygonPath.addLineToPoint(CGPointMake(frame.minX + 1.98823 * frame.width, frame.minY + 1.42424 * frame.height)) polygonPath.addLineToPoint(CGPointMake(frame.minX + 0.98546 * frame.width, frame.minY + 1.42424 * frame.height)) polygonPath.closePath() UIColor.grayColor().setFill() polygonPath.fill() var ovalPath = UIBezierPath(ovalInRect: CGRectMake(frame.minX + floor((frame.width - 44) * 0.50000 + 0.5), frame.minY + floor((frame.height - 44) * 1.00000 + 0.5), 44, 44)) UIColor.redColor().setFill() ovalPath.fill() CGContextEndTransparencyLayer(context) CGContextRestoreGState(context) This obviously isn't going to draw a bunch of small circles in the triangle, but you've not specified how many circles need to be drawn and so it's impossible to help you further without this very important information, but this will give you a start. And for reference, here's where you'll need to visit, the following information is dealing with packing problems and math, specifically packing problems with fitting circls inside of triangles: https://en.wikipedia.org/wiki/Malfatti_circles http://hydra.nat.uni-magdeburg.de/packing/crt/crt.html#Download https://en.wikipedia.org/wiki/Circle_packing_in_an_equilateral_triangle and then this: Dense Packings of Equal Disks in an Equilateral Triangle R. L. Graham, B. D. Lubachevsky Previously published packings of equal disks in an equilateral triangle have dealt with up to 21 disks. We use a new discrete-event simulation algorithm to produce packings for up to 34 disks. For each n in the range 22≤n≤34 we present what we believe to be the densest possible packing of n equal disks in an equilateral triangle. For these n we also list the second, often the third and sometimes the fourth best packings among those that we found. In each case, the structure of the packing implies that the minimum distance d(n) between disk centers is the root of polynomial Pn with integer coefficients. In most cases we do not explicitly compute Pn but in all cases we do compute and report d(n) to 15 significant decimal digits. Disk packings in equilateral triangles differ from those in squares or circles in that for triangles there are an infinite number of values of n for which the exact value of d(n) is known, namely, when n is of the form Δ(k):=k(k+1)2. It has also been conjectured that d(n−1)=d(n) in this case. Based on our computations, we present conjectured optimal packings for seven other infinite classes of n, namely n=Δ(2k)+1,Δ(2k+1)+1,Δ(k+2)−2,Δ(2k+3)−3,Δ(3k+1)+2,4Δ(k), and 2Δ(k+1)+2Δ(k)−1. We also report the best packings we found for other values of n in these forms which are larger than 34, namely, n=37, 40, 42, 43, 46, 49, 56, 57, 60, 63, 67, 71, 79, 84, 92, 93, 106, 112, 121, and 254, and also for n=58, 95, 108, 175, 255, 256, 258, and 260. We say that an infinite class of packings of n disks, n=n(1),n(2),...n(k),..., is tight , if [1/d(n(k)+1)−1/d(n(k))] is bounded away from zero as k goes to infinity. We conjecture that some of our infinite classes are tight, others are not tight, and that there are infinitely many tight classes. http://www.combinatorics.org/ojs/index.php/eljc/article/view/v2i1a1 and this as well: Abstract This paper presents a computational method to find good, conjecturally optimal coverings of an equilateral triangle with up to 36 equal circles. The algorithm consists of two nested levels: on the inner level the uncovered area of the triangle is minimized by a local optimization routine while the radius of the circles is kept constant. The radius is adapted on the outer level to find a locally optimal covering. Good coverings are obtained by applying the algorithm repeatedly to random initial configurations. The structures of the coverings are determined and the coordinates of each circle are calculated with high precision using a mathematical model for an idealized physical structure consisting of tensioned bars and frictionless pin joints. Best found coverings of an equilateral triangle with up to 36 circles are displayed, 19 of which are either new or improve on earlier published coverings. http://projecteuclid.org/euclid.em/1045952348 and then finally, this: https://en.wikipedia.org/wiki/Malfatti_circles A: Thanks Larcerax. I need to draw 53 circles on the boundary of Triangle Like a Rosary. Each circle will be drawn at specific distance. Out of 53 circles , 5 would be bigger than others(3 on corners(vertices) and other 2 on middle of 2 sides). Triangle would stand like Cone.
unknown
d18689
test
You can use unicode() to convert a byte string from some encoding to Unicode, but unless you specifiy the encoding, Python assumes it's ASCII. SQLite does not use ASCII but UTF-8, so you have to tell Python about it: ...join(unicode(y, 'UTF-8') for y in ...)
unknown
d18691
test
I will have to initialize a new instance of the Financial Report Controller with Print Presenter as one of the instance variable? No. But you will have to pass the appropriate Print Presenter to the Financial Report Controller somehow. When you decide which one is appropriate doesn’t have to be on initialization. You could pass it later with a setter. Or you could pass a collection of them to choose from. Or, like you said, create a new instance of the controller. They all work. Use what makes sense for your situation.
unknown
d18693
test
The query doesn't exclude duplicates, there just isn't any duplicates to exclude. There is only one record with id 3 in the table, and that is included because there is a 3 in the in () set, but it's not included twice because the 3 exists twice in the set. To get duplicates you would have to create a table result that has duplicates, and join the table against that. For example: select t.Name from someTable t inner join ( select id = 3 union all select 4 union all select 5 union all select 3 union all select 7 union all select 8 union all select 9 ) x on x.id = t.id A: Try this: SELECT Name FROM Tbl JOIN ( SELECT 3 Id UNION ALL SELECT 4 Id UNION ALL SELECT 5 Id UNION ALL SELECT 3 Id UNION ALL SELECT 7 Id UNION ALL SELECT 8 Id UNION ALL SELECT 9 Id ) Tmp ON tbl.Id = Tmp.Id
unknown
d18695
test
It's easier to write parallel programs for 1000s of threads than it is for 10s of threads. GPUs have 1000s of threads, with hardware thread scheduling and load balancing. Although current GPUs are suited mainly for data parallel small kernels, they have tools that make doing such programming trivial. Cell has only a few, order of 10s, of processors in consumer configurations. (The Cell derivatives used in supercomputers cross the line, and have 100s of processors.) IMHO one of the biggest problems with Cell was lack of an instruction cache. (I argued this vociferously with the Cell architects on a plane back from the MICRO conference Barcelona in 2005. Although they disagreed with me, I have heard the same from bigsuper computer users of cell.) People can cope with fitting into fixed size data memories - GPUs have the same problem, although they complain. But fitting code into fixed size instruction memory is a pain. Add an IF statement, and performance may fall off a cliff because you have to start using overlays. It's a lot easier to control your data structures than it is to avoid having to add code to fix bugs late in the development cycle. GPUs originally had the same problems as cell - no caches, neither I nor D. But GPUs did more threads, data parallelism so much better than Cell, that they ate up that market. Leaving Cell only its locked in console customers, and codes that were more complicated than GPUs, but less complicated than CPU code. Squeezed in the middle. And, in the meantime, GPUs are adding I$ and D$. So they are becoming easier to program. A: Why did Cell die? 1) The SDK was horrid. I saw some very bright developers about scratch their eyes out pouring through IBM mailing lists trying to figure out this problem or that with the Cell SDK. 2) The bus between compute units was starting to show scaling problems and never would have made it to 32 cores. 3) OpenCl was about 3-4 years too late to be of any use. A: I'd say the reasons for the lack of popularity for cell development are closer to: * *The lack of success in the PS3 (due to many mistakes on Sony's part and strong competition from the XBOX 360) *Low manufacturing yield, high cost (partly due to low yield), and lack of affordable hardware systems other than the PS3 *Development difficulty (the cell is an unusual processor to design for and the tooling is lacking) *Failure to achieve significant performance differences compared to existing x86 based commodity hardware. Even the XBOX 360's several year old triple core Power architecture processor has proven competitive, compared to a modern Core2 Quad processor the cell's advantages just aren't evident. *Increasing competition from GPU general purpose computing platforms such as CUDA A: If you started two or three years ago to program the cell, will you continue on this or are you considering switching to GPU's? I would have thought that 90% of the people who program for the Cell processor are not in a position where they can arbitrarily decide to stop programming for it. Are you aiming this question at a very specific development community?
unknown
d18703
test
As a bare minimum this should work for zooming: mediaPlayer.video().setScale(float factor); Where factor is like 2.0 for double, 0.5 for half and so on. In my experience, it can be a bit glitchy, and you probably do need to use it in conjunction with crop - and by the way, cropping does work. But if you want an interactive zoom, then you build that yourself invoking setCrop and setScale depending on some UI interactions you control. For the picture-in-picture type of zoom, if you're using VLC itself you do something like this: vlc --video-filter=magnify --avcodec-hw=none your-filename.mp4 It shows a small overlay where you can drag a rectangle and change the zoom setting. In theory, that would have been possible to use in your vlcj application by passing arguments to the MediaPlayerFactory: List<String> vlcArgs = new ArrayList<String>(); vlcArgs.add("--avcodec-hw=none"); vlcArgs.add("--video-filter=magnify"); MediaPlayerFactory factory = new MediaPlayerFactory(args); The problem is that it seems like you need "--avcodec-hw=none" (to disable hardware decoding) for the magnify filter to work - BUT that option is not supported (and does not work) in a LibVLC application. So unfortunately you can't get that native "magnify" working with a vlcj application. A final point - you can actually enable the magnify filter if you use LibVLC's callback rendering API (in vlcj this is the CallbackMediaPlayer) as this does not use hardware decoding. However, what you would see is the video with the magnify overlays painted on top but they are not interactive and your clicks will have no effect. So in short, there's no satisfactory solution for this really. In theory you could build something yourself, but I suspect it would not be easy.
unknown
d18705
test
When using rotate3d(x, y, z, a) the first 3 numbers are coordinate that will define the vector of the rotation and a is the angle of rotation. They are not multiplier of the rotation. rotate3d(1, 0, 0, 90deg) is the same as rotate3d(0.25, 0, 0, 90deg) and also the same as rotate3d(X, 0, 0, 90deg) because we will have the same vector in all the cases. Which is also the same as rotateX(90deg) .box { margin:30px; padding:20px; background:red; display:inline-block; } <div class="box" style="transform:rotate3d(1,0,0,60deg)"></div> <div class="box" style="transform:rotate3d(99,0,0,60deg)"></div> <div class="box" style="transform:rotate3d(0.25,0,0,60deg)"></div> <div class="box" style="transform:rotate3d(100,0,0,60deg)"></div> <div class="box" style="transform:rotate3d(-5,0,0,60deg)"></div> <div class="box" style="transform:rotateX(60deg)"></div> From this we can also conclude that rotate3d(0, Y, 0, a) is the same as rotateY(a) and rotate3d(0, 0, Y, a) the same as rotate(a). Note the use of 0 in two of the coordinates which will make our vector always in the same axis (X or Y or Z) rotate3d(1,1,0, 45deg) is not the same as rotateX(45deg) rotateY(45deg). The first one will perform one rotation around the vector defined by (1,1,0) and the second one will perform two consecutive rotation around the X and Y axis. In other words, rotate3d() is not a combination of the other rotation but a rotation on its own. The other rotation are particular cases of rotate3d() considering predefined axis. The multiplier trick apply to the coordinate if you keep the same angle. rotate3d(x, y, z, a) is equivalent to rotate3d(p*x, p*y, p*z, a) because if you multiply all the coordinates with the same value, you keep the same vector direction and you change only the vector dimension which is irrelevant when defining the rotation. Only the direction is relevant. More details here: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d You can clearly notice that using values in the range of [-1,1] for x,y,z is enough to define all the combination. In the other hand, any combination of x,y,z can be reduced to values inside the range [-1,1] Examples: .box { margin:30px; padding:20px; background:red; display:inline-block; } <div class="box" style="transform:rotate3d(10,5,-9,60deg)"></div> <div class="box" style="transform:rotate3d(1,0.5,-0.9,60deg)"></div> <div class="box" style="transform:rotate3d(25,-5,-8,60deg)"></div> <div class="box" style="transform:rotate3d(1,-0.2,-0.32,60deg)"></div> We simply divide by the biggest number.
unknown
d18711
test
If you use MVC it is recommended to encapsulate the setter (private). This because MVC discribes that your view does NOT change the model but the controller should do this. You can use ${model.property = 100}, which requires public setter Allthough in the MVC it is recommended to private the setter
unknown
d18713
test
You could for example use Handbreak to encode the video in a smaller format. I'd suggest to use H.264 (x264) as it can produce good quality at low bitrates (to the quality/size ratio is good) and is widely supported. If you're completely unexperienced with this you'll probably need to try around a bit with the options, but Handbreak makes it fairly easy. However, remember the smaller the file the worse the quality in the end. Also it's better if you have good quality in the source material as the compression can usually work more efficiently. A: I'm going to say no. Your limited by the server's net connection and your own Also, a fast internet connection can have different meaning to different people. I have 50mb broadband but someone else might consider 8mb as fast. Plus remember, you uprate is usually around 10x slower than your down rate on your connection. Sometimes more, sometimes less. The alternative to waiting is to transcode your video to a smaller size before uploading
unknown
d18715
test
The model configuration is accessible through an attribute called "model_config" on the top group that seems to contain the full model configuration JSON that is produced by model.to_json(). import json import h5py model_info = h5py.File('model.h5', 'r') model_config_json = json.loads(model_info.attrs['model_config']) A: If you save the full model with model.save, you can access each layer and it's activation function. from tensorflow.keras.models import load_model model = load_model('model.h5') for l in model.layers: try: print(l.activation) except: # some layers don't have any activation pass <function tanh at 0x7fa513b4a8c8> <function softmax at 0x7fa513b4a510> Here, for example, softmax is used in the last layer. If you don't want to import tensorflow, you can also read from h5py. import h5py import json model_info = h5py.File('model.h5', 'r') model_config = json.loads(model_info.attrs.get('model_config').decode('utf-8')) for k in model_config['config']['layers']: if 'activation' in k['config']: print(f"{k['class_name']}: {k['config']['activation']}") LSTM: tanh Dense: softmax Here, last layer is a dense layer which has softmax activation.
unknown
d18717
test
your xpath wrong syntax, just get rid of the "." and you'll get all the div elements with attribute class="record" '//div[@id="records"]//div[@class="record"]' if (as you said in the comments) you want to get all anchor elements then try this xpath: '//div[@id="records"]/div[@class="record"]/a[contains(@href,"firma")]'
unknown
d18719
test
This is a known issue with this named parameter https://github.com/dart-lang/sdk/issues/24637 A: The solution is to use postFormData() instead of send(). For example: final req = await HttpRequest .postFormData(url, {'action': 'delete', 'id': id}); return req.responseText; A: Future<String> deleteItem(String id) async { final req = new HttpRequest() ..open('POST', 'server/controller.php') ..send({'action': 'delete', 'id': id}); // wait until the request have been completed await req.onLoadEnd.first; // oh yes return req.responseText; } this one is the point, where sometimes you need "PUT" or "DELETE"
unknown
d18721
test
If you are using phonegap than for sure you can work with file system. Solution is to encode your array into JSON using serializeArray() method in JQuery. Once you encode your array you will get JSON string which you have to store in a file using PhoneGap's Filewriter() function. For more detail on that visit this link. I hope it helped you :-). A: JavaScript cannot tamper with the file system directly. You can do one of two things: * *Save the changes onto a cookie and read it the next time *Send the changes (via AJAX) to a PHP file which would generate a downloadable file on the server, and serve it to the client. There are probably more solutions, but these are the most reasonable two I can think of. A: Phonegap (at http://phonegap.com/tools/) is suggesting Lawnchair: http://westcoastlogic.com/lawnchair/ so you'd read that file into data.js instead of storing the data literally there A: You could also save your array (or better yet its members) using localStorage, a key/value storage that stores your data locally, even when the user quits your app. Check out the guide in the Safari Developer Library. A: use Lawnchair to save the array as a JSON object. The JSON object will be there in the memory till you clear the data for the application. If you want to save it permanently to a file on the local filesystem then i guess you can write a phonegap plugin to sent the data across to the native code of plugin which will create/open a file and save it.
unknown
d18723
test
You have to use union types: export type Objs = Array<Obj | string>; A: If the entries in the array can be either strings or objects in the form {id: string; labels: string[]}, you can use a union type: export type Obj = string | {id: string; labels: string[]}; const array: Obj[] = [ "", {id: "", labels: [""]} ]; Playground Example
unknown
d18725
test
I think this code, would produce a similar output to what you're looking for, but without the loop you wanted to create, because I'm sure that would require a fair few if statements. I was curious as what this line was doing currentTime because it doesn't look to me like it would do anything at all. #include <iostream> #include <conio.h> using namespace std; int main() { int hr, min; char period; cout << "Enter Hour" << endl; cin >> hr; cout << "Enter Minute" << endl; cin >> min; min++; cout << "Enter Period (A or P)" << endl; cin >> period; cout << "Current Time: " << hr << ":" << min << " " << period << "M" << endl; _getch(); } A: Here is an idea of how to accomplish this in C#. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication { class Program { static void Main(string[] args) { double hrs=0; double mins=0; DateTime dt = new DateTime(2013, 10, 20, 3, 59, 00); //dt = DateTime.Now; Console.WriteLine(dt.ToShortTimeString()); Console.WriteLine("Enter hours:"); hrs = Convert.ToDouble(Console.ReadLine()); dt = dt.AddHours(hrs); Console.WriteLine("Enter minutes:"); mins = Convert.ToDouble(Console.ReadLine()); dt = dt.AddMinutes(mins); if (dt.Minute == 59) dt = dt.AddMinutes(1); Console.WriteLine(dt.ToShortTimeString()); Console.ReadLine(); } } }
unknown
d18727
test
rangeSeries.columns.template.propertyFields.fill = "colour"; rangeSeries.columns.template.propertyFields.stroke = "colour";
unknown
d18729
test
Add a wrapper around your code: document.addEventListener("DOMContentLoaded", function(event) { // scroll reveal const ScrollReveal = require('scrollreveal'); // scroll reveal profile listings if (!/(?:^|\s)ie\-[6-9](?:$|\s)/.test(document.body.className)) { window.sr = new ScrollReveal({reset: false}); sr.reveal('[data-reveal="true"]', {duration: 1000}); } });
unknown
d18735
test
After learning TCPDF more, this is the conclusion: Cell() and MultiCell() are not intended to be used for just outputting a string and fitting it's length. Instead, Write() and WriteHtml() should be used. Cells exist for the case where you actually want to control the dimentions of the field manually. Nevertheless, in some cases one may want to compute the width of the cell, such that it takes into account the sizes of the text inside. For this purpose exists GetStringWidth(). (Unfortunately for me it err's from time to time. Maybe I'm not aware of something) A: Have an internal "Legacy" application that uses TCPDF to generate a PDF of a checklist. We recently moved from creating a giant string of HTML that described a table, created using the $pdf->writeHTML($myHTMLString); method, to using the MultiCell() methods. However, we ran into an issue where some text in a description cell would need to run on to a second line, this threw off our layout. As a fix, we created an if block based on 2 variables, one for the string width the other for the actual cell width. (We had 2 instances where the cell width might vary). If block example: // Get width of string $lWidth = $pdf->GetStringWidth(strip_tags($clItem['description'])); // Determine width of cell $oadWidth = (.01*$width[0])*186; if ($lWidth < $oadWidth) { $cHeight = 3.5; } else { $cHeight = 7; } We then used the variable created by the if block in the MultiCell() like this $pdf->MultiCell((.01*$width[0])*186, $cHeight, strip_tags($clItem['description']), 1, 'L', 1, 0, '', '', true); We reused the $cHeight variable for the height params in the other sibling cells so each row of cells had a uniform height. You could most likely reuse this method with any of the other right functions that have a height parameter in TCPDF. Thanks to @shealtiel for the original reference to GetStringWidth()
unknown
d18737
test
You should use a bootstrap action to change Hadoop configuration. The following AWS doc can be referenced for Hadoop configuratio bootstrap action. http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/emr-plan-bootstrap.html#PredefinedbootstrapActions_ConfigureHadoop This blog article that I bookmarked also has some info. http://sujee.net/tech/articles/hadoop/amazon-emr-beyond-basics/ For changing the cluster size dynamically, one option is to use the AWS SDK. http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/calling-emr-with-java-sdk.html Using the following interface you can modify the instance count of the instance group. http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/elasticmapreduce/AmazonElasticMapReduce.html
unknown
d18739
test
Currently, the purge API is the recommended way to invalidate cached content on-demand. Another approach for your scenario could be to look at Workers and Workers KV, and combine it with the Cloudflare API. You could have: * *A Worker reading the JSON from the KV and returning it to the user. *When you have a new version of the JSON, you could use the API to create/update the JSON stored in the KV. This setup could be significantly performant, since the Worker code in (1) runs on each Cloudflare datacenter and returns quickly to the users. It is also important to note that KV is "eventually consistent" storage, so feasibility depends on your specific application.
unknown
d18747
test
No need to use input mask .. use textbox and use format() function when store the text Dim MyStr as String = format(val(txtNumber.Text),"000000000000")
unknown
d18751
test
Perhaps try: $_SESSION['user'] = $row['username']; header("Location: ../php/home.php"); die(); You usually need to issue a die() command after the header() statement.
unknown
d18755
test
It seems as if the active network info will stay on the state of when the Context of the Service/Activity/Receiver is started. Hence if you start it on a network, and then later disconnect from that (i.e. moves from 3G to Wifi and disconnect the 3G connection) it will stay on the first active connection making the app believe the phone is offline even though it is not. It seems to me that the best solution is to user getApplicationContext instead as that will not be tied to when you started the particular "task". Update: Related is that if you run applications on Androids (in particular Nexus One) for a long period of time when connected to Wifi do check that you make sure you do not let the Wifi sleep when the screen sleeps. You will be able to set that at the Advanced option under Wireless Networks.
unknown