_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d9701
train
It has been said multiple times here, but just to reiterate - Spark is not Hive interface and is not designed for full Hive compatibility in terms of language (Spark targets SQL standard, Hive uses custom SQL-like query language) or capabilities (Spark is ETL solution, Hive is a Data Warehousing solution). Even data layouts are not fully compatible between these two. Spark with Hive support is Spark with access to Hive metastore, not Spark that behaves like Hive. If you need to access full set of Hive's features connect to Hive directly with native client or native (not Spark) JDBC connection, and use interact with it from there.
unknown
d9702
train
Enter-PSSession -hostname $hostname -username pshell -ScriptBlock{c:\Users\pshell\Anaconda3\python.exe script.py}; and get the output back to machine A. However, I don't know find the commands to copy script.py from machine A to machine B. I think it's a relatively easy task but I can't find the relevant commands. Any indications/suggestions not including third-party software/packages are welcome. A: From Is there a SCP alternative for PowerShell?: the little tool pscp.py, which comes with Putty can solve your task 1. For an example with PowerShell see this answer. A: Copy-Item -Path "ENTER_PATH HERE" -Destination "ENTER_PATH_HERE" -Recurse
unknown
d9703
train
You can print in another system, something like this: <?php $property = simple_fields_values("pillow_front"); foreach ($property as $value) { ?> <div class='solo'> <div class='box coussin'> <div class='outImg'><img src="<?php print wp_get_attachment_url($value);?>"/></div> </div> </div> <?php } ?> Please note that i put the echo of the function only because i do not know how it works, it can be not necessary, use php only when needed. A: Or just a bit more MVC-Pattern or in that case just MV? ;) Try this one without Wordpress. <?php //Init $property = simple_fields_values("pillow_front"); $template = '<div class="solo"> <div class="box coussin"> <div class="outImg"><img src="{MARKER:FRONT}" /></div> </div> </div>'; foreach ($property as $value) { echo str_replace(array('{MARKER:FRONT}'), array($value), $template); } ?> And as i know wordpress view, your code style is not confirm to WP-Styleguide. WP is using HTML/PHP Templating. In WP you view need to look like this. <?php foreach(simple_fields_values("pillow_front") as $value): ?> <div class='solo'> <div class='box coussin'> <div class='outImg'><img src="<?php echo htmlentities(value): ?>"/></div> </div> </div> <?php endforeach; ?>
unknown
d9704
train
Google has a huge userbase. They want to be reachable via multiple addresses, as that provides robust connections and some load balancing too. The technique is called DNS Round Robin. In case one of the multiple IP addresses doesn't work, most modern browsers will automatically try and use other addresses. If you would like to test a connection to particular IP, you could do a name lookup and pick one of the results. Like so, # Get a list of all Google IPs $googles = [Net.Dns]::GetHostAddresses("www.google.com") # Use IP address for the 1st entry test-connection $googles[0].IPAddressToString
unknown
d9705
train
Each stage materializes in some value, this is what gives you the ability to obtain a mechanism to push elements into the stream via a SourceQueueWithComplete when you use a Source.queue. Even a Flow could materialize in some value but this isn't common, in this cases you'll see that the materialized value is NotUsed.
unknown
d9706
train
The following will work in PHP >= 5.3, but you will still receive a Notice Error because propertyOne is not defined. <?php $somevar = array( 'propertyTwo' => false, 'propertyThree' => "hello!" ); $test = $somevar['propertyOne'] ?: $somevar['propertyTwo'] ?: $somevar['propertyThree']; echo $test; //displays 'hello!' You could however work around this by supressing the variables, but it is highly unrecommended: $test = @$somevar['propertyOne'] ?: @$somevar['propertyTwo'] ?: @$somevar['propertyThree']; A: This doesn't work in PHP, and here's why: $somevar['propertyOne'] = false; $somevar['propertyTwo'] = true; $test = $somevar['propertyOne'] || $somevar['propertyTwo']; Imagine typing that query into an if statement: if( $somevar['propertyOne'] || $somevar['propertyTwo'] ){ ... } This will return true (evaluates to 1) if either variable is true. Now, if we make all of the variables = false: $somevar['propertyOne'] = false; $somevar['propertyTwo'] = false; $test = $somevar['propertyOne'] || $somevar['propertyTwo']; The variable returns false (evaluates to 0). Another thing we can do is: $somevar['propertyOne'] = true; $somevar['propertyTwo'] = true; $test = $somevar['propertyOne'] && $somevar['propertyTwo']; This will return true (evaluates to 1) as both variables meet the criteria. This means that we can do things like this in PHP though: $test = $somevar['propertyOne'] || $somevar['propertyTwo']; if($test){ ... } TL,DR: In PHP you are storing the result of the expression into a variable, not doing any validation on anything.
unknown
d9707
train
You are looking for get_template_directory()
unknown
d9708
train
Works for me. The NETLINK_NETFILTER protocol is registered by the nfnetlink module. In my case, the kernel registers the module automatically since this code uses it, but if yours doesn't, try inserting it manually: $ sudo modprobe nfnetlink And then try opening the socket again.
unknown
d9709
train
Assuming that you have a running Hazelcast cluster, what you want to achieve can be done with Spring Boot by following the next steps: 1. Add the dependency camel-hazelcast-starter to your project With maven, you would add the next dependency <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-hazelcast-starter</artifactId> </dependency> 2. Create your specific HazelcastInstance In the example below, it creates a bean called customHazelcastConfig of type HazelcastInstance built from the client configuration file custom-client-hazelcast-config.xml that has been added to the root of the classpath. @Component public class HazelcastConfigProvider { @Bean public HazelcastInstance customHazelcastConfig() { return HazelcastClient.newHazelcastClient( new ClientClasspathXmlConfig("custom-client-hazelcast-config.xml") ); } } 3. Specify your HazelcastInstance to your Camel endpoint In the example below, we indicate camel-hazelcast to retrieve the HazelcastInstance from the registry using customHazelcastConfig as name corresponding to our specific instance created in step #2. fromF( "hazelcast-%sfoo?queueConsumerMode=Poll&hazelcastInstance=#customHazelcastConfig", HazelcastConstants.QUEUE_PREFIX ).log("Receiving: ${body}"); 4. Switch in client mode (Optional) By default the component camel-hazelcast is in node mode or cluster mode. To switch in client mode simply add camel.component.hazelcast-queue.hazelcast-mode=client to your application.properties This step is optional and could be skipped More details can be found from https://camel.apache.org/components/next/hazelcast-queue-component.html
unknown
d9710
train
You can change the directory that it initially starts in with a shortcut. If that is not enough, I don't believe what you want is possible without injecting a custom dll into the process after the fact. A: Why do you want to change the working directory? Maybe you could modify the PATH environment variable in some way to change the order of directories your app searches for files.
unknown
d9711
train
Try to use this regex for hostname (without protocol and trailing slash): ishank-juneja\.github\.io
unknown
d9712
train
I think you can do it like this: SELECT ca.id, ca.activity_date, cat.contact_id as cid FROM activity ca JOIN activity_target cat ON ca.id = cat.activity_id WHERE ca.activity_type_id = 44 and ca.id = (SELECT id from activity a join activity_target t on a.id = t.activity_id WHERE t.contact_id = cat.contact_id ORDER BY activity_date DESC LIMIT 1) ORDER BY activity_date DESC I can't say for sure without looking at your schema, and I'm guessing a bit with the differences between MySQL and Microsoft SQL Server. A: SELECT ca.id, ca.activity_date, cat.contact_id AS cid FROM activity ca JOIN activity_target cat ON ca.id = cat.activity_id JOIN ( SELECT t.contact_id , MAX(a.activity_date) AS activity_date FROM activity a JOIN activity_target t ON a.id = t.activity_id WHERE a.activity_type_id = 44 GROUP BY t.contact_id ) AS grp ON grp.contact_id = cat.contact_id AND grp.activity_date = ca.activity_date WHERE ca.activity_type_id = 44 ORDER BY ca.activity_date DESC
unknown
d9713
train
You'll want to get familiar with the "man (manual) pages": $ man ls In this case you'll see: -l (The lowercase letter ``ell''.) List in long format. (See below.) If the output is to a terminal, a total sum for all the file sizes is output on a line before the long listing. -t Sort by time modified (most recently modified first) before sorting the operands by lexicographical order. Another way you can see the effect of the options is to run ls without piping to the wc command. Compare $ ls with $ ls -l and $ ls -lt
unknown
d9714
train
Your interpretation of how the bindings expand is correct. The function essentially operates by converting a finite sorted list on demand into a binary search tree. I could rewrite portions of the function just to show that tree structure (note that the where portion is unchanged): data Tree a = Node (Tree a) a (Tree a) | Empty deriving Show tree [] = Empty tree xs = Node (tree ys1) y (tree ys2) where ys1 = take l xs (y:ys2) = drop l xs l = length xs `div` 2 The tree form can then be produced: *Main> tree [1..4] Node (Node (Node Empty 1 Empty) 2 Empty) 3 (Node Empty 4 Empty) The recursive upper section is about traversing only the relevant portion of the tree. bsearchT Empty _ = False bsearchT (Node ys1 y ys2) x = if x < y then bsearchT ys1 x else if x > y then bsearchT ys2 x else True bsearch xs x = bsearchT (tree xs) x The operation itself does suggest that a plain list is not the appropriate data type; we can observe that Data.List.Ordered.member performs a linear search, because lists must be traversed from the head and may be infinite. Arrays or vectors provide random access, so there is indeed a Data.Vector.Algorithms.Search.binarySearch.
unknown
d9715
train
Below is what you could use, if javsscript/jquery is an option: <ul id="cssdropdown"> <li class="headLink">Home <ul> <li><a href="#">Home1</a></li> <li><a href="#">Home4</a></li> <li><a href="#">Home2</a></li> <li><a href="#">Home3</a></li> <li><a href="#">Home5</a></li> </ul> </li> <li class="headLink">About <ul> <li><a href="#">About1</a></li> <li><a href="#">About2</a></li> <li><a href="#">About</a></li> <li><a href="#">About3</a></li> <li><a href="#">About5</a></li> </ul> </li> <li class="headLink">Contact <ul> <li><a href="#">Contact1</a></li> <li><a href="#">Contact2</a></li> <li><a href="#">Contact3</a></li> <li><a href="#">Contact4</a></li> <li><a href="#">Contact5</a></li> </ul> </li> <li class="headLink">Links <ul> <li><a href="#">Links1</a></li> <li><a href="#">Links2</a></li> <li><a href="#">Links3</a></li> <li><a href="#">Links4</a></li> <li><a href="#">Links5</a></li> </ul> </li> </ul> CSS body{ padding:0px; margin:0px; } ul li{ list-style-type:none; } #cssdropdown{ padding:0px; margin:0px; } a{ text-decoration:none; padding:0px; margin:0px;} .headLink{ display: inline-block; padding:10px; margin:10px; text-align:right; background-color:#999999; cursor:pointer; } .headLink ul{ display:none; position: absolute; margin:10px 0 0 -13px; padding:0 10px; text-align:left; background-color:#CCC; cursor:pointer; } JS: $(function() { $(".headLink").hover(function() { $('ul',this).slideToggle(); }); }); DEMO
unknown
d9716
train
As @RonakShah suggested, the most efficient way in this case may be this: split(iv2, cut(iv2, breaks = iv1,labels = paste0('ov',1:4))) Output: $ov1 [1] 120 140 160 180 $ov2 [1] 230 250 255 265 270 295 $ov3 [1] 340 355 $ov4 [1] 401 422 424 430
unknown
d9717
train
That depends on your cache implementation - not on Spring, which only provides an abstract caching API. You are using EhCache as your caching implementation, which comes with a Terracotta server for basic clustering support and is open source. See http://www.ehcache.org/documentation/3.1/clustered-cache.html#clustering-concepts for more details
unknown
d9718
train
You call styleBox without setting this reference, you need to do styleBox.apply(this) $("#invite-emails").keypress(function(e){ if(e.which == 32) { styleBox.apply(this); } }); Than inside styleBox this will be showing to #invite-emails
unknown
d9719
train
You can use the link and perform groupby operation: * *https://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html
unknown
d9720
train
you can try this for deleting the rows from the table : WITH RECURSIVE cancel_list (id, total_cancel, sum_cancel, index_to_cancel) AS ( SELECT p.id, abs(p.amount), 0, array[p.index] FROM payment_table AS p WHERE p.amount < 0 AND p.id = id_to_check_and_cancel -- this condition can be suppressed in order to go through the full table payment UNION ALL SELECT DISTINCT ON (l.id) l.id, l.total_cancel, l.sum_cancel + p.amount, l.index_to_cancel || p.index FROM cancel_list AS l INNER JOIN payment_table AS p ON p.id = l.id WHERE l.sum_cancel + p.amount <= l.total_cancel AND NOT l.index_to_cancel @> array[p.index] -- this condition is to avoid loops ) DELETE FROM payment_table AS p USING (SELECT DISTINCT ON (c.id) c.id, unnest(c.index_to_cancel) AS index_to_cancel FROM cancel_list AS c ORDER BY c.id, array_length(c.index_to_cancel, 1) DESC ) AS c WHERE p.index = c.index_to_cancel; you can try this for just querying the table without the hidden rows : WITH RECURSIVE cancel_list (id, total_cancel, sum_cancel, index_to_cancel) AS ( SELECT p.id, abs(p.amount), 0, array[p.index] FROM payment_table AS p WHERE p.amount < 0 AND p.id = id_to_check_and_cancel -- this condition can be suppressed in order to go through the full table payment UNION ALL SELECT DISTINCT ON (l.id) l.id, l.total_cancel, l.sum_cancel + p.amount, l.index_to_cancel || p.index FROM cancel_list AS l INNER JOIN payment_table AS p ON p.id = l.id WHERE l.sum_cancel + p.amount <= l.total_cancel AND NOT l.index_to_cancel @> array[p.index] -- this condition is to avoid loops ) SELECT * FROM payment_table AS p LEFT JOIN (SELECT DISTINCT ON (c.id) c.id, c.index_to_cancel FROM cancel_list AS c ORDER BY c.id, array_length(c.index_to_cancel, 1) DESC ) AS c ON c.index_to_cancel @> array[p.index] WHERE c.index_to_cancel IS NULL ;
unknown
d9721
train
this symptom will happen when any given player (not specific to Exo) cannot resolve from the source media either/or the input's sample-rate or bit-depth - If you start with one song using known values, say sample-rate 44100 Hertz and a bit-depth of 16 bits which are typical audio defaults, play this then convert it into permutations, say bit-depth of 8 bits to see if this makes a difference
unknown
d9722
train
You have to specify the 'html' in flask to access it, however, if you open the html file in browser this will still work since its action is aimed directly at your flask server. the code of your main.py says that if the in the form sent the data 'uname' and 'pass' are respectively 'ayush' and 'google', the code sends back to the browser a text indicating: "Welcome ayush" If you want to directly implement the html in your flask web server, you have to create the function and put your html code in templates folder. from flask import render_template ... @app.route('/', methods=['GET']) def code(): return render_template('index.html', name='') So you can access with http://localhost:5000/ now
unknown
d9723
train
...I would suggest setting the line-height the same as the font-size and playing with the link's padding to get the same result. I am certain that this is causing the issue.
unknown
d9724
train
How to set Browser language and/or Accept-Language header exports.config = { capabilities: { browserName: 'chrome', chromeOptions: { // How to set browser language (menus & so on) args: [ 'lang=fr-FR' ], // How to set Accept-Language header prefs: { intl: { accept_languages: "fr-FR" }, }, }, }, }; More examples: intl: { accept_languages: "es-AR" } intl: { accept_languages: "de-DE,de" } A: As it turns out - the answer was in the docs all along. This is how you do it for chrome and i guess it similar for other browsers: inside the protractor.conf.js (for Spanish): capabilities: { browserName: 'chrome', version: '', platform: 'ANY', 'chromeOptions': { 'args': ['lang=es-ES']} }
unknown
d9725
train
If you are using strings as your primary keys you'll probably have to do something like this: public class EntityMap : ClassMap<Entity> { public EntityMap() { Id(x => x.Name).GeneratedBy.Assigned(); Map(x => x.TimeStamp); } } From the nhibernate documentation: 5.1.4.7. Assigned Identifiers If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision). Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession. Also here is a related article. It is a bit dated but still applies to your situation: http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/6c9620b7c5bb7ca8
unknown
d9726
train
Check whether your questions object is in scope. angular.module("test", []) .controller('ctr1', function($scope) { $scope.save = function(ques){ $scope.showAnswer=true; } $scope.ques = { "q1": { "qText": " question1", "result": "", "options": { "A": "option1", "N": "option2", "D": "otpion3", "NA": "option4" } }, "q2": { "qText": " question2", "result": "", "options": { "A": "option1", "N": "option2", "D": "otpion3", "NA": "option4" } }, "q3": { "qText": " question3", "result": "", "options": { "A": "option1", "N": "option2", "D": "otpion3", "NA": "option4" } } } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script> <div ng-app="test" ng-controller="ctr1"> <form name="testForm"> <ul> <li ng-repeat="q in ques"> {{q.qText}} <input type="radio" ng-model="q.result" ng-value="q.options.A" /><label>{{q.options.A}}</label> <input type="radio" ng-model="q.result" ng-value="q.options.N" /><label>{{q.options.N}}</label> <input type="radio" ng-model="q.result" ng-value="q.options.D" /><label>{{q.options.D}}</label> </li> </ul> <input type="submit" ng-click="save(ques)" value="Submit" /> </form> <div ng-if="showAnswer"> <ul> <li ng-repeat="q in ques"> {{q.qText}}== {{q.result}} </li> </ul> </div> </div> A: Your json does not contain an array, but an object with other objects. Therefore you must let angular know to iterate through its keys: <div ng-repeat="(key, question) in questions track by $index"> <!-- .. --> </div> A: I see what you are trying to do! Your model says : `"questions": { "q1": {...} }, "q2": {...}, ... }` so, questions should be an Array for ng-repeat to work with it! Just a guess, I don't think you will need "q1", "q2" tags at all.. Modify your "questions" model to this: `"questions": [ { "qText": " question1", "result":"result1", "options":{ "A":"option1", "N":"option2", "D":"otpion3", "NA":"option4" } }, {...}, {...}, {...} ]` Remember: ng-repeat is well suited for Collections, and is not meant for Objects. Hope this serves your purpose!
unknown
d9727
train
Drop the last char class_id[LENGTH]; that you print as it was never initialized. Then switch your printf() to use the actual target of the strcpy. strncpy(new_node->class_id, data[i].c_name, LENGTH); printf("%.*s\n", LENGTH, new_node->class_id); I've also put a few LENGTH limits in my code to assure you don't do bad things on bad input without a terminal \0. Never blindly trust your C input unless you generated it in a fail-safe manner. Disclaimer: desktop inspection changes. Actual debugging is left as an exercise to the student.
unknown
d9728
train
Assuming your date is always in that format, you can use a more general regular expression to replace the date: my $string = 'startDate="2014-06-10"'; $string =~ s/startDate="\d{4}-\d{1,2}-\d{1,2}"/startDate=""/g; and since startDate="" stays the same you really just need to replace the date itself: my $string = 'startDate="2014-06-10"'; $string =~ s/\d{4}-\d{1,2}-\d{1,2}//g; A: Assuming perl >5.10: s/startDate="\K[^"]{10}//g; Replaces 10 characters which aren't " following startDate=". Using \K means you don't need to replace the bit you wanted to retain: \K , which causes the regex engine to "keep" everything it had matched prior to the \K and not include it in $&
unknown
d9729
train
Which tool are you using to parse the result of the split (or the grep)? xmllint (from libxml2) complains, but xmlwf (from expat) doesn't. So I think any expat-based tool would be ok with the XML, but not libxml2-based ones. It looks like xml_split and xml_grep could declare the namespaces though. At least it should be an option. I'll have a look at it. In the meantime, here is a quick'n dirty way to post-process the result you get with xml_grep: xml_grep --root 'SubInformation' --cond 'SubInformationName[string()="Blah"]' Infile.xml | perl -MXML::Twig -e'XML::Twig->new( start_tag_handlers => { xml_grep => sub { $_->set_att( "xmlns:m" => "http://m.org") }, SubInformation => sub { $_->flush } })->parse( \*STDIN)' > Outfile.xml replace xmlns:m and "http://m.org" with the appropriate values. Let me think of a way to do this in a generic way for the result of xml_split. Can I assume that the namespace declarations are not too tricky (ie that the prefix(es) are declared just once)? Edit: Here is a way to add the namespace declarations to the files resulting from xml_split, call it as add_ns Infile after you have run xml_split on Infile.xml: #!/usr/bin/perl use strict; use warnings; use XML::Twig; my $root= shift @ARGV; my( $base, @files)= sort glob( "$root-*.xml"); my %ns= ns_for_file( $base); foreach my $file (@files) { add_ns( $file, %ns); } sub ns_for_file { my( $base)= @_; my %ns; XML::Twig->new( start_tag_handlers # get namespace declarations from the root and bail => { 'level(0)' => sub { %ns= ns_for_tag( $_); $_[0]->finish_now(); } }, ) ->parsefile( $base); return %ns; } # get all namespace declarations from the root element sub ns_for_tag { my( $e)= @_; return map { $_ => $e->att( $_) if m{^xmlns:} } $e->att_names; } sub add_ns { my( $file, %ns)= @_; XML::Twig->new( start_tag_handlers => { 'level(0)' => sub { $_->set_att( %ns); } }, twig_handlers => { _all_ => sub { $_->flush; } }, keep_spaces => 1, ) ->parsefile_inplace( $file); } A: To process large XML files, you can also use a pull parser. See XML::LibXML::Reader.
unknown
d9730
train
Would you need an explicit conversion to array when import-csv is giving you a nice enumerable array of System.Object instances? When you use import-csv , PowerShell will read the header row and give you back an array of custom objects. Each of these objects will have properties which match the Header column. Example of test.csv Id,FirstName 1,Name001 2,Name002 Results after import-csv You can iterate through the collection as shown below $csv = Import-CSV "test.csv" foreach($item in $csv) { $msg=("Id={0} , Name={1}" -f $item.Id, $item.FirstName) Write-Host $msg } #Add the first item to your own array $arrMy=@() $arrMy+=$csv[0] $arrMy Output Id=1 , Name=Name001 Id=2 , Name=Name002 Id FirstName -- --------- 1 Name001 MSDN https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/import-csv?view=powershell-6 Getting deeper - what does import-csv actually return? It returns an array with N objects of type System.Management.Automation.PSCustomObject. Here N=no of rows in the CSV file. A: I'm not quite sure what you are asking here, but it looks to me that you want to get the headers of a CSV file as array: (Take the first row(with headers) and add it to an array in powershell) If that is the case, here's a small function that can do that for you: function Get-CsvHeaders { # returns an array with the names of the headers in a csv file in the correct order [CmdletBinding(DefaultParameterSetName = 'ByDelimiter')] param( [Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)] [ValidateScript({Test-Path -Path $_ -PathType Leaf})] [string]$Path, [Parameter(Mandatory = $false)] [ValidateSet ('ASCII', 'BigEndianUnicode', 'Default', 'OEM', 'Unicode', 'UTF32', 'UTF7', 'UTF8')] [string]$Encoding = $null, [Parameter(Mandatory = $false, ParameterSetName = 'ByDelimiter')] [char]$Delimiter = ',', [Parameter(Mandatory = $false, ParameterSetName = 'ByCulture')] [switch]$UseCulture ) $splatParams = @{ 'Path' = $Path } switch ($PSCmdlet.ParameterSetName) { 'ByDelimiter' { $splatParams.Delimiter = $Delimiter; break } 'ByCulture' { $splatParams.UseCulture = $true; break } } if ($Encoding) { $splatParams.Encoding = $Encoding } $data = Import-Csv @splatParams -ErrorAction SilentlyContinue $data[0].PSObject.properties.name } Usage: $headersArray = Get-CsvHeaders -Path 'test.csv'
unknown
d9731
train
I had a similar problem. I use Xlib to take screenshots, but this method can't work on Wayland. Every time I run to xgetimage, I report an error. After looking up the data, I find Wayland doesn't allow such screenshots. However, in this way, I can still get the correct screen size. Now I use DBUS to call the session bus of the system to take a screenshot, which I learned from reading the source code of Gnome screenshot. This is a simple summary code: method_name = "Screenshot"; method_params = g_variant_new ("(bbs)", TRUE, FALSE, /* flash */ filename); connection = g_application_get_dbus_connection (g_application_get_default ()); g_dbus_connection_call_sync (connection, "org.gnome.Shell.Screenshot", "/org/gnome/Shell/Screenshot", "org.gnome.Shell.Screenshot", method_name, method_params, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); The document link is here: https://developer.gnome.org/references The GitHub of Gnome screenshot is here: https://github.com/GNOME/gnome-screenshot
unknown
d9732
train
I found the answer by carefully reading this post here: PHP_CodeSniffer. There are several steps to it - and it's highly customizable: * *Only 'flag' editted lines *Only 'flag' editted files *Which standards to use *Should it show it as a warning or an error. Etc... That combined with: The 'reformat on save' I found in 'Settings' >> 'Actions on save'.
unknown
d9733
train
Having aliased coefficients doesn't necessarily mean two predictors are perfectly correlated. It means that they are linearly dependent, that is at least one terms is a linear combination of the others. They could be factors or continuous variables. To find them, use the alias function. For example: y <- runif(10) x1 <- runif(10) x2 <- runif(10) x3 <- x1 + x2 alias(y~x1+x2+x3) Model : y ~ x1 + x2 + x3 Complete : (Intercept) x1 x2 x3 0 1 1 This identifies x3 as being the sum of x1 and x2
unknown
d9734
train
In the end the solution was a hack of Swipejs in which I added a method 'hideOthers()', setting the style visibility to 'hidden', which unloads the pages from hardware memory: hideOthers: function(index) { var i = 0; var el; for( i in this.slides ) { el = this.slides[i]; if ( el.tagName == 'LI' ) { // Show pages i-1, i and i+1 if ( parseInt(i) == index || (parseInt(i) + 1) == index || (parseInt(i) - 1) == index ) { el.style.visibility = 'visible'; } else { el.style.visibility = 'hidden'; } } } } ..and added the trigger below as last line in the 'slide()' method // unload list elements from memory var self = this; setTimeout( function() { self.hideOthers(index); }, 100 ); Only the translate3d was needed to toggle the hardware acceleration on (as mentioned in my question above): -webkit-transform:translate3d(0,0,0); You can find the result (including iScroll for vertical scrolling) here. A: in regards to the webkit backface/translate3d props used to trigger hardware acceleration, I've read that in iOS 6+ these don't work quite the same as in previous versions, and (more importantly) that hardware acceleration needs to be applied not only on the element that is being animated, but also on any element that it is overlapping/overlaps it. reference (not much): http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/ To be fair this is fairly anecdotal, I was myself unable to fix my own flickering issue - due to tight deadlines - but this might be a point in the right direction.
unknown
d9735
train
cd \ takes you to the root directory of the current drive. That is a function of Windows, not a function of git. If you want to change it, you'll have to use Windows to do that, not git. One route might be to use a separate drive letter (e.g. Z:) bound to C:\Users\J P\Dropbox\Git Bash. In DOS the SUBST command did that. It appears to work with XP, and here's a way to make it persistent. The easiest appears to be: net use z: "\\computerName\c$\Users\J P\Dropbox\Git Bash" /persistent:yes Then if you change to drive z:, cd \ will take you to z:'s root, which will be the right place. There's probably a different/better Windows way to do that.
unknown
d9736
train
Try with this. for setting up kubernetes cluster using ansible. This will provision AWS ec2 and will setup cluster. This role includes lots of addons which is sufficient for development cluster [1]: https://github.com/khann-adill/kubernetes-ansible
unknown
d9737
train
Assuming you mean you want something like this: class base { public: virtual void h_w() { std::cout << "Hello world!\n"; } }; class derived : public base { public: void h_w() { std::cout << "Today is: " << rand() << "\n"; } }; int main() { std::unique_ptr<base> b = std::make_unique<derived>(); b->h_w(); } ...then yes, C++ supports that. In fact, this is pretty much a canonical demonstration of virtual functions, at least if you change names to (for example) "animal" as the base class and "duck" as the derived class, and have them print out something like "generic animal" and "duck" respectively. For the record, it's probably worth noting that most example based on animals are more or less broken in various ways, such as animals simply not following simple sets of rules like we expect code to. A better example, would be something like a base class defining a generic interface to a database that allows things like reading a record, writing a record, and finding a set of records that satisfy some criteria. The derived class could then (for example) provide an implementation to carry out those "commands" in terms of some specific type of database--perhaps SQL, or perhaps some simple key/value storage engine, but the client doesn't know or care, beyond minor details like performance. As to why this is better: first of all, because it corresponds much more closely to things you're likely to really do with a computer. Second, because we can define databases to really follow our rules and fulfill the obligations we set. With animals, we're stuck with all sorts of exceptions to any meaningful rule we might try to make, as well as the simple fact that (of course) being able to make a Duck say "quack" and a dog say "bow wow" isn't really very useful (and in the rare case that it is useful, we probably just want to save/retrieve its sound as some sort of blob, not define an entire new type to encode something better stored as data).
unknown
d9738
train
The code you posted doesn't run. The beginning of each for loop for (line[i]; makes no sense. Maybe you meant for (line = lines[i]; ? var lines = ["Line 1", "Line 2", "Line 3"], i = 0, line; for (line = lines[i]; i < lines.length; line = lines[i++]) { console.log(line); //Outputs "Line 1" three times } i = 0; for (line = lines[i]; i < lines.length; i++, line = lines[i]) { console.log(line); //Outputs "Line 1", "Line 2", "Line 3" } In that case case 1 prints line 1 line 1 line 2 And case 2 prints line 1 line 2 line 3 As for why, i++ means temp = i; i = i + 1; return temp; so in the first case if i = 0 this part line = lines[i++] will be this line = lines[0], i = i + 1 since temp in the example of what i++ actually means is 0 at the point it's used. whereas in the second case i++, line = lines[i] You're doing the postincrement before it's used To be clear i++ this is called post incrementing. The value of the expression is the value before it was incremented. If you actually mean increment instead of postincrement use ++i As for elegant, that's an opinion. It's not clear what you're trying to do and there are certainly reasons to use loops based on indices but just in case here's a few other ways to iterate var lines = ["Line 1", "Line 2", "Line 3"]; // use a function lines.forEach(function(line) { console.log(line); }); // use a function with arrow syntax lines.forEach(line => { console.log(line); }); // and of course if you really want to use indices why is // this not elegant? for (let i = 0, len = lines.length; i < len; ++i) { const line = lines[i]; console.log(line); } It's not clear to me why you think you're solution is elegant. I'd look at your solution and think it's obfusticated. In other words it's hard to understand and hard to understand is not elegant. A: Javascript For Final Expression does not allow complex statements. Why? You answered your own question. The final-expression is an expression, not a statement. That is the way the language was designed. It goes back to the comma operator in C forty years ago, if not further. If you want to assign line inside the for, you can write your loop this way: const lines = [1, 2, 3]; for (let i = 0, line; line = lines[i], i < lines.length; i++) { console.log(line); }
unknown
d9739
train
by DICOM cine image, you mean multi-frame DICOM files right? May i know : which platform you are on, which dicom lib/SDK you are using? and for your DICOM image, has it been decompressed? to BMP(32-bit/24-bit)? If your dicom file is in 24bit(3-bytes) BMP, then your next frame of pixel data would be 640*480*3. A: Assuming you are dealing with uncompressed (native) multi-frame DICOM. In that case, you need to extract following information before proceeding to calculate the size of each image frame. * *Transfer Syntax (0002, 0010) to make sure dataset set is not using encapsulated/compressed transfer syntax. *Sample per Pixel (0028, 0002): This represents number of samples (planes) in this image. As for example 24-bit RGB will have value of 3 *Number of Frames (0028, 0008): total number of frames *Rows (0028, 0010) *Columns (0028, 0011) *Bit Allocated (0028, 0100): Number of bits allocated for each pixel sample. *Planar Configuration (0028, 0006): Conditional element that indicates whether the pixel data are sent color-by-plane or color-by-pixel. This is required if Samples per Pixel (0028, 0002) has a value greater than 1. You would calculate the frame size as follows: Frame size in bytes = Rows * Columns * (Bit Allocated* Sample per Pixel/8)
unknown
d9740
train
Use subprocess.call with stdout argument: import subprocess import sys with open('text.log', 'w') as f: subprocess.call([sys.executable, 'server.py'], stdout=f) # ADD stderr=subprocess.STDOUT if you want also catch standard error output
unknown
d9741
train
If you don't explicitly request an order with ORDER BY, MySQL displays the results in the order it reads them from an index. I would infer that MySQL is using your UNIQUE index to read these rows, so they're read from that index in order by product_id first, then by project_id. By analogy, if you read names from the telephone book, you read them in order by last name and then by first name. That's the order they're stored, regardless of which phone number was assigned first. The id column is the primary key, which is implicitly appended to every non-primary index. A: Normally, databases do not have a "default" order, so if you do not specify an implicit order, you can not make any assumptions on the final order of the results. If you need to retrieve the records in any certain order, you should append " ORDER BY " at the end of your query. Please, note that the exact same query, without an order by clause, can produce results in very different order. A: Do not depend on order when ORDER BY is missing. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. So there's even no guarantee that two queries which look the same will return results in the same order: if you don't specify it, you cannot rely on it.
unknown
d9742
train
well there has been many discussion on this topic actually, backbone does nothing for you, you will have to do it yourself and this is what you have to take care of: * *removing the view (this delegates to jQuery, and jquery removes it from the DOM) // to be called from inside your view... otherwise its `view.remove();` this.remove(); this removes the view from the DOM and removes all DOM events bound to it. *removing all backbone events // to be called from inside the view... otherwise it's `view.unbind();` this.unbind(); this removes all events bound to the view, if you have a certain event in your view (a button) which delegates to a function that calls this.trigger('myCustomEvent', params); if you want some idea's on how to implement a system I suggest you read up on Derrick Bailey's blogpost on zombie views: http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/. another option another option would be to reuse your current view, and have it re-render or append certain items in the view, bound to the collection's reset event A: I was facing the same issue. I call the view.undelegateEvents() method. Removes all of the view's delegated events. Useful if you want to disable or remove a view from the DOM temporarily. A: I use the stopListening method to solve the problem, usually I don't want to remove the entire view from the DOM. view.stopListening(); Tell an object to stop listening to events. Either call stopListening with no arguments to have the object remove all of its registered callbacks ... or be more precise by telling it to remove just the events it's listening to on a specific object, or a specific event, or just a specific callback. http://backbonejs.org/#Events-stopListening A: Here's one alternative I would suggest to use, by using Pub/Sub pattern. You can set up the events bound to the View, and choose a condition for such events. For example, PubSub.subscribe("EVENT NAME", EVENT ACTIONS, CONDITION); in the condition function, you can check if the view is still in the DOM. i.e. var unsubscribe = function() { return (this.$el.closest("body").length === 0); }; PubSub.subscribe("addSomething",_.bind(this.addSomething, this), unsubscribe); Then, you can invoke pub/sub via PubSub.pub("addSomething"); in other places and not to worry about duplicating actions. Of course, there are trade-offs, but this way not seems to be that difficult.
unknown
d9743
train
You have entered the times as strings. As such, the formatting for numbers has no effect. You need to enter either datetime.time objects or datetime.timedelta objects in order for the formatting to have an effect, though openpyxl by default will try and set it correctly. eg. ws["A4"] = datetime.time(hours=1, minutes=2)
unknown
d9744
train
The documentation clearly states: To use this module, you need to have already downloaded and started the Selenium Server (Selenium Server is a Java application). A: In order to use any of the "unofficial bindings" (like the Perl bindings) you need to first launch the standalone-server jar file. As well, you need to do this in all the bindings if the browser is opening in a machine other than where the script is running (e.g. using RemoteWebdriver). Hope that helps. A: You can also use this, so you don't have to start the Selenium Server yourself: `use Selenium::PhantomJS;` `my $driver = Selenium::PhantomJS->new;`
unknown
d9745
train
Take a look at: Remove C# attribute of a property dynamically Anyway I think the proper solution is to inherit an attribute from RequiredAttribute and override the Validate() method (so you can check when that field is required or not). You may check CompareAttribute implementation if you want to keep client side validation working. A: Instead of dynamically adding and removing validation, you would be better served to create an attribute that better serves this purpose. The following article demonstrates this (MVC3 with client-side validation too): http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx A: I would remove the RequiredAttribute from your model and check it once you've hit your controller and check it against whatever causes it to not be required. If it falls into a case where it is required and the value is not filled in, add the error to the ModelState manually ModelState.AddModelError("DepartmantCode", "DepartmantCode is Required"); You would just lose the validation on the client side this way A: I've got round this issue in the model, in some cases it's not ideal but it's the cheapest and quickest way. public string NonMandatoryDepartmentCode { get { return DepartmentCode; } set { DepartmentCode = value; } } I used this approach for MVC when a base model I inherited contained attributes I wanted to override.
unknown
d9746
train
The command that Ansible is running is returning 255 as the return code, for some reason: <127.0.0.1> (255, b'/home/vagrant\n', b'') OpenSSH uses this return code for connection errors but does not prevent remote processes from returning it, and Ansible can't tell the difference between a 255 that is a genuine connection error and whatever happened here. Paramiko is a Python library and raises errors using native Python error handling, so it doesn't have the same issue. The only way to get Ansible's OpenSSH plugin working is to figure out why '/bin/sh -c '"'"'echo ~vagrant && sleep 0'"'"' is returning 255 on your target host, and fix that issue.
unknown
d9747
train
Try this: I asume you are dismissing a view controller 2 from view controller 1. In view controller 2 you are using this [self dismissModalViewControlleAnimated: NO]]; Now In the first view controller, in viewWillAppear: method add the code CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setType:kCATransitionPush]; [animation setSubtype:kCATransitionFromLeft]; [animation setDuration:0.50]; [animation setTimingFunction: [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]]; [self.view.layer addAnimation:animation forKey:kCATransition]; A: I have accepted the answer from Safecase, but I would like to publish my final solution here: 1) To present a modal view controller with a from right to left transition I have written following method: -(void) presentModalView:(UIViewController *)controller { CATransition *transition = [CATransition animation]; transition.duration = 0.35; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionMoveIn; transition.subtype = kCATransitionFromRight; // NSLog(@"%s: self.view.window=%@", _func_, self.view.window); UIView *containerView = self.view.window; [containerView.layer addAnimation:transition forKey:nil]; [self presentModalViewController:controller animated:NO]; } 2) To dismiss a modal view with an slide transition left to right: -(void) dismissMe { CATransition *transition = [CATransition animation]; transition.duration = 0.35; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionMoveIn; transition.subtype = kCATransitionFromLeft; // NSLog(@"%s: controller.view.window=%@", _func_, controller.view.window); UIView *containerView = self.view.window; [containerView.layer addAnimation:transition forKey:nil]; [self dismissModalViewControllerAnimated:NO]; } Thanks guys! A: This Swift 4 ModalService class below is a pre-packaged flexible solution that can be dropped into a project and called from anywhere it is required. This class brings the modal view in on top of the current view from the specified direction, and then moves it out to reveal the original view behind it when it exits. Given a presentingViewController that is currently being displayed and a modalViewController that you have created and wish to display, you simply call: ModalService.present(modalViewController, presenter: presentingViewController) Then, to dismiss, call: ModalService.dismiss(modalViewController) This can of course be called from the modalViewController itself as ModalService.dismiss(self). Note that dismissing does not have to be called from the presentingViewController, and does not require knowledge of or a reference to the original presentingViewController. The class provides sensible defaults, including transitioning the modal view in from the right and out to the left. This transition direction can be customised by passing a direction, which can be customised for both entry and exit: ModalService.present(modalViewController, presenter: presentingViewController, enterFrom: .left) and ModalService.dismiss(self, exitTo: .left) This can be set as .left, .right, .top and .bottom. You can likewise pass a custom duration in seconds if you wish: ModalService.present(modalViewController, presenter: presentingViewController, enterFrom: .left, duration: 0.5) and ModalService.dismiss(self, exitTo: .left, duration: 2.0) Head nod to @jcdmb for the Objective C answer on this question which formed the kernel of the solution in this class. Here's the full class. The values returned by the private transitionSubtype look odd but are set this way deliberately. You should test the observed behaviour before assuming these need 'correcting'. :) import UIKit class ModalService { enum presentationDirection { case left case right case top case bottom } class func present(_ modalViewController: UIViewController, presenter fromViewController: UIViewController, enterFrom direction: presentationDirection = .right, duration: CFTimeInterval = 0.3) { let transition = CATransition() transition.duration = duration transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionMoveIn transition.subtype = ModalService.transitionSubtype(for: direction) let containerView: UIView? = fromViewController.view.window containerView?.layer.add(transition, forKey: nil) fromViewController.present(modalViewController, animated: false) } class func dismiss(_ modalViewController: UIViewController, exitTo direction: presentationDirection = .right, duration: CFTimeInterval = 0.3) { let transition = CATransition() transition.duration = duration transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionReveal transition.subtype = ModalService.transitionSubtype(for: direction, forExit: true) if let layer = modalViewController.view?.window?.layer { layer.add(transition, forKey: nil) } modalViewController.dismiss(animated: false) } private class func transitionSubtype(for direction: presentationDirection, forExit: Bool = false) -> String { if (forExit == false) { switch direction { case .left: return kCATransitionFromLeft case .right: return kCATransitionFromRight case .top: return kCATransitionFromBottom case .bottom: return kCATransitionFromTop } } else { switch direction { case .left: return kCATransitionFromRight case .right: return kCATransitionFromLeft case .top: return kCATransitionFromTop case .bottom: return kCATransitionFromBottom } } } }
unknown
d9748
train
Thanks to Robert Crovella for pointing me in the right direction with a comment above, and linking a similar question. The gist is that by passing devPtr by value rather than by pointer or by reference into my GPU write and read functions, the cudaMalloc and cudaMemcpy functions were acting only on a copy in the function scope. Two solutions - (both of these run without throwing errors for me) First: Pass devPtr by reference into write2dArrayToGPU and read2dArrayFromGPU the solution then looks like. #include <iostream> using namespace std; void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){ arr = new float*[rows]; arr[0] = new float[rows * cols]; for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols; } //changed float * devPtr to float * &devPtr void write2dArrayToGPU(float ** arr, float * &devPtr, unsigned long int rows, unsigned long int cols){ if(cudaSuccess != cudaMalloc((void**)&devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed"; if(cudaSuccess != cudaMemcpy(devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed"; } //changed float * devPtr to float * &devPtr void read2dArrayFromGPU(float ** arr, float * &devPtr, unsigned long int rows, unsigned long int cols){ if(cudaSuccess != cudaMemcpy(arr[0], devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl; } int main(){ int R = 100; int C = 7; cout << "Allocating an " << R << "x" << C << " array ..."; float ** arrA; alloc2dArray(arrA, R, C); cout << "Assigning some values ..."; for(int i = 0; i < R; i++){ for(int j = 0; j < C; j++){ arrA[i][j] = i*C + j; } } cout << "Done!" << endl; cout << "Writing to the GPU ..."; float * Darr = 0; write2dArrayToGPU(arrA, Darr, R, C); cout << " Done!" << endl; cout << "Allocating second " << R << "x" << C << " array ..."; float ** arrB; alloc2dArray(arrB, R, C); cout << "Done!" << endl; cout << "Reading from the GPU into the new array ..."; read2dArrayFromGPU(arrB, Darr, R, C); } Second: Pass devPtr by pointer so the solution looks like #include <iostream> using namespace std; void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){ arr = new float*[rows]; arr[0] = new float[rows * cols]; for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols; } //changed float * devPtr to float ** devPtr void write2dArrayToGPU(float ** arr, float ** devPtr, unsigned long int rows, unsigned long int cols){ if(cudaSuccess != cudaMalloc((void**)devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed"; if(cudaSuccess != cudaMemcpy(*devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed"; } //changed float * devPtr to float ** devPtr void read2dArrayFromGPU(float ** arr, float ** devPtr, unsigned long int rows, unsigned long int cols){ if(cudaSuccess != cudaMemcpy(arr[0], *devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl; } int main(){ int R = 100; int C = 7; cout << "Allocating an " << R << "x" << C << " array ..."; float ** arrA; alloc2dArray(arrA, R, C); cout << "Assigning some values ..."; for(int i = 0; i < R; i++){ for(int j = 0; j < C; j++){ arrA[i][j] = i*C + j; } } cout << "Done!" << endl; cout << "Writing to the GPU ..."; float * Darr = 0; write2dArrayToGPU(arrA, &Darr, R, C); \\changed Darr to &Darr cout << " Done!" << endl; cout << "Allocating second " << R << "x" << C << " array ..."; float ** arrB; alloc2dArray(arrB, R, C); cout << "Done!" << endl; cout << "Reading from the GPU into the new array ..."; read2dArrayFromGPU(arrB, &Darr, R, C); // changed Darr to &Darr }
unknown
d9749
train
you could try it as follows: detection_object.objects.raw({'legacy_id': "1437424"} ).first() probably the legacy_id is stored as string. Othewise, make sure the db name is present at the end of the MONGO_URI as it is underlined in the docs. A: Each document in your 'detection_object' collection requires to have '_cls' attribute. The string value stored in this attribute should be __main__.classname (class name according to your code is detection_object). For example a document in your database needs to look like this: {'_id': ObjectId('5c4099dcffa4fb11494d983d'), 'legacy_id': 1437424, '_cls': '__ main __.detection_object'}
unknown
d9750
train
Found my problem. I did not append Provider to the provider name. In this case it would look like accessProviderProvider.
unknown
d9751
train
You can try using the deconstruct_array (..) function to extract the values. This function will give you a Datum type pointer. Example of the book: deconstruct_array(input_array, //one-dimensional array INT4OID, //of integers 4,//size of integer in bytes true,//int4 is pass-by value 'i',//alignment type is 'i' &datums, &nulls, &count); // result here "The datums pointer will be set to point to an array filled with actual elements." You can access the values using: DatumGetInt32(datums[i]);
unknown
d9752
train
With single awk: awk '{ k=$1 FS $2 FS $3 }NR==FNR && NF{ a[k]=$1; next } NF{ if(k in a) delete a[k]; else if(!b[$1]++) print $1 } END{ for(i in a) if(!(a[i] in b)) print a[i] }' file1 file2 The output: LSP1 LSP2 A: $ comm -3 file1 file2 | awk '$1 { print $1 }' | uniq LSP1 LSP2 comm -3 will output the lines that are only in file1 xor in file2. The awk script will extract column 1 from non-empty lines (whitespace-separated) and uniq will remove duplicates. Note that comm assumes sorted input. A: $ awk -v RS= 'NR==FNR{a[$1]=$0;next} $0!=a[$1]{print $1}' file1 file2 LSP1 LSP2
unknown
d9753
train
You could use the weblogic.rmi.clientTimeout setting in order to avoid thread stuck situations when the target server is experiencing problems. EDITED: Another solution which is useful when you are trying to read from a socket and you are not getting any response from the server is the following: An RMISocketFactory instance is used by the RMI runtime in order to obtain client and server sockets for RMI calls. An application may use the setSocketFactory method to request that the RMI runtime use its socket factory instance instead of the default implementation. Implementation example: RMISocketFactory.setSocketFactory(new RMISocketFactory() { public Socket createSocket(String host, int port) throws IOException { Socket s = new Socket(); s.setSoTimeout(timeoutInMilliseconds); s.setSoLinger(false, 0); s.connect(new InetSocketAddress(host, port), timeoutInMilliseconds); return s; } public ServerSocket createServerSocket(int port) throws IOException { return new ServerSocket(port); } }); The setSocketFactory sets the global socket factory from which RMI gets sockets.
unknown
d9754
train
The issue is with the names of input fields. In PHP or any other programming language, You should use the input name="something" to get the input values. You should give the name for each input fields. For example, <input name = "name" id="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required><br> A: <form method='post' enctype='multipart/form-data'> <input name="name" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required><br> <input name="designation" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required><br> <input name="description" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required><br> <input id="pic" type="file" style="height:30px; width: 350px; "><br><br> <input name="insert" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px;" value='Add Member' /><br><br> </form> <?php if(isset($_POST['insert'])) { echo $namevar = $_POST['name']; echo $descriptionvar = $_POST['description']; echo $designationvar = $_POST['designation']; } ?> A: You cannot pass POST data to another page vie using ID. You should give name to <input> <input name="name"> <input name="description"> <input name="designation"> Edit You are defining variables and echoing them same time Change your code to: <?php if(isset($_POST["insert"])){ echo $_POST["name"]; echo $_POST["description"]; echo $_POST["designation"]; }?>
unknown
d9755
train
The exception seems to tell you that the key you are trying to add in toVerifyTags already exists. You weren't checking if the key already existed in the right dictionary. public void verifyTags(List<BasicTagBean> tags) { System.Diagnostics.Debug.WriteLine("Thread ID: " + Thread.CurrentThread.ManagedThreadId); lock (lockobj) { foreach (BasicTagBean tag in tags) { if (!toVerifyTags.ContainsKey(tag.EPC)) { toVerifyTags.Add(tag.EPC, tag); } } }
unknown
d9756
train
The GRP_ID can be calculated using DENSE_RANK(): select col1, col2, col3, dense_rank() over (order by col1, col2, col3) as grp_id from t; If you want to update the value, one method is: update t set grp_id = (select count(distinct col1, col2, col3) + 1 from t t2 where t2.col1 < t.col1 or (t2.col1 = t.col1 and t2.col2 < t.col2) or (t2.col1 = t.col1 and t2.col2 = t.col2 and t2.col3 <= t.col3) ); Note that not all database support count(distinct) on multiple columns. In those databases, you can concatenate the values together.
unknown
d9757
train
yes u can use php or there is some backend providers that offer alot of good stuff backendless or parse.com but if u already have your php services dame u can use them by the HTTPRequests / HTTPResponses using this in some asynch task will make it eazy
unknown
d9758
train
I don't understand the "return an event" but I'm guessing you want to call finish function whenever something is finished. I am not sure this is the best way, but it's something you can start with. $.fn.myFunction = function (object) { const _self = $(this); const init = () => { if (object.hasOwnProperty('myCallback') && typeof object.myCallback === 'function') { _self.on('myEvent', object.myCallback) } _self.on('click', triggerCustomEvent) }; const triggerCustomEvent = () => _self.trigger('myEvent') init(); } $('#c').myFunction({ myCallback: () => alert(123), }) $('#d').myFunction({ myCallback: () => alert(1234), }) body { background: #20262E; padding: 20px; font-family: Helvetica; } #banner-message { background: #fff; border-radius: 4px; padding: 20px; font-size: 25px; text-align: center; transition: all 0.2s; margin: 0 auto; width: 300px; } button { background: #0084ff; border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; color: #fff; } #banner-message.alt { background: #0084ff; color: #fff; margin-top: 40px; width: 200px; } #banner-message.alt button { background: #fff; color: #000; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div id="banner-message"> <button id="c">Color</button> <button id="d">Dollar</button> </div>
unknown
d9759
train
QNetworkAccessManager doesn't support that A: Although it is recommended to use QNetworkAccessManager as much as possible, you always fall back to the QtFtp add-on as follows: QT += ftp Then, you will be able to use the mkdir method of the QFtp class.
unknown
d9760
train
I had real trouble with this and finally with some support which led me in the right direction I managed to get the syntax correct, this is entered in the Name column of the Resources.resw file. myUid.[using:Windows.UI.Xaml.Controls.Primitives]PickerFlyoutBase.Title
unknown
d9761
train
Try adding an entry in the /etc/hosts on the host where you are running this command for this host 192.168.50.20 and see if it works Something like 127.0.0.1 localhost.localdomain localhost OR 192.168.50.20 hostname hostname-alias Then try using it in the command OR Try using ip address directly in the command instead of localhost
unknown
d9762
train
Plain old luck, I would say. If thirty threads go ahead and want to update the same 1000 rows, they can either access these rows in the same order (in which case they will lock out each other and do it sequentially) or in different orders (in which case they will deadlock). That's the same for InnoDB and PostgreSQL. To analyze why things work out different in your case, you should start by comparing the execution plans. Maybe then you get a clue why PostgreSQL does not access all rows in the same order. Lacking this information, I'd guess that you are experiencing a feature introduced in version 8.3 that speeds up concurrent sequential scans: * *Concurrent large sequential scans can now share disk reads (Jeff Davis) This is accomplished by starting the new sequential scan in the middle of the table (where another sequential scan is already in-progress) and wrapping around to the beginning to finish. This can affect the order of returned rows in a query that does not specify ORDER BY. The synchronize_seqscans configuration parameter can be used to disable this if necessary. Check if your PostgreSQL execution plan uses sequential scans and see if changing synchronize_seqscans avoids the deadlocks.
unknown
d9763
train
It it doesn't work either... cannot use grd_studentsList (type `[]ui.Grid`) as type `[]ui.Control` in argument to `ui.NewSimpleGrid` As I mentioned before ("What about memory layout means that []T cannot be converted to []interface{} in Go?"), you cannot convert implicitly A[] in []B. You would need to copy first: var controls []ui.Control = make([]ui.Control, len(grd_studentsList)) for i, gs := range grd_studentsList{ controls [i] = gs } And then use the right slice (with the right type) return ui.NewSimpleGrid(1, controls...) A: Try something like: return ui.NewSimpleGrid(1, grd_studentsList...) ^^^^ This is mentioned in the spec Passing arguments to ... parameters.
unknown
d9764
train
To use the class as it is written ANGULAR_RESO must be a compile time constant and in this way it is no longer a specific member for every object. It must be static. If you need a varying array size, use std::vector , as follows class BLDCControl { public: uint16_t ANGULAR_RESO; std::vector<uint16_t> sine; uint16_t pwm_resolution = 16; } And if ANGULAR_RESO is the size of your array (as @ aschepler suggested ), you can go without it because your std::vector has this size as a private member and you can get its value by std::vector<unit16_t>::size() method #include <cstdint> #include <vector> struct BLDCControl { BLDCControl(uint16_t ANGULAR_RESO, uint16_t pwm_resolution_v = 16) : pwm_resolution {pwm_resolution_v}, sine {std::vector<uint16_t>(ANGULAR_RESO)}{} std::vector<uint16_t> sine; uint16_t pwm_resolution; }; int main(){ BLDCControl u(4, 16); std::cout << "ANGULAR_RESO is:\t" << u.sine.size(); }
unknown
d9765
train
What you are looking for is the WordPress Rewrite API. This allows you to define a new "endpoint" for your URL's, and allows you to pick up the variable from the URL via built-in WordPress functionality. A great article on it can be found here: Custom Endpoints
unknown
d9766
train
You try to use Request before it is initialized, before $app->run(). You can manually initialize Request: $app = new \Silex\Application(); $app['request'] = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); ..... $app->run($app['request']); or make lazy loading in service providers: $app['object1'] = $app->share(function ($app) { return new Object1($app['request']->query->get('country')); }); ... and somewhere in controller get these variable as $app['object1']
unknown
d9767
train
Have you created a new PyDev project for this? Without that, Eclipse won't be able to find your full Jython installation, which could explain the underlinings. In my environment (Eclipse Kepler, PyDev, and Jython 2.5.2) it works correctly.
unknown
d9768
train
You are initiating an asynchronous NSURLConnection and then immediately starting the parsing process. You need to defer the initiation of the parsing until connectionDidFinishLoading, or you should do a synchronous NSURLConnection (but obviously, not from the main queue). Thus, while you're eventually getting a response, the parsing is undoubtedly initiated before the response has been received.
unknown
d9769
train
The reason why you can't see Log.d("ss", "save") being called is simply that the code line is invoked after the return statement. The onSaveInstanceState() is actually called. To see the log move Log.d("ss", "save") above return super.onSaveInstanceState().
unknown
d9770
train
After having a bit of a play and a Google, I found this page which helped me fix my issue https://msdn.microsoft.com/en-us/library/office/aa221970(v=office.11).aspx I changed my code as below: version = WrdDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text Although I'm not sure why the previous version didnt work as there is a footer on the first page.
unknown
d9771
train
If you call new Word.Application you're creating a new instance, if what you want is to create a new instance if there is none, but reuse one if there is already one open you can do the following: Application app; try { app = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"); } catch { app = new Application(); } Based on your comment i think you actually only have 1 instance of word open, it just opens both documents in different Windows (but a single application). Windows aren't the same as applications. If you want it all in a single window you could reuse the previous document or else close it before you open a new one A: Ronan's code above did the trick for me. I was doing new Application() every time, adding WINWORD instances (I know, should've known better). I speak both C# and VB, but here's the VB version I used in this project: ' Use same winword instance if there; if not, create new one Dim oApp As Application Try oApp = DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"), Application) Catch ex As Exception ' Word not yet open; open new instance Try ' Ensure we have Word installed oApp = New Application() Catch eApp As Exception Throw New ApplicationException(String.Format("You must have Microsoft Word installed to run the Top Line report")) End Try End Try oApp.Visible = True
unknown
d9772
train
Have you thought about creating a fifth column by adding the data of the four columns into it? Just use the QGIS field calculator to do it in a single command. Then do the qgis2web setup in this fifth column. This way when your users start typing the language they will see the different locations in the drop-down menu that they can select for zooming. Greetings.
unknown
d9773
train
I ran it on my x64 machine and it works ok, it does start to struggle as time goes but I wouldn't call it a memory leak, if anything it just hammers the CPU when it spikes. It could just be struggling to keep up with the commands depending on the performance of the computer. I added in a timeout for a second, now cmd is much happier and showing less than 1MB RAM consumption. Try just adjusting this to your needs, or find middle ground where you get the speed and the performance, just give cmd a break :) @echo off :label cmd.exe /c cls echo hello timeout /t 1 >nul goto label
unknown
d9774
train
Try this: 1) Add Enabled="True" to gridview markup: <ac:GridViewWithPager ID="gdvwAllowedVersion" runat="server" Enabled="True" UseCustomPager="True" AllowPaging="True" AutoGenerateColumns="False" Width="50%"> 2) Use Jquery's DOM manipulation method attr(key, value) to enable/disable gridview: $(document).ready(function () { // Add onclick handler to checkbox w/id checkme $('#<%=chkActivateSettings.ClientID %>').click(function () { // If checked if ($('#<%=chkActivateSettings.ClientID %>').is(":checked")) { //show the hidden div $('#<%=gdvwAllowedVersion.ClientID %>').attr("disabled", false); } else { //otherwise, hide it $('#<%=gdvwAllowedVersion.ClientID %>').attr("disabled", true); } }); });
unknown
d9775
train
The list you are quoting is not a list of options presented in a menu, it is a list of different ways of saying the same thing. These are all just keywords which Github recognises when it looks at the description. Different people use different terms, so rather than forcing people to use (and remember) one preferred term, they include multiple possibilities. The examples below the list use different keywords just for illustration. All the keywords are interchangeable.
unknown
d9776
train
If you want the new window not to have the menu bars and toolbars, the only way to do it is through JavaScript as with the example you provided yourself. However keep in mind that most browsers, nowadays, ignore what you set for the status bar (always show it) and may be configured to also always show the remaining toolbars. If a browser is configured in such a way there's no escaping it, although the default should be that you'll only get the status bar and perhaps the address bar. A: Your solution is good, but there are alternatives. You can create the window by your own, as some kind of layer. Then you need to implement lots of things but it gives you full control over window Look And Feel. Of course you can always use some scripts like jQuery UI Dialog. A: In short, you can't control everything that the browser displays in a pop-up window. Most browsers keep the URL visible, for example. This page explains most of the details (though it is a couple years old).
unknown
d9777
train
I am using a debian system and installed the libgpg-error-dev package and it worked. A: Via this forum post, adding --disable-static to ./configure was my fix. I'm installing in a web hosting environment as a user without sudo/root. My full configure command is ./configure --prefix=$HOME --without-zlib --disable-static
unknown
d9778
train
Yes, earlier versions of iOS 10 did still enforce the forward secrecy requirement of app transport security in web views even with the NSAllowsArbitraryLoadsInWebContent key. That was a bug, that was fixed by Apple. The problem is that earlier versions of iOS shipped with the bug so you must be able to handle it, which isn't always possible if you don't know all the possible URLs that your Web you could navigate to. This may be part of the reason that Apple has extended their deadline for enabling app transport security and all apps submitted to the App Store.
unknown
d9779
train
Its pretty useless to create getters and setters with snippets for ruby. Using attr_accessor & attr_reader is the fastest and cleanest way to declare these properties and NOT having to create snippets for it. attr_accessor :name is the same as def name @name end def name=(n) @name = n end 99% of the time this is what you want. Just declare an attribute accessor for the given instance variable. The remaining 1% is when you actually want a custom attribute with some extra validations inside. And even then you could declare attr_reader :custom_attribute def custom_attribute=(value) # some validation code here ... @custom_attribute = value end
unknown
d9780
train
There is no OnMouseOver server-side event on asp:Image object. What you can do you can write js function called on client-side onmouseover event and inside that function trigger click on hidden button or you can change Image to ImageButton and trigger click on that image. <asp:Image ID="MapImage" runat="server" Height="601px" Width="469px" onmouseover="javascript:foo()"/> <asp:Button ID="Button1" runat="server" style="display:none" OnClick="OnMouseOverMap" /> And in js function: function foo() { document.getElementById('<%= Button1.ClientID %>').click(); } A: I am pretty sure that you are supposed to insert javascript code there and not a "code behind event handler reference". See ASP NET image onmouseover not working for example.
unknown
d9781
train
Can you list the objects and their relationship names? What you're asking is of course possible, but it's a bit hard to grok (for me) from what's above. A couple of suggestions without that; * *You can traverse the relationship from parent to children (not sure if child is a to-many or a to-one though) and again out to the grandchild *You can get funkier using a SUBQUERY() NSPredicate. Advantage is fetch speed, disadvantage is that it's a bit more complex (and sometimes can indicate that you're going about things in not the best way).
unknown
d9782
train
pluck doesn't modify the original relationship, it only returns an array. Try this one : public function show(Request $request, Company $company) { $this->authorize('view', $company); $result = $company->toArray(); if ($request->boolean('with_roles')) { $result['roles'] = $company->roles()->pluck('name')->toArray(); } return new ApiSuccessResponse($result); }
unknown
d9783
train
db4o (at least until Jan/2012) can only load full objects. You can use some tricks like introduce a new class to hold data (fields) that you don't use very often and rely on transparent activation to load this data when required (something like the code below). class FishData { private Image picture; // other fields, getters / setters etc } class Fish { private string name; private FishData data; // other fields, getters / setters etc }
unknown
d9784
train
I believe that's because inside your keyframes, you're using transform:, which will work for IE10, Firefox and Opera, but haven't also got the webkit equivalent - specifically -webkit-transform which will work for Chrome and Safari. @keyframes threesixty { 0% { transform: rotate(0deg); -webkit-rotate(0deg); -ms-transform:rotate(0deg); } 100% { transform: rotate(360deg); -webkit-rotate(360deg); -ms-transform:rotate(360deg); } } @-webkit-keyframes threesixty { 0% { transform: rotate(0deg); -webkit-rotate(0deg); -ms-rotate(0deg); } 100% { transform: rotate(360deg); -webkit-rotate(360deg); -ms-rotate(360deg); } } You should also include the -ms- prefix as I've shown above, for versions of IE before 10. A: From the MDN article on transforms: Webkit browsers (Chrome, Safari) still needs the -webkit prefix for transforms, while Firefox, as of version 16, does not. This code should do the job for you: @keyframes threesixty { 0% { transform: rotate(0deg); -webkit-transform: rotate(0deg); } 100% { transform: rotate(360deg); -webkit-transform: rotate(360deg); } } @-webkit-keyframes threesixty { 0% { transform: rotate(0deg); -webkit-transform: rotate(0deg); } 100% { transform: rotate(360deg); -webkit-transform: rotate(360deg); } } For Opera and IE9+ support, use -o and -ms prefixes respectively. (IE10 does not require the prefix)
unknown
d9785
train
there is nothing wrong with the program. It works fine, Just check it again How many Verses would you like to print: 4 4 bottles of beer on the wall 4 bottles of beer Take one down, pass it around, 3 bottles of beer on the wall. 3 bottles of beer on the wall 3 bottles of beer Take one down, pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall 2 bottles of beer Take one down, pass it around, 1 bottles of beer on the wall. 1 bottles of beer on the wall 1 bottles of beer Take one down, pass it around, 0 bottles of beer on the wall. Go to the store, buy some more, 99 bottles of beer on the wall. A: I would try it like that: for ( int x = 0; x <= num2; x++ ) { int y = 100 - x; System.out.println(y + " bottles of beer on the wall " + y + " bottles of beer"); System.out.println("Take one down, pass it around, " + (y - 1) + " bottles of beer on the wall.\n"); } It's easier to understand if you define a second variable. Now you have your output with 100 99 98 97 96
unknown
d9786
train
"difference between 2 Numbers in %" sounds strange, perhaps you want percentage difference (see explanation at https://www.mathsisfun.com/percentage-difference.html) For case of comprising only results of exp function (two positive values) you can use the following function: double percdiffcalc(double a, double b) { double difference = abs(a - b); double average = (a + b) / 2.0; return difference * 100.0 / average; } You can call this function for any two values, e.g. percdiffcalc(myexp(x), exp(x));
unknown
d9787
train
My assumptions from your questions: * *You want to use Appcelerator Arrow Push to send a push notification using https://platform.appcelerator.com *You want the push notification to appear in the iOS Notification Centre You code does not show that you actually send the deviceToken to Arrow or any other back-end where you'd send the push notification. Please follow: https://appcelerator.github.io/appc-docs/latest/#!/guide/Subscribing_to_push_notifications-section-37551717_Subscribingtopushnotifications-SubscribingtoPushNotificationswithDeviceTokens The app does not control where a push notification appears. This is controlled in iOS via Settings > Notifications per app.
unknown
d9788
train
with the dynamically loaded content you just need to juse live bindings. Please use jQuery live events. Suppose contact link has class "clsContact" then you can put dialog opening login in function "OpenModal" and bind links like this: $("a.clsContact").live('click', OpenModal);
unknown
d9789
train
Yes, it's possible in thrust with a single thrust algorithm call (I assume that is what you mean by "without ... doing multiple traversals") and without "allocating a secondary array". One approach would be to pass the data array plus an index/"address" array (via thrust::counting_iterator, which avoids the allocation) to a thrust::transform_iterator which creates your "transform" operation (combined with an appropriate functor). You would then pass the above transform iterator to an appropriate thrust stream compaction algorithm to select the values you want. Here's a possible approach: $ cat t1044.cu #include <thrust/device_vector.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/copy.h> #include <math.h> #include <iostream> __host__ __device__ int my_transform(int data, int idx){ return (data - idx); //put whatever transform you want here } struct my_transform_func : public thrust::unary_function<thrust::tuple<int, int>, int> { __host__ __device__ int operator()(thrust::tuple<int, int> &t){ return my_transform(thrust::get<0>(t), thrust::get<1>(t)); } }; struct my_test_func { __host__ __device__ bool operator()(int data){ return (abs(data) > 5); } }; int main(){ int data[] = {10,-1,-10,2}; int dsize = sizeof(data)/sizeof(int); thrust::device_vector<int> d_data(data, data+dsize); thrust::device_vector<int> d_result(dsize); int rsize = thrust::copy_if(thrust::make_transform_iterator(thrust::make_zip_iterator(thrust::make_tuple(d_data.begin(), thrust::counting_iterator<int>(0))), my_transform_func()), thrust::make_transform_iterator(thrust::make_zip_iterator(thrust::make_tuple(d_data.end(), thrust::counting_iterator<int>(dsize))), my_transform_func()), d_data.begin(), d_result.begin(), my_test_func()) - d_result.begin(); thrust::copy_n(d_result.begin(), rsize, std::ostream_iterator<int>(std::cout, ",")); std::cout << std::endl; return 0; } $ nvcc -o t1044 t1044.cu $ ./t1044 10,-12, $ Some possible criticisms of this approach: * *It would appear to be loading the d_data elements twice (once for the transform operation, once for the stencil). However, it's possible that the CUDA optimizing compiler would recognize the redundant load in the thread code that ultimately gets generated, and optimize it out. *It would appear that we are performing the transform operation on every data element, whether we intend to save it or not in the result. Once again, it's possible that the thrust copy_if implementation may actually defer the data loading operation until after the stencil decision is made. If that were the case, its possible that the transform only gets done on an as-needed basis. Even if it is done always, this may be an insignificant issue, since many thrust operations tend to be load/store or memory bandwidth bound, not compute bound. However an interesting alternate approach could be to use the adaptation created by @m.s. here which creates a transform applied to the output iterator step, which would presumably limit the transform operation to only be performed on the data elements that are actually being saved in the result, although I have not inspected that closely either. *As mentioned in the comment below, this approach does allocate temporary storage (thrust does so under the hood, as part of the copy_if operation) and of course I'm explicitly allocating O(n) storage for the result. I suspect the thrust allocation (a single cudaMalloc) is probably also for O(n) storage. While it may be possible to do all the things asked for (parallel prefix sum, stream compaction, data transformation) with absolutely no extra storage of any kind (so perhaps the request is for an in-place operation), I think that crafting an algorithm that way is likely to have significant negative performance implications, if it is doable at all (it's not clear to me a parallel prefix sum can be realized with absolutely no additional storage of any kind, let alone coupling that with a stream compaction i.e. data movement in parallel). Since thrust frees all such temporary storage it uses, there can't be much of a storage concern associated with frequent use of this method. The only remaining concern (I guess) is performance. If the performance is a concern, then the time overhead associated with the temporary allocations should be mostly eliminated by coupling the above algorithm with a thrust custom allocator (also see here), which would allocate the maximum needed storage buffer once, then re-use that buffer each time the above algorithm is used.
unknown
d9790
train
There was a issue in the PostgreSQL JDBC driver. Building the driver from the lastest PostgreSQL JDBC driver source code returned the correct meta-data for the Stored Procedure. Driver: PostgreSQL 9.4 JDBC4.1 (build 1200) Parameter Name: itemid Paramter Type: 1 Data Type: 4 Parameter Name: id Paramter Type: 5 Data Type: 4 Parameter Name: name Paramter Type: 5 Data Type: 12
unknown
d9791
train
This is what I found after a more specific Google search than just UTF-8 encode/decode. so for those who are looking for a converting library to convert between encodings, here you go. https://github.com/inexorabletash/text-encoding var uint8array = new TextEncoder().encode(str); var str = new TextDecoder(encoding).decode(uint8array); Paste from repo readme All encodings from the Encoding specification are supported: utf-8 ibm866 iso-8859-2 iso-8859-3 iso-8859-4 iso-8859-5 iso-8859-6 iso-8859-7 iso-8859-8 iso-8859-8-i iso-8859-10 iso-8859-13 iso-8859-14 iso-8859-15 iso-8859-16 koi8-r koi8-u macintosh windows-874 windows-1250 windows-1251 windows-1252 windows-1253 windows-1254 windows-1255 windows-1256 windows-1257 windows-1258 x-mac-cyrillic gb18030 hz-gb-2312 big5 euc-jp iso-2022-jp shift_jis euc-kr replacement utf-16be utf-16le x-user-defined (Some encodings may be supported under other names, e.g. ascii, iso-8859-1, etc. See Encoding for additional labels for each encoding.) A: @albert's solution was the closest I think but it can only parse up to 3 byte utf-8 characters function utf8ArrayToStr(array) { var out, i, len, c; var char2, char3; out = ""; len = array.length; i = 0; // XXX: Invalid bytes are ignored while(i < len) { c = array[i++]; if (c >> 7 == 0) { // 0xxx xxxx out += String.fromCharCode(c); continue; } // Invalid starting byte if (c >> 6 == 0x02) { continue; } // #### MULTIBYTE #### // How many bytes left for thus character? var extraLength = null; if (c >> 5 == 0x06) { extraLength = 1; } else if (c >> 4 == 0x0e) { extraLength = 2; } else if (c >> 3 == 0x1e) { extraLength = 3; } else if (c >> 2 == 0x3e) { extraLength = 4; } else if (c >> 1 == 0x7e) { extraLength = 5; } else { continue; } // Do we have enough bytes in our data? if (i+extraLength > len) { var leftovers = array.slice(i-1); // If there is an invalid byte in the leftovers we might want to // continue from there. for (; i < len; i++) if (array[i] >> 6 != 0x02) break; if (i != len) continue; // All leftover bytes are valid. return {result: out, leftovers: leftovers}; } // Remove the UTF-8 prefix from the char (res) var mask = (1 << (8 - extraLength - 1)) - 1, res = c & mask, nextChar, count; for (count = 0; count < extraLength; count++) { nextChar = array[i++]; // Is the char valid multibyte part? if (nextChar >> 6 != 0x02) {break;}; res = (res << 6) | (nextChar & 0x3f); } if (count != extraLength) { i--; continue; } if (res <= 0xffff) { out += String.fromCharCode(res); continue; } res -= 0x10000; var high = ((res >> 10) & 0x3ff) + 0xd800, low = (res & 0x3ff) + 0xdc00; out += String.fromCharCode(high, low); } return {result: out, leftovers: []}; } This returns {result: "parsed string", leftovers: [list of invalid bytes at the end]} in case you are parsing the string in chunks. EDIT: fixed the issue that @unhammer found. A: // String to Utf8 ByteBuffer function strToUTF8(str){ return Uint8Array.from(encodeURIComponent(str).replace(/%(..)/g,(m,v)=>{return String.fromCodePoint(parseInt(v,16))}), c=>c.codePointAt(0)) } // Utf8 ByteArray to string function UTF8toStr(ba){ return decodeURIComponent(ba.reduce((p,c)=>{return p+'%'+c.toString(16),''})) } A: This should work: // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt /* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <[email protected]> * Version: 1.0 * LastModified: Dec 25 1999 * This library is free. You can redistribute it and/or modify it. */ function Utf8ArrayToStr(array) { var out, i, len, c; var char2, char3; out = ""; len = array.length; i = 0; while(i < len) { c = array[i++]; switch(c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += String.fromCharCode(c); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = array[i++]; out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++]; char3 = array[i++]; out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; } } return out; } Check out the JSFiddle demo. Also see the related questions: here and here A: Perhaps using the textDecoder will be sufficient. Not supported in IE though. var decoder = new TextDecoder('utf-8'), decodedMessage; decodedMessage = decoder.decode(message.data); Handling non-UTF8 text In this example, we decode the Russian text "Привет, мир!", which means "Hello, world." In our TextDecoder() constructor, we specify the Windows-1251 character encoding, which is appropriate for Cyrillic script. let win1251decoder = new TextDecoder('windows-1251'); let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]); console.log(win1251decoder.decode(bytes)); // Привет, мир! The interface for the TextDecoder is described here. Retrieving a byte array from a string is equally simpel: const decoder = new TextDecoder(); const encoder = new TextEncoder(); const byteArray = encoder.encode('Größe'); // converted it to a byte array // now we can decode it back to a string if desired console.log(decoder.decode(byteArray)); If you have it in a different encoding then you must compensate for that upon encoding. The parameter in the constructor for the TextEncoder is any one of the valid encodings listed here. A: To answer the original question: here is how you decode utf-8 in javascript: http://ecmanaut.blogspot.ca/2006/07/encoding-decoding-utf8-in-javascript.html Specifically, function encode_utf8(s) { return unescape(encodeURIComponent(s)); } function decode_utf8(s) { return decodeURIComponent(escape(s)); } We have been using this in our production code for 6 years, and it has worked flawlessly. Note, however, that escape() and unescape() are deprecated. See this. A: Update @Albert's answer adding condition for emoji. function Utf8ArrayToStr(array) { var out, i, len, c; var char2, char3, char4; out = ""; len = array.length; i = 0; while(i < len) { c = array[i++]; switch(c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += String.fromCharCode(c); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = array[i++]; out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++]; char3 = array[i++]; out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; case 15: // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx char2 = array[i++]; char3 = array[i++]; char4 = array[i++]; out += String.fromCodePoint(((c & 0x07) << 18) | ((char2 & 0x3F) << 12) | ((char3 & 0x3F) << 6) | (char4 & 0x3F)); break; } return out; } A: Here is a solution handling all Unicode code points include upper (4 byte) values and supported by all modern browsers (IE and others > 5.5). It uses decodeURIComponent(), but NOT the deprecated escape/unescape functions: function utf8_to_str(a) { for(var i=0, s=''; i<a.length; i++) { var h = a[i].toString(16) if(h.length < 2) h = '0' + h s += '%' + h } return decodeURIComponent(s) } Tested and available on GitHub To create UTF-8 from a string: function utf8_from_str(s) { for(var i=0, enc = encodeURIComponent(s), a = []; i < enc.length;) { if(enc[i] === '%') { a.push(parseInt(enc.substr(i+1, 2), 16)) i += 3 } else { a.push(enc.charCodeAt(i++)) } } return a } Tested and available on GitHub A: Using my 1.6KB library, you can do ToString(FromUTF8(Array.from(usernameReceived))) A: This is a solution with extensive error reporting. It would take an UTF-8 encoded byte array (where byte array is represented as array of numbers and each number is an integer between 0 and 255 inclusive) and will produce a JavaScript string of Unicode characters. function getNextByte(value, startByteIndex, startBitsStr, additional, index) { if (index >= value.length) { var startByte = value[startByteIndex]; throw new Error("Invalid UTF-8 sequence. Byte " + startByteIndex + " with value " + startByte + " (" + String.fromCharCode(startByte) + "; binary: " + toBinary(startByte) + ") starts with " + startBitsStr + " in binary and thus requires " + additional + " bytes after it, but we only have " + (value.length - startByteIndex) + "."); } var byteValue = value[index]; checkNextByteFormat(value, startByteIndex, startBitsStr, additional, index); return byteValue; } function checkNextByteFormat(value, startByteIndex, startBitsStr, additional, index) { if ((value[index] & 0xC0) != 0x80) { var startByte = value[startByteIndex]; var wrongByte = value[index]; throw new Error("Invalid UTF-8 byte sequence. Byte " + startByteIndex + " with value " + startByte + " (" +String.fromCharCode(startByte) + "; binary: " + toBinary(startByte) + ") starts with " + startBitsStr + " in binary and thus requires " + additional + " additional bytes, each of which shouls start with 10 in binary." + " However byte " + (index - startByteIndex) + " after it with value " + wrongByte + " (" + String.fromCharCode(wrongByte) + "; binary: " + toBinary(wrongByte) +") does not start with 10 in binary."); } } function fromUtf8 (str) { var value = []; var destIndex = 0; for (var index = 0; index < str.length; index++) { var code = str.charCodeAt(index); if (code <= 0x7F) { value[destIndex++] = code; } else if (code <= 0x7FF) { value[destIndex++] = ((code >> 6 ) & 0x1F) | 0xC0; value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80; } else if (code <= 0xFFFF) { value[destIndex++] = ((code >> 12) & 0x0F) | 0xE0; value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80; value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80; } else if (code <= 0x1FFFFF) { value[destIndex++] = ((code >> 18) & 0x07) | 0xF0; value[destIndex++] = ((code >> 12) & 0x3F) | 0x80; value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80; value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80; } else if (code <= 0x03FFFFFF) { value[destIndex++] = ((code >> 24) & 0x03) | 0xF0; value[destIndex++] = ((code >> 18) & 0x3F) | 0x80; value[destIndex++] = ((code >> 12) & 0x3F) | 0x80; value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80; value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80; } else if (code <= 0x7FFFFFFF) { value[destIndex++] = ((code >> 30) & 0x01) | 0xFC; value[destIndex++] = ((code >> 24) & 0x3F) | 0x80; value[destIndex++] = ((code >> 18) & 0x3F) | 0x80; value[destIndex++] = ((code >> 12) & 0x3F) | 0x80; value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80; value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80; } else { throw new Error("Unsupported Unicode character \"" + str.charAt(index) + "\" with code " + code + " (binary: " + toBinary(code) + ") at index " + index + ". Cannot represent it as UTF-8 byte sequence."); } } return value; } A: You should take decodeURI for it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI As simple as this: decodeURI('https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B'); // "https://developer.mozilla.org/ru/docs/JavaScript_шеллы" Consider to use it inside try catch block for not missing an URIError. Also it has full browsers support. A: const decoder = new TextDecoder(); console.log(decoder.decode(new Uint8Array([97]))); MDN resource link A: I reckon the easiest way would be to use a built-in js functions decodeURI() / encodeURI(). function (usernameSent) { var usernameEncoded = usernameSent; // Current value: utf8 var usernameDecoded = decodeURI(usernameReceived); // Decoded // do stuff } A: Preferably, as others have suggested, use the Encoding API. But if you need to support IE (for some strange reason) MDN recommends this repo FastestSmallestTextEncoderDecoder If you need to make use of the polyfill library: import {encode, decode} from "fastestsmallesttextencoderdecoder"; Then (regardless of the polyfill) for encoding and decoding: // takes in USVString and returns a Uint8Array object const encoded = new TextEncoder().encode('€') console.log(encoded); // takes in an ArrayBuffer or an ArrayBufferView and returns a DOMString const decoded = new TextDecoder().decode(encoded); console.log(decoded); A: I searched for a simple solution and this works well for me: //input data view = new Uint8Array(data); //output string serialString = ua2text(view); //convert UTF8 to string function ua2text(ua) { s = ""; for (var i = 0; i < ua.length; i++) { s += String.fromCharCode(ua[i]); } return s; } Only issue I have is sometimes I get one character at a time. This might be by design with my source of the arraybuffer. I'm using https://github.com/xseignard/cordovarduino to read serial data on an android device.
unknown
d9792
train
Try replacing all of your setup code with this: // get the url as moveURL self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL]; self.moviePlayer.view.frame = self.view.bounds; [self.view addSubview:self.moviePlayer.view]; [self.moviePlayer prepareToPlay]; // notice what notification we subscribe to... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerLoadStateChanged:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil]; Log state changes in moviePlayerLoadStateChanged:. If that doesn't work, it's probably the url that's the problem.
unknown
d9793
train
OpenRasta was built for resource-oriented scenarios. You can achieve the same thing with any other frameworks (with more or less pain). OpenRasta gives you a fully-composited, IoC friendly environment that completely decouples handlers and whatever renders them (which makes it different from MVC frameworks like nancy and MVC). I'd add that we have a very strong community, a stable codebase and we've been in this for quite a few years, we're building 2.1 and 3.0 and our featureset is still above and beyond what you can get from most other systems. Compare this to most of the frameworks you've highlighted, where none have reached 1.0. Professional support is also available, if that's a deciding factor for your company. But to answer your question fully, depending on your scenario and what you want to achieve, you can make anything fits, given enough work. I'd suggest reformulating your question in terms of architecture rather than in terms of frameworks.
unknown
d9794
train
>> and << are the right and left bit shift operators, respectively. You should look at the binary representation of the numbers. >>> bin(100) '0b1100100' >>> bin(12) '0b1100' A: The other answers explain the idea of bitshifting, but here's specifically what happens for 100>>3 100 128 64 32 16 8 4 2 1 0 1 1 0 0 1 0 0 = 100 100 >> 1 128 64 32 16 8 4 2 1 0 0 1 1 0 0 1 0 = 50 100 >> 2 128 64 32 16 8 4 2 1 0 0 0 1 1 0 0 1 = 25 100 >> 3 128 64 32 16 8 4 2 1 0 0 0 0 1 1 0 0 = 12 You won't often need to use it, unless you need some really quick division by 2, but even then, DON'T USE IT. it makes the code much more complicated then it needs to be, and the speed difference is unnoticeable. The main time you'd ever need to use it would be if you're working with binary data, and you specifically need to shift the bits around. The only real use I've had for it was reading & writing ID3 tags, which stores size information in 7-bit bytes, like so: 0xxxxxxx 0xxxxxxx 0xxxxxxx 0xxxxxxx. which would need to be put together like this: 0000xxxx xxxxxxxx xxxxxxxx xxxxxxxx to give a normal integer in memory. A: Right shift is not division Let's look at what right-shift actually does, and it will become clear. First, recall that a number is stored in memory as a collection of binary digits. If we have 8 bits of memory, we can store 2 as 00000010 and 5 as 00000101. Right-shift takes those digits and shifts them to the right. For example, right-shifting our above two digits by one will give 00000001 and 00000010 respectively. Notice that the lowest digit (right-most) is shifted off the end entirely and has no effect on the final result. A: Bit shifting an integer gives another integer. For instance, the number 12 is written in binary as 0b1100. If we bit shift by 1 to the right, we get 0b110 = 6. If we bit shift by 2, we get 0b11 = 3. And lastly, if we bitshift by 3, we get 0b1 = 1 rather than 1.5. This is because the bits that are shifted beyond the register are lost. One easy way to think of it is bitshifting to the right by N is the same as dividing by 2^N and then truncating the result. A: I have read the answers above and just wanted to add a little bit more practical example, that I had seen before. Let us assume, that you want to create a list of powers of two. So, you can do this using left shift: n = 10 list_ = [1<<i for i in range(1, n+1)] # Where n is a maximum power. print(list_) # Output: [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] You can timeit it if you want, but I am pretty sure, that the code above is one the fastest solutions for this problem. But what I cannot understand is when you can use right shift.
unknown
d9795
train
At the moment you read one line and then close the result. You need to loop through the results reading and processing one line at a time and then only once you are done close the result.
unknown
d9796
train
I think it depends on the state of the User table - the way you have it now there will be a User table and a Employee table and a One to One relationship. If you want it so that both the Employee and Employer Table includes an 'age' attribute you have to make the User table abstract. https://docs.djangoproject.com/en/3.1/topics/db/models/#model-inheritance The way to do this is : class User(AbstractUser): class Meta: abstract = True age=models.BooleanField(default=True) Even though you have inherited from Abstract User, I wouldn't assume that the Meta settings are inherited.
unknown
d9797
train
BigInteger has a constructor taking a byte array as argument. Any String can be converted to a byte array, without loss, using (for example), UTF-8 encoding: byte[] bytes = string.getBytes(StandardCharsets.UTF_8); Combine both, and you have an easy way to transform a String into a BigDecimal. For the reverse operation, use BigInteger.toByteArray(), and then new String(bytes, StandardCharsets.UTF_8).
unknown
d9798
train
Eclipse > Right-click project > Properties > Java Compiler > Compiler compliance level > 1.6
unknown
d9799
train
From the autoscalers documentation, the property autoscalingPolicy.loadBalancingUtilization.utilizationTarget is only for setting an HTTP(S) load balancer. If this is not the case, you should remove it from your query and the error will disappear.
unknown
d9800
train
np.transpose() picks the dimensions you specify in the order you specify. In your first case, your array shape is (1,2,3) i.e. in dimension->value format, it is 0 -> 1, 1 -> 2 and 2 -> 3. In np.transpose(), you're requesting for the order 0,2,1 which is 1,3,2. In the second case, your array shape is (4,2,3) i.e. in dimension->value format, it is 0 -> 4, 1 -> 2 and 2 -> 3. In np.transpose(), you're requesting for the order 2,0,1 which is 3,4,2.
unknown