id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_1700
So far, I have: LDWA 0xFFFF, i DECO 0xFFFF, i LDBA 0xFC15, d STWA 0x001D, d STBA 0xFC16, d LDWA 0x001D, d SUBA 0x001F, d ORA 0x0021, d STBA 0xFC16, d STOP .BLOCK 2 .WORD 20 .WORD 0x0020 .END Whenever I run it with my input, it instead adds 20h instead of subtracting 20h to make the ASCII character uppercase. Any pointers? A: Re-jigging your code with addresses (and some comments) makes it a little easier to figure out potential problems: 0000 LDWA 0xFFFF, i ; set A to -1, why? 0003 DECO 0xFFFF, i ; decimal output -1 0006 LDBA 0xFC15, d ; get input character 0009 STWA 0x001D, d ; store to variable 000c STBA 0xFC16, d ; output character 000f LDWA 0x001D, d ; get character back 0012 SUBA 0x001F, d ; presumably subtract 0x20 0015 ORA 0x0021, d ; not sure what this intends 0018 STBA 0xFC16, d 001b STOP ; 1-byte operation 001c .BLOCK 2 ; two arbitrary bytes. 001e .WORD 20 ; takes two bytes 0x0014 0020 .WORD 0x0020 ; 0x0020 .END Based on that, you appear to have used the wrong addresses for direct storage and retrieval, possibly because you think STOP is a two-byte operation but I can't be sure. Going forward, you should be able to get rid of superfluous code and ensure you only uppercase lowercase letters by only acting on the range (inclusive) a..z. Something like this would be a good start: asc_a: .equate 0x0061 ; Lower case A. asc_z: .equate 0x007a ; Lower case Z. sub_val: .equate 0x0020 ; Difference from upper to lower. in_char: .equate 0xfc15 ; Address to get char from user. out_char: .equate 0xfc16 ; Address to put char to user. main: deco 0xffff,i ; Decimal output -1. ldba in_char,d ; Get input character. cpwa asc_a,i ; If outside a..z, do not translate. brlt no_xlat cpwa asc_z,i brgt no_xlat suba sub_val,i ; Convert to upper (61..7a -> 41..5a). no_xlat: stba out_char,d ; Output character. stop You'll see there that we don't actually need data storage since we can just use immediate operands for constants and the accumulator for the character itself. If you do need data storage, I would tend to place it at a fixed location so that code changes do not affect it, something like: 0000 start: br main 0003 some_data: .block 0x20 0023 more_data: .word 0xdead 0026 more_data: .word 0xbeef 0029 main: <<Code goes here>> That way, no changes to the code affect your variables, something that will be quite handy if you have to hand-code your stuff rather than relying on a decent assembler that can work out the symbols automatically.
doc_1701
Now I would like to include these files in my project, so in VS2012 I have marked my project and click the "Show All Files" button. I can see that the button is pressed, but my files are not showing up in my SSIS Packages folder (or anywhere else for that matter). I know that I can manually move the files outside my project and the "Add existing item" and add the files in that way. And that would be fine if it was only this one time. But my problem is that we are two developers working on the project. And everytime the other developer adds a file, I have to do this manually. Anyone who has an idea on how to fix this?
doc_1702
I am trying to add entries to a dictionary which contains {user : password, user2 : password2} for any new users. This is not to be registered to as only an admin should be able to add users. This is where the other program idea came into play. But I am open to any solution! A: If you want to achieve this using functions, you can use the dict.update function. def combine_dicts(x, y): x.update(y) return x def get_passwords(): dict = {"a":"test", "b":"testa"} return dict firstDict = {"this":"is", "a":"test"} secondDict = get_passwords() combinedDict = combine_dicts(firstDict, secondDict) Note: The parameter you use of dict.update() will override existing value/key pairs.
doc_1703
Python Code for remote access: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") assert "Python" in driver.title elem = driver.find_element_by_class_name("q") Local HTML Code: s = "<body> <p>This is a test</p> <p class="q">This is a second test</p> </body>" A: Here was my solution for doing basic generated tests without having to make lots of temporary local files. import json from selenium import webdriver driver = webdriver.PhantomJS() # or your browser of choice html = '''<div>Some HTML</div>''' driver.execute_script("document.write('{}')".format(json.dumps(html))) # your tests A: If you don't want to create a file or load a URL before being able to replace the content of the page, you can always leverage the Data URLs feature, which supports HTML, CSS and JavaScript: from selenium import webdriver driver = webdriver.Chrome() html_content = """ <html> <head></head> <body> <div> Hello World =) </div> </body> </html> """ driver.get("data:text/html;charset=utf-8,{html_content}".format(html_content=html_content)) A: If I understand the question correctly, I can imagine 2 ways to do this: * *Save HTML code as file, and load it as url file:///file/location. The problem with that is that location of file and how file is loaded by a browser may differ for various OSs / browsers. But implementation is very simple on the other hand. *Another option is to inject your code onto some page, and then work with it as a regular dynamic HTML. I think this is more reliable, but also more work. This question has a good example. A: If I am reading correctly you are simply trying to get text from an element. If that is the case then the following bit should fit your needs: elem = driver.find_element_by_class_name("q").text print elem Assuming "q" is the element you need.
doc_1704
So, if I have these models: public MyModel { public int Id {get; set;} public string RecordName {get; set;} public ChildModel MyChild {get; set;} } public ChildModel { public int ChildModelId {get; set;} public DateTime SavedDate {get; set;} } I can sort two ways: myList.OrderByField("RecordName "); myList.OrderByField("MyChild.SavedDate"); However, if my object has an ICollection property, like ICollection<ChildModel> MyChildren I can hard code my sort like this: myList .OrderBy(m => m.MyChildren .OrderByDescending(c => c.SavedDate).FirstOrDefault().SavedDate); And get what I want. My question is, how can I update my extension method to allow to get the same results with this: myList.OrderByField("MyChildren.SavedDate"); Here is my current extension: public static class MkpExtensions { public static IEnumerable<T> OrderByField<T>(this IEnumerable<T> list, string sortExpression) { sortExpression += ""; string[] parts = sortExpression.Split(' '); bool descending = false; string fullProperty = ""; if (parts.Length > 0 && parts[0] != "") { fullProperty = parts[0]; if (parts.Length > 1) { descending = parts[1].ToLower().Contains("esc"); } ParameterExpression inputParameter = Expression.Parameter(typeof(T), "p"); Expression propertyGetter = inputParameter; foreach (string propertyPart in fullProperty.Split('.')) { PropertyInfo prop = propertyGetter.Type.GetProperty(propertyPart); if (prop == null) throw new Exception("No property '" + fullProperty + "' in + " + propertyGetter.Type.Name + "'"); propertyGetter = Expression.Property(propertyGetter, prop); } Expression conversion = Expression.Convert(propertyGetter, typeof(object)); var getter = Expression.Lambda<Func<T, object>>(conversion, inputParameter).Compile(); if (descending) return list.OrderByDescending(getter); else return list.OrderBy(getter); } return list; } } I was thinking of checking the type of the prop and doing an if... else statement, but I'm not sure. Maybe something like this: foreach (string propertyPart in fullProperty.Split('.')) { var checkIfCollection = propertyGetter.Type.GetInterfaces()//(typeof (ICollection<>).FullName); .Any(x => x.IsGenericType && (x.GetGenericTypeDefinition() == typeof(ICollection<>) || x.GetGenericTypeDefinition() == typeof(IEnumerable<>))); if (checkIfCollection) { // Can I get this to do something like // myList.OrderBy(m => m.MyChildren.Max(c => c.SavedDate)); // So far, I can get the propertyGetter type, and the type of the elements: var pgType = propertyGetter.Type; var childType = pgType.GetGenericArguments().Single(); // Now I want to build the expression tree to get the max Expression left = Expression.Call(propertyGetter, pgType.GetMethod("Max", System.Type.EmptyTypes)); // But pgType.GetMethod isn't working } else { PropertyInfo prop = propertyGetter.Type.GetProperty(propertyPart); if (prop == null) throw new Exception("No property '" + fullProperty + "' in + " + propertyGetter.Type.Name + "'"); propertyGetter = Expression.Property(propertyGetter, prop); } } A: The Max function is an extension method, not a member method of IEnumerable or ICollection. You must call it from it's class Enumerable. Here is an example of how to call Max through expression tree: IEnumerable<int> list = new List<int> { 3, 5, 7, 2, 12, 1 }; var type = typeof(Enumerable); //This is the static class that contains Max //Find The overload of Max that matches the list var maxMethod = type.GetMethod("Max", new Type[] { typeof(IEnumerable<int>) }); ParameterExpression p = Expression.Parameter(typeof(IEnumerable<int>)); //Max is static, so the calling object is null var exp = Expression.Call(null, maxMethod, p); var lambda = Expression.Lambda<Func<IEnumerable<int>, int>>(exp, p); Console.WriteLine(lambda.Compile()(list));
doc_1705
We've been excited by standardized localeformatting from the Javascript i18n library, but it looks like the default formatting is the first example above and is therefore not accessible in VoiceOver: var number = -5; number.toLocaleString('en-CA', {style: 'currency', currency: 'CAD'}); // "-$5.00" // needs to be "$−5.00" var number = -5; number.toLocaleString('fr-CA', {style: 'currency', currency: 'CAD'}); // "-5,00 $" // needs to be "−5,00 $" Both those strings are read in VO as "5 dollars" unless the dash is replaced with the unicode minus symbol after the fact. I am writing a function to do that after the fact, but it feels messy, especially to try and account for every scenario. Furthermore in english, we need to transpose the $ and −. Not to mention what happens when we need to support other locales. Is there a way to provide that option to localeString so that it is accessible out of the box? I'm wondering if there are other approaches that might be more manageable in a large codebase to ensure data is accessible
doc_1706
I know that I can send the same message to a list of emails, but what I need is to send one text to certain recipients and other text to other list of emails. I need this because my message contains approval information (which should only be seen by an admin) and I need to sent at the same time other mail just for telling the user "your request have been sent and will be reviewed". Is there a function in mail() that can do this? A: -As requested- Unfortunately, PHP's mail() function can only handle this by using seperate mail() functions. You can send the same email to multiple recipients at the same time, but to send two different messages (and two different subjects) intended for two different recipients requires using two different mail() functions, along with two different sets of recipients/subjects/messages/headers. For example: /* send to 1st recipient */ $to_1 = "[email protected]"; $from = "[email protected]"; $subject_1 = "Subject for recipient 1"; $message_1 = "Message to recipient 1"; $headers_1 = 'From: ' . $from . "\r\n"; $headers_1 .= "MIME-Version: 1.0" . "\r\n"; $headers_1 .= "Content-type:text/html;charset=utf-8" . "\r\n"; mail($to_1, $subject_1, $message_1, $headers_1); /* send to 2nd recipient */ $to_2 = "[email protected]"; $from = "[email protected]"; $subject_2 = "Subject for recipient 2"; $message_2 = "Message to recipient 2"; $headers_2 = 'From: ' . $from . "\r\n"; $headers_2 .= "MIME-Version: 1.0" . "\r\n"; $headers_2 .= "Content-type:text/html;charset=utf-8" . "\r\n"; mail($to_2, $subject_2, $message_2, $headers_2); A: Just like this. <?php //first mail //// $to = '[email protected]'; $subject = 'the subject'; $message = '1st Message'; $headers = 'From: [email protected]' . "\r\n" . 'Reply-To: [email protected]' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); //second mail //// $to = '[email protected]'; $subject = 'the subject'; $message = '2nd Message'; $headers = 'From: [email protected]' . "\r\n" . 'Reply-To: [email protected]' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); ?>
doc_1707
There is no "Affects Me too" button anywhere on github. For e.g. how do I express my concern on this page without adding any comment. https://github.com/pandas-dev/pandas/issues/21621 Writing a "Me too" comment does not add any value to bug report. Right? A: There is an "add reaction emoji" button at top right; if anyone did so, it appears at the bottom of that comment, and you can click the emoji to add yourself to it too. In particular, adding a thumbs up reaction is a common way to say "me too".
doc_1708
How can i do this? Thanks, Vara Prasad.M A: You can try it your self: http://www.ryancooper.com/resources/keycode.asp Still remember that I don't think the actual behavior will change (so I you press F1 you might detect that but in IE still the help file will open). So take inot acount the usefullness/useability of your solution. A: You can do it if you write a plugin like ActiveX, Flash or Silverlight. Depending on the install the user will still have to grant permission to run executables. A: It's a crazy idea. The F keys already have functions native to the browser, in IE for example: * *F1 – opens the browser’s Help page *F3 – opens the browser’s Find function *F4 – drops down the browser’s address bar history *F5 – refresh page *F6 – puts focus into the address bar *F7 – allows you to turn carat browsing off/on (whatever that is!) *F10 – goes to the File menu *F11 – toggles full screen *F12 – toggles the Developer Tools Even if you detect keystrokes the browser will still perform its native function.
doc_1709
I guess there is a kernel module behind smp_affinity, however, ls tells me it is a normal file: # ls -rw-r--r-- 1 root root 0 Feb 9 16:06 smp_affinity So I wonder, what kind of file /proc/irq/<irqid>/smp_affinity is? A: Read about procfs - https://man7.org/linux/man-pages/man5/procfs.5.html https://en.wikipedia.org/wiki/Procfs etc. smp_affinity is a file inside /proc filesystem. File operation on that file are handled specially by the kernel. Writing or reading - instead of storing or retrieving the data using some non-volatile medium - the kernel executes special function with special semantics instead. The file would be created somewhere in kernel/irq/proc.c.
doc_1710
I'm using Eclipse Luna 4.4.2. I created a new test project that contains only the following class: package org.example; import javax.annotation.Nonnull; public class OmgNulls { public static void main(String[] args) { @Nonnull String test = null; System.out.println(test); } } My compiler settings are configured to use the javax annotations: My project's includes the checker-1.8.10 JAR to provide the annotations. With these settings, Eclipse reports 0 errors. If I check "Use default annotations for null specifications" and change my test class to use Eclipse's annotation, I get: Anyone know what I'm doing wrong or is this an Eclipse bug maybe? I've also tried the jsr305 JAR from google instead of checker in case that was an issue but that didn't help.
doc_1711
i want to save temperature data ( which i get from a paho client) in an array named 'single'. Finally, i want to show the live data in a gauge. For this i created a service to store the data and to hand out the data to several components. But i get only the ERR: "" is not assignable to parameter of type '{ value: string; }'. I would really appreciate some new thoughts on this! Thanks! My Service: import { Injectable } from '@angular/core'; import { Component, OnInit } from '@angular/core'; import {Paho} from '../../../node_modules/ng2-mqtt/mqttws31'; @Injectable() export class ClassdataproviderService { public name: string; public value: string; single = [ { name: 'eins', value: '15' }, { name: 'zwei', value: '20' }, { name: 'drei', value: '73' } ]; // Create a client instance client: any; packet: any; constructor() { this.client = new Paho.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080, 'Steffen'); this.onMessage(); this.onConnectionLost(); // connect the client this.client.connect({onSuccess: this.onConnected.bind(this)}); } // called when the client connects onConnected() { console.log('Connected'); this.client.subscribe('node/m1/temperature'); //this.sendMessage('HelloWorld'); } sendMessage(message: string) { const packet = new Paho.MQTT.Message(message); packet.destinationName = 'World'; this.client.send(packet); } // called when a message arrives onMessage() { this.client.onMessageArrived = (message: Paho.MQTT.Message) => { console.log('Message arrived : ' + message.payloadString); this.single.push('test', message.payloadString); **//<-- Here i want to push the data in my array** }; } // called when the client loses its connection onConnectionLost() { this.client.onConnectionLost = (responseObject: Object) => { console.log('Connection lost : ' + JSON.stringify(responseObject)); }; } A: I solved the problem. You just have to push the data in the array(single) by using this line in the onMessageArrived function: this.single.push({name: 'test', value: message.payloadString});
doc_1712
My idea for the code is.. But my formatting is wrong. Thank you! while True: if datetime == HH:MM:00 print format(datetime.datetime.now()) else wait A: Time till the end of the current minute can be computed: while True: now = datetime.datetime.now() time.sleep(60.0 - now.second - now.microsecond / 1e6) # do the work
doc_1713
{-# LANGUAGE OverloadedStrings #-} import Control.Monad.IO.Class (liftIO) import Data.Conduit import qualified Data.Conduit.List as CL import qualified Data.ByteString.Char8 as BS import Data.Attoparsec.Char8 main = (CL.sourceList [BS.pack "foo", BS.pack "bar"]) $$ sink -- endless loop -- this works: -- main = (CL.sourceList [BS.pack "foobar"]) $$ sink sink :: Sink BS.ByteString IO () sink = awaitForever $ \str -> do liftIO $ putStrLn $ BS.unpack str -- debug, will print foo forever. case (parse (string "foobar") str) of Fail _ _ _ -> do liftIO $ putStr $ "f: " ++ BS.unpack str sink Partial _ -> do leftover str sink Done rest final -> do liftIO $ putStr $ "d: " ++ show final ++ " // " ++ show rest sink A: The idea of "Partial" is that it returns you a continuation function; that is, once you have more input you call the continuation with that input. Trying to push the leftover lines back on to the input stream is wasteful at best, because you repeatedly parse the first bit of input. You need to write your function to take a parser function as a parameter. Then your Partial case should read Partial c -> sink c That will cause "sink" to wait for more input and then hand it to the "c" function, which will continue parsing the new input from where it left off. A: Keep in mind that Conduit has no concept of concatenating output. So what happens is: * *The conduit gets a partial input. *It's not enough to parse. *You put it back as a leftover. *The conduit reads again the same you put back. *And this goes forever. If you really want to pursue the direction of repeatedly trying the parser, you need to ensure that each time you put a leftover value back it's larger than the previous time. So you'd do something like this: If the parser doesn't finish, read additional input, concatenate it with the input you already have, push this back as a leftover and try again. Note that the above procedure has complexity O(n^2), which will be particularly problematic if your parser succeeds after consuming a big block of data. If you'll be receiving one character at a time (which might happen) and the parser needs to consume 1000 characters, you'll get something like 500000 processing steps. So I'd strongly suggest using either the provided binding between Conduit and Attoparsec, or, if you want to do it yourself, properly use the continuation provided by Partial.
doc_1714
auto set_a=generateSet(nelements1); //generateSet calls rand auto set_b=generateSet(nelements2); //so set_b is determined by the previous line :( So this is what I came up with: (note that this isnt thread safe, it is designed to be safe in a way that calls to generateSet dont affect eachother(through changing state of rand internal value)) template<typename container_type,typename element_type > class RandElemGetter { const container_type& containter_ref; std::uniform_int_distribution<size_t> distribution; std::mt19937 engine; public: RandElemGetter(container_type& container): containter_ref(container),distribution(0,container.size()-1) { } element_type get() { return containter_ref[distribution(engine)]; } }; usage : { vector<int> v{1,2,3,1701,1729}; vector<int> result; RandElemGetter<vector<int>,int> reg_v(v); for(size_t i=0;i<nelements;++i) result.push_back(reg_v.get()); } So is this OK solution? I know it is not thread safe, that is not the point. Im wondering is there better "scoped" way of getting random element from random access container. It could be modified maybe with std::advance to work for all. A: RandElemGetter(container_type container): containter_ref(container),distribution(0,container.size()-1) This takes the container by value, creating a temporary copy, and stores a reference to that copy. The reference is invalid once the constructor has finished. You need to either store a copy, or pass the argument by reference. It's a good idea to pass complex objects by constant reference anyway, to avoid unnecessary copying. A: * *I would use <typename container_type, typename value_type = container_type::typename value_type>. STL containers have typedefs for their value_types, so there's usually no need to repeat yourself. *The correct solution is indeed to return *std::advance(containter_ref.begin(), distribution(engine)); *I'd rename get() to operator(), and provide a result_type typedef to comply with the STL model AdaptableGenerator You might want to have a peak at SGI's random_sample from the original STL; I believe GNU still has that as an extension.
doc_1715
In a Ruby script that would be: #!/usr/bin/env ruby puts "Has -h" if ARGV.include? "-h" How to best do that in Bash? A: The simplest solution would be: if [[ " $@ " =~ " -h " ]]; then echo "Has -h" fi A: #!/bin/bash while getopts h x; do echo "has -h"; done; OPTIND=0 As Jonathan Leffler pointed out OPTIND=0 will reset the getopts list. That's in case the test needs to be done more than once. A: It is modestly complex. The quickest way is also unreliable: case "$*" in (*-h*) echo "Has -h";; esac Unfortunately that will also spot "command this-here" as having "-h". Normally you'd use getopts to parse for arguments that you expect: while getopts habcf: opt do case "$opt" in (h) echo "Has -h";; ([abc]) echo "Got -$opt";; (f) echo "File: $OPTARG";; esac done shift (($OPTIND - 1)) # General (non-option) arguments are now in "$@" Etc. A: I'm trying to solve this in a straightforward but correct manner, and am just sharing what works for me. The dedicated function below solves it, which you can use like so: if [ "$(has_arg "-h" "$@")" = true ]; then # TODO: code if "-h" in arguments else # TODO: code if "-h" not in arguments fi This function checks whether the first argument is in all other arguments: function has_arg() { ARG="$1" shift while [[ "$#" -gt 0 ]]; do if [ "$ARG" = "$1" ]; then echo true return else shift fi done echo false }
doc_1716
@Scripts.Render("~/Scripts/jQuery") What's the best way to do so? A: Here is one way: <script> if (!window.jQuery) { document.write('<script src="@BundleTable.Bundles.ResolveBundleUrl("~/Scripts/jQuery")">\x3C/script>'); } </script> This is essentially the same logic used when one includes jQuery from a CDN, and then has a local reference fallback if the CDN delivery failed.
doc_1717
A: The important part is "will be inferred from the right-hand side" [of the assignment]. You only need to specify a type when declaring but not assigning a variable, or if you want the type to be different than what's inferred. Otherwise, the variable's type will be the same as that of the right-hand side of the assignment. // s and t are strings s := "this is a string" // this form isn't needed inside a function body, but works the same. var t = "this is another string" // x is a *big.Int x := big.NewInt(0) // e is a nil error interface // we specify the type, because there's no assignment var e error // resp is an *http.Response, and err is an error resp, err := http.Get("http://example.com") Outside of a function body at the global scope, you can't use :=, but the same type inference still applies var s = "this is still a string" The last case is where you want the variable to have a different type than what's inferred. // we want x to be an uint64 even though the literal would be // inferred as an int var x uint64 = 3 // though we would do the same with a type conversion x := uint64(3) // Taken from the http package, we want the DefaultTransport // to be a RoundTripper interface that contains a Transport var DefaultTransport RoundTripper = &Transport{ ... }
doc_1718
"Hi {name}, do you like milk?" How could I replace the {name} by code, Regular expressions? To expensive? Which way do you recommend? How do they in example NHibernates HQL to replace :my_param to the user defined value? Or in ASP.NET (MVC) Routing that I like better, "{controller}/{action}", new { controller = "Hello", ... }? A: Now if you have you replacements in a dictionary, like this: var replacements = new Dictionary<string, string>(); replacements["name"] = "Mike"; replacements["age"]= "20"; then the Regex becomes quite simple: Regex regex = new Regex(@"\{(?<key>\w+)\}"); string formattext = "{name} is {age} years old"; string newStr = regex.Replace(formattext, match=>replacements[match.Groups[1].Captures[0].Value]); A: Have you confirmed that regular expressions are too expensive? The cost of regular expressions is greatly exaggerated. For such a simple pattern performance will be quite good, probably only slightly less good than direct search-and-replace, in fact. Also, have you experimented with the Compiled flag when constructing the regular expression? That said, can't you just use the simplest way, i.e. Replace? string varname = "name"; string pattern = "{" + varname + "}"; Console.WriteLine("Hi {name}".Replace(pattern, "Mike")); A: After thinking about this, I realized what I actually wished for, was that String.Format() would take an IDictionary as argument, and that templates could be written using names instead of indexes. For string substitutions with lots of possible keys/values, the index numbers result in illegible string templates - and in some cases, you may not even know which items are going to have what number, so I came up with the following extension: https://gist.github.com/896724 Basically this lets you use string templates with names instead of numbers, and a dictionary instead of an array, and lets you have all the other good features of String.Format(), allowing the use of a custom IFormatProvider, if needed, and allowing the use of all the usual formatting syntax - precision, length, etc. The example provided in the reference material for String.Format is a great example of how templates with many numbered items become completely illegible - porting that example to use this new extension method, you get something like this: var replacements = new Dictionary<String, object>() { { "date1", new DateTime(2009, 7, 1) }, { "hiTime", new TimeSpan(14, 17, 32) }, { "hiTemp", 62.1m }, { "loTime", new TimeSpan(3, 16, 10) }, { "loTemp", 54.8m } }; var template = "Temperature on {date1:d}:\n{hiTime,11}: {hiTemp} degrees (hi)\n{loTime,11}: {loTemp} degrees (lo)"; var result = template.Subtitute(replacements); As someone pointed out, if what you're writing needs to be highly optimized, don't use something like this - if you have to format millions of strings this way, in a loop, the memory and performance overhead could be significant. On the other hand, if you're concerned about writing legible, maintainable code - and if you're doing, say, a bunch of database operations, in the grand scheme of things, this function will not add any significant overhead. ... For convenience, I did attempt to add a method that would accept an anonymous object instead of a dictionary: public static String Substitute(this String template, object obj) { return Substitute( template, obj.GetType().GetProperties().ToDictionary(p => p.Name, p => p.GetValue(obj, null)) ); } For some reason, this doesn't work - passing an anonymous object like new { name: "value" } to that extension method gives a compile-time error message saying the best match was the IDictionary version of that method. Not sure how to fix that. (anyone?) A: Regex is certainly a viable option, especially with a MatchEvaluator: Regex re = new Regex(@"\{(\w*?)\}", RegexOptions.Compiled); // store this... string input = "Hi {name}, do you like {food}?"; Dictionary<string, string> vals = new Dictionary<string, string>(); vals.Add("name", "Fred"); vals.Add("food", "milk"); string q = re.Replace(input, delegate(Match match) { string key = match.Groups[1].Value; return vals[key]; }); A: How about stringVar = "Hello, {0}. How are you doing?"; arg1 = "John"; // or args[0] String.Format(stringVar, arg1) You can even have multiple args, just increment the {x} and add another parameter to the Format() method. Not sure the different but both "string" and "String" have this method. A: A compiled regex might do the trick , especially if there are many tokens to be replaced. If there are just a handful of them and performance is key, I would simply find the token by index and replace using string functions. Believe it or not this will be faster than a regex. A: Try using StringTemplate. It's much more powerful than that, but it does the job flawless. A: or try this with Linq if you have all your replace values stored in a Dictionary obj. For example: Dictionary<string,string> dict = new Dictionary<string,string>(); dict.add("replace1","newVal1"); dict.add("replace2","newVal2"); dict.add("replace3","newVal3"); var newstr = dict.Aggregate(str, (current, value) => current.Replace(value.Key, value.Value)); dict is your search-replace pairs defined Dictionary object. str is your string which you need to do some replacements with. A: I would go for the mindplay.dk solution... Works quite well. And, with a slight modification, it supports templates-of-templates, like "Hi {name}, do you like {0}?", replacing {name} but retaining {0}: In the given source (https://gist.github.com/896724), replace as follows: var format = Pattern.Replace( template, match => { var name = match.Groups[1].Captures[0].Value; if (!int.TryParse(name, out parsedInt)) { if (!map.ContainsKey(name)) { map[name] = map.Count; list.Add(dictionary.ContainsKey(name) ? dictionary[name] : null); } return "{" + map[name] + match.Groups[2].Captures[0].Value + "}"; } else return "{{" + name + "}}"; } ); Furthermore, it supports a length ({name,30}) as well as a formatspecifier, or a combination of both. A: UPDATE for 2022 (for both .NET 4.8 and .NET 6): Especially when multi-line string templates are needed, C# 6 now offers us both $ and @ used together like: (You just need to escape quotes by replacing " with "") string name = "Mike"; int age = 20 + 14; // 34 string product = "milk"; var htmlTemplateContent = $@" <!DOCTYPE html> <html> <head> <meta charset=""utf-8"" /> <title>Sample HTML page</title> </head> <body> Hi {name}, now that you're {age.ToString()}, how do you like {product}? </body> </html>";
doc_1719
So far I've seen people suggest pcapy and pypcap, but when I try to install those, they both fail and tell me I am missing msvcr71.dll even though it is on my computer. Also, the python-libpcap sourceforge page seems to be unavailable, so I can't try that. A: py-pcap from dirtbags.net doesn't depend on a pcap lib so it might work for you. Though, I'm not sure how fast it is or if it works on windows. http://dirtbags.net/py-pcap.html A: Obviously you want to use a ready-made wrapper, but keep in mind that you can always use Ctypes to directly access the capture functions. See: http://www.python.org/doc/current/library/ctypes.html Hope this helps
doc_1720
I have very little knowledge of payment gateways. I will coordinate with some bank payment gateways but can I setup/integrate those with this DPS Payment Gateway plugin? is DPS Payment Gateway a standard term? A: It's referring to this services offered by http://www.paymentexpress.com (aka DPS)
doc_1721
A: While you certainly can do things like Clipboard.SetText and Clipboard.GetText in your VM, if you are an MVVM purist (like me), then I would recommend creating a ClipboardService (with an appropriate interface, so you can mock it in unit tests). Something like the following: using System.Windows; public class ClipboardService : IClipboardService { public void SetText(string value) { Clipboard.SetText(value); } public string GetText() { return Clipboard.GetText(); } } Then you can reference it as a property in your VM like so: public IClipboardService ClipboardService { get; set; } And either set it directly as a property or include it in your constructor: public FooViewModel(IClipboardService service) { ClipboardService = service; } And when you need it, instead of calling Clipboard.SetText directly, you can use ClipboardService.SetText instead. And you can (as mentioned before) mock it in unit tests. So, if you use Moq (like I do), you could have something like: Mock<IClipboardService> clipMock = new Mock<IClipboardService>(); clipMock.Setup(mock => mock.GetText(It.IsAny<string>())).Returns("Foo"); And instantiate your VM like so: var fooVm = new FooViewModel(clipMock.Object); And so on. I realize this is an ancient post, but I was looking for some best practices on Clipboards and MVVM, made my own decision while reading this post and decided to share. Hope somebody finds it useful. :-) A: SL 4 now supports text clipboard operations. This is transparent in OOB mode and requires user confirmation if not in OOB mode. You can use Clipboard.GetText() in your view models and commands to retrieve the text content available in the clipboard.
doc_1722
I have the project structure as below The gradle build should appear on the right-hand side of the IDE, but it is not Even on the run configuration I don't see the project I can see the build.gradle file for both the project A: Make sure you have Gradle bundled plugin enabled in Preferences | plugins. Then you can add a Gradle module via File | New | Module form Existing Sources and select build.gradle file to import from, see Import an existing module to the project.
doc_1723
Controller: @users = User.all.page(params[:page]).per(params[:per_page]).order(sort_by => sort_order).where(type: {'$all': ["#{params[:type]}"] }) Now, is it possible to find all document from collection using: .where(type: {'$all': ['something_to_find_all_from type:'] }) ? A: Assuming, params[:type] is an array, you can search all users using where, and thereafter sort these results using order. You can find a similar example here. @users = User.where(:type.in => params[:type]).order(sort_by => sort_order).page(params[:page]).per(params[:per_page]) If you're looking for a translated mongoid query you can check out this link Your query might then read something like User.where(:type.all => params[:type])
doc_1724
When I register a new user on the site it can login and logout successfully, but when I login through the login form it fails every time even though I'm providing the right data. I don't understand why this is happening. What did I do wrong? Here is my auth controller. <?php namespace App\Http\Controllers\Auth; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Validator; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; class AuthController extends Controller { use AuthenticatesAndRegistersUsers, ThrottlesLogins; protected $redirectTo = '/home'; protected $guard = 'user'; public function __construct() { $this->middleware($this->guestMiddleware(), ['except' => 'logout']); } protected function validator(array $data) { return Validator::make($data, [ 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6|confirmed', ]); } protected function create(array $data) { return User::create([ 'first_name' => $data['firstName'], 'last_name' => $data['lastName'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } } Route.php <?php Route::group(['middleware' => ['web']], function () { // Your route here // // Authentication routes... Route::get('customer/login', 'Customer\Auth\AuthController@getLogin'); Route::post('customer/login', 'Customer\Auth\AuthController@postLogin'); Route::get('customer/logout', 'Customer\Auth\AuthController@getLogout'); // // // Registration routes... Route::get('customer/register', 'Customer\Auth\AuthController@getRegister'); Route::post('customer/register', 'Customer\Auth\AuthController@postRegister'); Route::auth(); Route::get('/home', function (){ return view('welcome'); }); }); Route::get('/home', 'HomeController@index');
doc_1725
price float(15,2) in mysql, mongo is not float(15,2). I want to Determine a var $price have two decimal places. eg. 100.00 is right, 100 or 100.0 is wrong. eg.1 $price = 100.00; $price have two decimal, it's right. eg.2 $price = 100.0; $price have not two decimal, it's wrong. A: I like to use Regular Expressions to do these things function validateTwoDecimals($number) { if(preg_match('/^[0-9]+\.[0-9]{2}$/', $number)) return true; else return false; } (Thanks to Fred-ii- for the corrections) A: Everybody is dancing around the fact that floating point numbers don't have a number of decimal places in their internal representation. i.e. in float 100 == 100.0 == 100.00 == 100.000 and are all represented by the same number, effectively 100 and is stored that way. The number of decimal places in this example only has a context when the number is represented as a string. In which case any string function that counts the number of digits trailing the decimal point could be used to check. A: number_format($price, $numberOfDecimalDigits) === $price; or strrpos($price, '.') === strlen($price) - 1 - $numberOfDecimalDigits; Trivia: $price should not be called a "float variable". This is a string that happens to represent a float value. 100.00 as a float has zero decimal digits, and 100.00 === 100 as float : $price = 100.00; echo $price; // output: 100 $price2 = (float)100; echo $price === $price2; // ouput: 1 A: In order for this to work, the number will need to be wrapped in quotes. With the many scripts I've tested, using $price = 100.00; without quotes did not work, while $price = 100.10; did, so this is as best as it gets. <?php $number = '100.00'; echo $number.'<br>'; $count = explode('.',$number); echo 'The number of digits after the decimal point is: ' . strlen($count[1]); if(strlen($count[1]) == 2){ echo "<br>"; echo "There is 2 decimal points."; } else{ echo "<br>"; echo "There is not 2 decimal points."; } A: After you format the value, you can check with simply splitting the value as string into 2 parts, for example with explode ... $ex=explode('.',$in,2); if (strlen($ex[1])==2) { // true } else { // false } But again, as i've commented already, if you really have floating input, this is just not a reliable way, as floating numbers are without set decimal places, even if they appears so because of the rounding at the float=>string conversion What you can do, if you really have floating numbers and wish to have xxx.yy format numbers: 1) convert float to string using round($x,2), so it will round to 2 decimal places. 2) explode the number as i've described, and do the following: while (strlen($ex[1]<2)) {$ex[1].='0';} $number=implode('.',$ex); A: I would use the following function for that: function isFloatWith2Decimals($number) { return (bool) preg_match('/^(?:[1-9]{1}\d*|0)\.\d{2}$/', $number); } This will also check if you have only one leading 0 so number like 010.23 won't be considered as valid whereas number like 0.23 will. And if you don't care about leading 0 you could use simpler method: function isFloatWith2Decimals($number) { return (bool) preg_match('/^\d+\.\d{2}$/', $number); } Of course numbers need to be passed as string - if you pass 100.00 won't be considered as true, whereas '100.00' will
doc_1726
Notice: Only variables should be assigned by reference in /xxxxx/www/administrator/modules/mod_hccmededelingen/tmpl/default.php on line 15 <?php // No direct access defined('_JEXEC') or die; $componentnaam = 'com_hccxmlbeheer'; $componentcat = 'com'; // haal variable op jimport('HCCxmlLibrary.HCCxmlLibrary'); jimport( 'joomla.plugin.helper' ); // haal setting op ingestelde groepering op bij de Authenticatie plugin $authplugin = JPluginHelper::getPlugin('authentication', 'HCCxmlAuthenticatie'); $authpluginparams = new JRegistry($authplugin->params); $Ingesteldegroepering = $authpluginparams->get('groepering', ''); $config = JFactory::getConfig(); $liveurl = $config->get('live_site'); $user =& JFactory::getUser(); $name = $user->name; $berichten = HCC::getberichten($componentnaam, $componentcat); $mededeling = $berichten['mededelingen']; $AlertActief = $berichten['AlertActief']; $Alert = $berichten['Alert']; if ($AlertActief == 1) { echo " <div class=\"alert alert-error\"> <h4 class=\"alert-heading\">Opgelet!:</h4> <p>$Alert</p> </div> "; } $query = "SELECT `id` FROM `#__template_styles` WHERE `client_id` = 0 AND `home` = '1'"; $styleId = HCC::selectwaarde($query, $componentnaam, $componentcat); echo "<div class=\"row-striped\">"; echo "<br>"; echo "Hallo $name,"; echo "<br>"; echo "<br>"; echo "Om de \"template module locatie's\" te bekijken <a href=\"$liveurl/index.php?tp=1&templateStyle=$styleId\" target=\"_blank\">klik hier</a><br><br>"; echo "$mededeling"; echo "</div>"; ?> Note: I don't need to disable Strict Standards in php.ini with this method: error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT I want to fix my PHP code. A: The following line make this error: $user =& JFactory::getUser(); you can't directly add reference on return value from function. you need to cast it in variable before and make reference on it. If you want to modify private attribute , use setMethod of object
doc_1727
0x40080201: WinRT originate error (parameters: 0xC00D3704, 0x00000049, 0x10EFF1CC) in my logs but my try catch block doesn't catch the error. create_task(_mediaCapture->StartPreviewToCustomSinkAsync(encoding_profile, media_sink)).then([this, &hr](task<void>& info) { try { info.get(); } catch (Exception^ e) { hr = e->HResult; } }).wait(); A: StartPreviewAsync method will throw a FileLoadException if another app has exclusive control of the capture device. We can catch this error to alert the user that the camera is currently being used by another application. A simple sample can be found at Use MediaCapture to start the preview stream. However, this is a C# sample and FileLoadException is what used in .Net. For C++/CX, we can check the HRESULT value which should be 0x80070020. Following is the simple sample in C++/CX version. MainPage.xaml <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <CaptureElement Name="PreviewControl" Stretch="Uniform"/> <Button Click="Button_Click">Click</Button> </Grid> MainPage.xaml.h public ref class MainPage sealed { public: MainPage(); private: // Prevent the screen from sleeping while the camera is running Windows::System::Display::DisplayRequest^ _displayRequest; // MediaCapture Platform::Agile<Windows::Media::Capture::MediaCapture^> _mediaCapture; void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); }; MainPage.xaml.cpp MainPage::MainPage() : _mediaCapture(nullptr) , _displayRequest(ref new Windows::System::Display::DisplayRequest()) { InitializeComponent(); } void MainPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { _mediaCapture = ref new Windows::Media::Capture::MediaCapture(); create_task(_mediaCapture->InitializeAsync()) .then([this](task<void> previousTask) { try { previousTask.get(); _displayRequest->RequestActive(); Windows::Graphics::Display::DisplayInformation::AutoRotationPreferences = Windows::Graphics::Display::DisplayOrientations::Landscape; PreviewControl->Source = _mediaCapture.Get(); create_task(_mediaCapture->StartPreviewAsync()) .then([this](task<void>& previousTask) { try { previousTask.get(); } catch (Exception^ exception) { if (exception->HResult == 0x80070020) { auto messageDialog = ref new Windows::UI::Popups::MessageDialog("Cannot setup camera; currently being using."); create_task(messageDialog->ShowAsync()); } } }); } catch (AccessDeniedException^) { auto messageDialog = ref new Windows::UI::Popups::MessageDialog("The app was denied access to the camera."); create_task(messageDialog->ShowAsync()); } }); } StartPreviewToCustomSinkAsync method is similar to StartPreviewAsync method and can also throw a FileLoadException. You should be able to handle it using the same way. For more info, please also see Handle changes in exclusive control.
doc_1728
var country = svg.selectAll(".country") .data(countries) .enter().append("g") .attr("class", "country"); var path = country.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d) { return color(d.country); }) var totalLength = path.node().getTotalLength(); d3.select(".line") .attr("stroke-dasharray", totalLength + " " + totalLength) .attr("stroke-dashoffset", totalLength) .transition() .duration(1000) .ease("linear") .attr("stroke-dashoffset", 0) .each("end", function() { d3.select(".label") .transition() .style("opacity", 1); }); var labels = country.append("text") .datum(function(d) { return {country: d.country, value: d.values[d.values.length - 1]}; }) .attr("class", "label") .attr("transform", function(d) { return "translate(" + x(d.value.month) + "," + y(d.value.rainfall) + ")"; }) .attr("x", 3) .attr("dy", ".35em") .style("opacity", 0) .text(function(d) { return d.country; }); A: You can use .delay() with a function to do this: d3.select(".line") .attr("stroke-dasharray", totalLength + " " + totalLength) .attr("stroke-dashoffset", totalLength) .transition() .delay(function(d, i) { return i * 1000; }) .duration(1000) .ease("linear") .attr("stroke-dashoffset", 0) .each("end", function() { d3.select(".label") .transition() .style("opacity", 1); });
doc_1729
My app is crashing when I try to write it to the db. Im sure I am missing something in my helper or setup, but I do not have the experience to understand what it is. My helper class is as follows: public class TableSubandObAssessment { public static final String TAG = "TableSubandObAssessment"; public static final String KEY_TABLE = "assessments"; private static final String KEY_APPOINTMENT_ID = "appointmentID"; private static final String KEY_TYPE = "type"; private static final String KEY_ASSESSMENT = "assessment"; private static final String KEY_VARIABLE1 = "variable1"; private static final String KEY_VARIABLE2 = "vriable2"; private static final String KEY_VARIABLE3 = "vriable3"; private static final String KEY_VARIABLE4 = "vriable4"; private DatabaseHelper helper; private final Context context; public static SQLiteDatabase db; private static final String CREATE_TABLE = "CREATE TABLE " + KEY_TABLE + " (" + KEY_APPOINTMENT_ID + " INTEGER PRIMARY KEY NOT NULL, " + KEY_TYPE + " TEXT NOT NULL, " + KEY_ASSESSMENT + " TEXT NOT NULL, " + KEY_VARIABLE1 + " TEXT, " + KEY_VARIABLE2 + " TEXT NOT NULL, " + KEY_VARIABLE3 + " TEXT, " + KEY_VARIABLE4 + " INT " + ");"; public static void createTable(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } public static void dropTable(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + KEY_TABLE); createTable(db); } public TableSubandObAssessment(Context context) { this.context = context; } public TableSubandObAssessment open() throws SQLException { helper = new DatabaseHelper(context); db = helper.getWritableDatabase(); return this; } public void close() { helper.close(); } public static long insertTableSubandObAssessment(int appointmentID, String type, String assessment, String variable1, String variable2, String variable3, String variable4) { ContentValues values = new ContentValues(); values.put(KEY_APPOINTMENT_ID, appointmentID); values.put(KEY_TYPE, type); values.put(KEY_ASSESSMENT, assessment); values.put(KEY_VARIABLE1, variable1); values.put(KEY_VARIABLE2, variable2); values.put(KEY_VARIABLE3, variable3); values.put(KEY_VARIABLE4, variable4); return db.insert(KEY_TABLE, null, values); } } The existing helpers are as follows (I added in the references to my table): public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "PGAAPPOINTMENTS.db"; private static final int DATABASE_VERSION = 1; private SQLiteDatabase db = null; public DatabaseHelper(Context c) { super(c, DATABASE_NAME, null, DATABASE_VERSION); } public void openToRead() { close(); db = this.getReadableDatabase(); } public void openToWrite() { close(); db = this.getWritableDatabase(); } public void close() { if (db != null) { super.close(); db = null; } } @Override public void onCreate(SQLiteDatabase db) { AppointmentTable.createTable(db); PlayerTable.createTable(db); PractitionerTable.createTable(db); TableRoutine.createTable(db); TableDiagnostic.createTable(db); TableAssessment.createTable(db); TableFollowUp.createTable(db); TableNote.createTable(db); TableSubandObAssessment.createTable(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { TableRoutine.dropTable(db); AppointmentTable.dropTable(db); TableDiagnostic.dropTable(db); TableAssessment.dropTable(db); TableFollowUp.dropTable(db); TableNote.dropTable(db); PlayerTable.dropTable(db); PractitionerTable.dropTable(db); TableSubandObAssessment.dropTable(db); onCreate(db); } } and the method I use to setup the database is: public void saveToDb(){ createTable(TableSubandObAssessment.db); int a=(int)ActivityMain.apID; TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Observation", Active_Movements.obs, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Joint Integrity Test", Active_Movements.JIT, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Active Movements", Active_Movements.amv, Active_Movements.amv2,Active_Movements.amv3,""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Passive Movements", Active_Movements.passive, Active_Movements.passive1,Active_Movements.passive2,""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Repeated Movements", Active_Movements.repm, Active_Movements.repm1,Active_Movements.repm2,""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Combined Movements", Active_Movements.comb, Active_Movements.comb1,Active_Movements.comb2,""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Capsular Pattern", Active_Movements.cappat, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Joint Effusion", Active_Movements.joint_eff, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "PPIVMs", Active_Movements.PPIVMS, Active_Movements.PPIVMS2,Active_Movements.PPIVMS3,Active_Movements.PPIVMS4); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Other Joints Involved", Active_Movements.other_joints, Active_Movements.other_joints1,"",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Muscle Strength", Active_Movements.muscst, Active_Movements.muscst1,Active_Movements.muscst2,""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Muscle Control",Active_Movements.musccont, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Muscle Length", Active_Movements.musclength, Active_Movements.musclength1,Active_Movements.musclength2,""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Isometric Muscle Tests",Active_Movements.imt, "", "",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Integrity Of Nervous System", Active_Movements.INS, Active_Movements.INS1,Active_Movements.INS2,""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Mobility Of Nervous System", Active_Movements.MobNS, Active_Movements.MobNS1,Active_Movements.MobNS2,""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Diagnostic Tests", Active_Movements.diagt, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Special Tests", Active_Movements.spect, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Accessory Movements", Active_Movements.accm, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Palpation", Active_Movements.palp, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Conclusion", Active_Movements.conc, "","",""); TableSubandObAssessment.insertTableSubandObAssessment(a, "Objective", "Diagnosis", Active_Movements.Diag, Active_Movements.Diag1,Active_Movements.Diag2,""); } and here is the logcat (Which I have no ides how to interpret): 07-27 11:37:16.757: E/AndroidRuntime(12807): FATAL EXCEPTION: main 07-27 11:37:16.757: E/AndroidRuntime(12807): java.lang.NullPointerException 07-27 11:37:16.757: E/AndroidRuntime(12807): at com.ucl.pga.db.TableSubandObAssessment.insertTableSubandObAssessment(TableSubandObAssessment.java:73) 07-27 11:37:16.757: E/AndroidRuntime(12807): at com.ucl.pga.db.Objective.Summary.saveToDb(Summary.java:921) 07-27 11:37:16.757: E/AndroidRuntime(12807): at com.ucl.pga.db.Objective.Summary$2$1.onClick(Summary.java:495) 07-27 11:37:16.757: E/AndroidRuntime(12807): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166) 07-27 11:37:16.757: E/AndroidRuntime(12807): at android.os.Handler.dispatchMessage(Handler.java:99) 07-27 11:37:16.757: E/AndroidRuntime(12807): at android.os.Looper.loop(Looper.java:137) 07-27 11:37:16.757: E/AndroidRuntime(12807): at android.app.ActivityThread.main(ActivityThread.java:4745) 07-27 11:37:16.757: E/AndroidRuntime(12807): at java.lang.reflect.Method.invokeNative(Native Method) 07-27 11:37:16.757: E/AndroidRuntime(12807): at java.lang.reflect.Method.invoke(Method.java:511) 07-27 11:37:16.757: E/AndroidRuntime(12807): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 07-27 11:37:16.757: E/AndroidRuntime(12807): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 07-27 11:37:16.757: E/AndroidRuntime(12807): at dalvik.system.NativeStart.main(Native Method) A: I think your Attribute db you want to write to is null. You should call TableSubandObAssessment.open() before insertTableSubandObAssessment(), because this initializes your attribute. Note that the Argument of createTable is shadowing your Attribute and does not initializes it for the insert method.
doc_1730
import static org.junit.jupiter.api.Assertions.*; import org.junit.After; import org.junit.Before; import org.junit.jupiter.api.Test; class TestingJUnit { @Before public void testOpenBrowser() { System.out.println("Opening Chrome browser"); } @Test public void tesingNavigation() { System.out.println("Opening website"); } @Test public void testLoginDetails() { System.out.println("Enter Login details"); } @After public void testClosingBrowser() { System.out.println("Closing Google Chrome browser"); } } But when I run this cas only @Test annotations are running @Before and @After annotations code are not running. Please guide me I think this is JUnit version or eclipse IDE version problem, and also my all Test classes not running in TestSuit I don't know why although Test Classes are running fine individually. My TestSuit Class is here: import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({TestingJUnit.class, SecondTest.class}) public class TestSuit { } A: Try using @BeforeEach instead of @Before and @AfterEach instead of @After A: Try Using This @BeforeEach public void before() { System.out.println("Before"); } @AfterEach public void after() { System.out.println("After"); } @Test public void sum_with3numbers() { System.out.println("Test 1"); } @Test public void sum_with1numbers() { System.out.println("Test 2"); } Output will be: Before Test 1 After Before Test 2 After
doc_1731
Other Devices ADB Interface( with question mark) I tried to fix this problem updating Driver Software from Android SDK/ but, this one was not find. I went to the Dell drivers and I could not find it either. I read that the Clockworkmod drivers Version 7.0.0.4 date 8/27/2012 would work well with my mobile device. For it, Could anybody help me to find the correct drivers for this tablet? Thanks in advance Alejandro Castan A: Here placed a similar question: Debugging Android Apps on Dell Venue 7 using Eclipse And it looks like first comment contain instructions to make it work. I never faced such kind of a problem, so I cant say if that instuction really help, but I hope it will work for you. A: maybe you should install the adb driver from http://adbdriver.com/downloads/. My android mobile phone works well now after installing this one.
doc_1732
I am using Fullpage.js (https://github.com/alvarotrigo/fullPage.js/) plugin to create a site where pages move horizontally. The plugin is designed to create full page sites where it vertically scrolls through each section, by scrolling or pressing down the keys, just like a parallax site. In my file, I am only using the one section with left and right arrows to contain my multiple pages for horizontal scrolling. Like the example on http://alvarotrigo.com/fullPage/examples/scrolling.html Since I don't have multiple sections, when I hit the up/down keys it doesn't scroll the content at all. Any suggestions would be greatly appreciated. Thanks in advance! A: Just assign the fullpage functions moveSlideRight and moveSlideLeft to your keydown events and turn off the default keyboard scrolling of fullpage.js by using $.fn.fullpage.setKeyboardScrolling(false) $(document).keydown(function (e) { var shiftPressed = e.shiftKey; switch (e.which) { //up case 38: case 33: $.fn.fullpage.moveSlideLeft(); break; //down case 40: case 34: $.fn.fullpage.moveSlideRight(); break; } }); Demo online
doc_1733
Here I can login with Facebook successfully and can fetch name, email and profile pic. I have used gem : gem ‘omniauth-facebook’ But now I want to fetch all posts from the timeline of Facebook user. Please guide me for this. Thanks in advance A: You have to create one sample application on Facebook developer center in order to get AppId and AppSecret for authentication. Also, you can give few permission there in your profile of developers account. You can refer to following Blog : https://medium.com/@trydelight/facebook-authentication-with-devise-5b53d2f664ed
doc_1734
import { authenticationService, getUserProfileService, } from '../services/user-service'; import { getDonationHistory } from '../services/donation-service'; import AsyncStorage from '@react-native-async-storage/async-storage'; import * as TaskManager from 'expo-task-manager'; import * as Location from 'expo-location'; import * as BackgroundFetch from 'expo-background-fetch'; const UserInfoContext = createContext(); const UserInfoProvider = ({ children }) => { const [isLoggedIn, setIsLoggedIn] = useState(false); const [userProfile, setUserProfile] = useState({ donorId: '', icNo: '', fName: '', lName: '', bloodType: '', }); const [errorMessage, setErrorMessage] = useState(null); const [location, setLocation] = useState({ latitude: '', longitude: '' }); let updateLocation = (loc) => { setLocation(loc); }; console.log(location); const sendBackgroundLocation = async () => { const { status } = await Location.requestForegroundPermissionsAsync(); if (status === 'granted') { const { status } = await Location.requestBackgroundPermissionsAsync(); if (status === 'granted') { await Location.startLocationUpdatesAsync('LocationUpdate', { accuracy: Location.Accuracy.Balanced, timeInterval: 10000, distanceInterval: 1, foregroundService: { notificationTitle: 'Live Tracker', notificationBody: 'Live Tracker is on.', }, }); } } }; const _requestLocationPermission = async () => { (async () => { let { status } = await Location.requestForegroundPermissionsAsync(); if (status == 'granted') { let { status } = await Location.requestBackgroundPermissionsAsync(); if (status == 'granted') { } else { console.log('Permission to access location was denied'); } } else { console.log('Permission to access location was denied'); } })(); }; sendBackgroundLocation(); const getUserProfile = () => { return userProfile; }; useEffect(() => { (async () => await _requestLocationPermission())(); retrieveAuthTokens(); retrieveUserProfile(); }); let retrieveAuthTokens = async () => { try { const authTokens = await AsyncStorage.getItem('authTokens'); authTokens ? setIsLoggedIn(true) : setIsLoggedIn(false); } catch (error) { console.log(error.message); } }; let retrieveUserProfile = async () => { try { const userProfile = JSON.parse(await AsyncStorage.getItem('userProfile')); userProfile ? setUserProfile({ donorId: userProfile.donorId, icNo: userProfile.appUser.username, fName: userProfile.fName, lName: userProfile.lName, bloodType: userProfile.bloodType, }) : null; } catch (error) { console.log(error.message); } }; let loginUser = (values) => { authenticationService(values) .then(async (data) => { if (data !== undefined && data !== null) { const tokens = data.data; await AsyncStorage.setItem('authTokens', JSON.stringify(tokens)); getProfile(values.icNo); getHistories(userProfile.donorId); setErrorMessage(null); } else { setErrorMessage('Wrong email/password!'); } }) .catch((error) => console.log(error.message)); }; let logoutUser = async () => { try { await AsyncStorage.clear().then(console.log('clear')); setIsLoggedIn(false); } catch (error) { console.log(error.message); } }; getProfile = (icNo) => { getUserProfileService(icNo) .then(async (res) => { if (res !== undefined && res !== null) { const profile = res.data; await AsyncStorage.setItem('userProfile', JSON.stringify(profile)); setIsLoggedIn(true); } }) .catch((error) => console.log(error.message)); }; const getHistories = (userId) => { getDonationHistory(userId) .then(async (res) => { if (res !== undefined && res !== null) { const historyData = res.data; await AsyncStorage.setItem( 'donationHistories', JSON.stringify(historyData) ); } else { console.log('no data'); } }) .catch((error) => console.log(error.message)); }; let contextData = { loginUser: loginUser, logoutUser: logoutUser, isLoggedIn: isLoggedIn, errorMessage: errorMessage, userProfile: userProfile, getHistories: getHistories, }; return ( <UserInfoContext.Provider value={contextData}> {children} </UserInfoContext.Provider> ); }; export const useUserInfo = () => useContext(UserInfoContext); export default UserInfoProvider; function myTask() { try { const backendData = 'Simulated fetch ' + Math.random(); return backendData ? BackgroundFetch.BackgroundFetchResult.NewData : BackgroundFetch.BackgroundFetchResult.NoData; } catch (err) { return BackgroundFetch.BackgroundFetchResult.Failed; } } async function initBackgroundFetch(taskName, interval = 60 * 15) { try { if (!TaskManager.isTaskDefined(taskName)) { TaskManager.defineTask(taskName, ({ data, error }) => { if (error) { console.log('Error bg', error); return; } if (data) { const { locations } = data; console.log( locations[0].coords.latitude, locations[0].coords.longitude ); //-----------------doesnt work ---------------------------- UserInfoProvider.updateLocation({ latitude: locations[0].coords.latitude, longitude: locations[0].coords.longitude, }); //-----------------doesnt work ---------------------------- } }); } const options = { minimumInterval: interval, // in seconds }; await BackgroundFetch.registerTaskAsync(taskName, options); } catch (err) { console.log('registerTaskAsync() failed:', err); } } initBackgroundFetch('LocationUpdate', 5); I'm trying to update the location state in the UserInfoProvider and this location info will be sent to the firestore along with the userprofile details retrieved in this provider. However, it seems that i cant access the UserInfoProvider.updateLocation() outside the UserInfoProvider component. Is there anyway I can get both the userprofile info and the location info retrieved from background task together and send them to firestore? At the moment, only the console.log( locations[0].coords.latitude, locations[0].coords.longitude ); in the background task seems to be working. Error I got: TaskManager: Task "LocationUpdate" failed:, [TypeError: undefined is not a function (near '...UserInfoProvider.updateLocation...')] at node_modules\react-native\Libraries\LogBox\LogBox.js:149:8 in registerError at node_modules\react-native\Libraries\LogBox\LogBox.js:60:8 in errorImpl at node_modules\react-native\Libraries\LogBox\LogBox.js:34:4 in console.error at node_modules\expo\build\environment\react-native-logs.fx.js:27:4 in error at node_modules\expo-task-manager\build\TaskManager.js:143:16 in eventEmitter.addListener$argument_1 at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch at node_modules\regenerator-runtime\runtime.js:294:29 in invoke at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch at node_modules\regenerator-runtime\runtime.js:155:27 in invoke at node_modules\regenerator-runtime\runtime.js:190:16 in PromiseImpl$argument_0 at node_modules\react-native\node_modules\promise\setimmediate\core.js:45:6 in tryCallTwo at node_modules\react-native\node_modules\promise\setimmediate\core.js:200:22 in doResolve at node_modules\react-native\node_modules\promise\setimmediate\core.js:66:11 in Promise at node_modules\regenerator-runtime\runtime.js:189:15 in callInvokeWithMethodAndArg at node_modules\regenerator-runtime\runtime.js:212:38 in enqueue at node_modules\regenerator-runtime\runtime.js:239:8 in exports.async at node_modules\expo-task-manager\build\TaskManager.js:133:57 in eventEmitter.addListener$argument_1 at node_modules\react-native\Libraries\vendor\emitter_EventEmitter.js:135:10 in EventEmitter#emit at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:4 in __callFunction at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:6 in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:4 in callFunctionReturnFlushedQueue A: By reviewing UserInfoProvider context value: let contextData = { loginUser: loginUser, logoutUser: logoutUser, isLoggedIn: isLoggedIn, errorMessage: errorMessage, userProfile: userProfile, getHistories: getHistories, }; updateLocation function not available and you can't access. You need to use useUserInfo to consume UserInfoProvider value.
doc_1735
A: FlatList A performant interface for rendering basic, flat lists, supporting the most handy features: * *Fully cross-platform. *Optional horizontal mode. *Configurable viewability callbacks. *Header support. *Footer support. *Separator support. *Pull to Refresh. *Scroll loading. *ScrollToIndex support. *Multiple column support. If you need section support, use . Demo: https://snack.expo.dev/@g1sm0/flatlist-simple Doc: https://reactnative.dev/docs/flatlist PERSONAL NOTE: DON'T FORGET THE KEY EXTRACT!
doc_1736
I have this command "du -hs /var" which give me usage of /var in MB and /var is in the /root directory. So to calculate total disk on which /var is present I did the following command df -ks, this gives me the total of / and some % which I am not sure I should use. Can please someone help with a command for calculating the %. A: If you are using snmpd you would just need to add this to snmpd.conf: disk /var 80% This will generate a trap when the /var partition reaches 80% usage. If you want to use the result of df -k /var command, use the Use% column. A: Does this work for you? df /var | tail -1 | sed -r 's/.* ([0-9]+%).*/\1/' Breaking this down: df /var outputs the header and one line for /var. tail -1 strips the header. The sed command edits the line, capturing the percentage used and discarding the rest. In words, we could say “match everything up to a space, followed by one or more digits and a percent sign; capture the digits and percent sign; match the rest of the line; replace the line with the part that was captured”. This produces a nice human-readable number with a percent sign. For computing purposes you probably want the number without the percent sign: df /var | tail -1 | sed -r 's/.* ([0-9]+)%.*/\1/'
doc_1737
Is there a standard for representing notes digitally? I don't want to reinvent any wheels. Given a sequence of notes and durations, is there a library for displaying these in a sheet music format? Basically I'm looking for a place to get started. I'm not heavily into graphics, so a existing open-source library would be awesome. If none exists in Python, I'm competent at Java/Javascript/C as well. Thanks A: As far as I know, abc notation is still the de facto standard text format in traditional/folk music circles. There is quite a bit of software available for it, including abctool and abc2ly (part of GNU LilyPond), both of which are written in python. Being a self-described python hacker, I imagine you could turn either of these into a library without much trouble. A: Take a look at lilypond. It uses LaTeX to typeset sheet music. Its input format is simple text, and can be generated pretty easily with Python or whatever. Abjad is a "Python API for Formalized Score Control" and a wrapper around lilypond, but I haven't used it and so can't vouch for it. A: Probably not exactly what you're looking for, but there is a commercial program called capella (from a small German software company; there is an English version, too). It supports the MusicXML format, and it uses Python for scripting, so you can write scripts for extending its functionality (which is already quite impressive, though). I learned Python because of capella. (Turns out I never did write any scripts for capella - never needed to - but it sure made me curious about Python :)) A: Is there a standard for representing notes digitally? I assume you've heard of MIDI (which encompasses far more than simply notes and durations, but which is a standard that represents notes digitally). I recommend looking at the Music Notation programs listed in the Python in Music Python wiki page and seeing if you can extend or contribute to those applications before rolling your own.
doc_1738
but they are not working all at one time. only transaction is working right now that is of DocumentReference PostRef. please assist in running multiple transactions. db.runTransaction(new Transaction.Function<Void>() { @Override public Void apply(Transaction transaction) throws FirebaseFirestoreException { DocumentSnapshot documentSnapshot1 = transaction.get(PostRef); boolean l2 = documentSnapshot1.getBoolean("l2"); if(l2 == false) { transaction.update(PostRef, "l2", true); return null; } DocumentSnapshot documentSnapshot2 = transaction.get(PostUserRef); long l11 = documentSnapshot2.getLong("l1"); { transaction.update(PostRef, "l1", l11+1); } DocumentSnapshot snapshot = transaction.get(likesRef); boolean l1 = snapshot.getBoolean("l1"); if (l1 == false) { transaction.update(likesRef, "l1", true); //2 transactions to update userprofile return null; } else { throw new FirebaseFirestoreException("You already liked", FirebaseFirestoreException.Code.ABORTED); } } }) A: What I did is I Setup the multiple transactions as a function and then called those functions in the onclick event and it performed the required functions
doc_1739
mockMyService.doSomethingAsync.andReturnValue($q.when(successResponse)) This has been working out pretty well, however, I have a method that looks like the following: # MyService MyService.doSomethingAsync(params).$promise.then -> $scope.isLoading = false # MyService Spec mockMyService = doSomethingAsync: jasmine.createSpy('doSomethingAsync') it 'calls service #doSomethingAsync', -> inject ($q) -> mockMyService.doSomethingAsync.and.returnValue($q.when(response)) controller.methodThatWrapsServiceCall() scope.$apply() expect(mockMyService.doSomethingAsync).toHaveBeenCalled() and unfortunately the mocking strategy outlined above doesn't seem to work when a $promise.then is chained at the end. I end up with the following error: TypeError: 'undefined' is not an object (evaluating 'MyService.doSomethingAsync(params).$promise.then') Methods that simply end with doSomethingAsync().$promise pass the tests without issues using this mocking strategy. (Other info: These are Jasmine tests run with Karma and PhantomJS) A: Actually, figured it out! I just changed my mock to return and.returnValue( { $promise: $q.when(response) } )
doc_1740
#define ISPOINTER(x) ((((uintptr_t)(x)) & ~0xffff) != 0) I know we have std::is_pointer, but how does this macro work? I tried and failed with strange behavior which I couldn't explained why it's happend: #define ISPOINTER(x) ((((uintptr_t)(x)) & ~0xffff) != 0) int main() { int* ptr; int val; if (ISPOINTER(ptr)) { std::cout << "`ptr`: Is Pointer" << std::endl; } if (ISPOINTER(val)) { std::cout << "`val`: Is Pointer" << std::endl; } } I don't have any output, but if I add another pointer: #define ISPOINTER(x) ((((uintptr_t)(x)) & ~0xffff) != 0) int main() { int* ptr; int val; int* ptr2; if (ISPOINTER(ptr)) { std::cout << "`ptr`: Is Pointer" << std::endl; } if (ISPOINTER(val)) { std::cout << "`val`: Is Pointer" << std::endl; } if (ISPOINTER(ptr2)) { std::cout << "`ptr2`: Is Pointer" << std::endl; } } The output will be: `ptr`: Is Pointer What does ISPOINTER doing? It's undefined behavior? A: Let's do this in steps: ((uintptr_t)(x)) is simply a cast from whatever x is into a uintptr_t (an unsigned integer type capable of storing pointer values) ~0xffff is a bit-wise complement of 0xffff (which is 16 bits of all 1s). The result of that is a number that is all 1s except the last 16 bits. ((uintptr_t)(x)) & ~0xffff is a bit-wise AND of the pointer value with the above number. This will effectively zero-out the 16 lowest bits of whatever the pointer value is. The full expression now just checks if the result is zero or not. So the whole expression basically checks if any bits except the least-significant 16 are set and if so it considers it a pointer. Since this came from Wolfenstein 3D, they probably made the assumption that all dynamically allocated memory lives in high memory addresses (higher than 2^16). So this is NOT a check if a type is a pointer or not using the type system like std::is_pointer does. This is an assumption based on the target architecture Wolfenstein 3D will likely run on. Keep in mind that this is not a safe assumption, since "normal" values above 2^16 would also be considered pointers and the memory layout of your process can be very different depending on a lof of factors (e.g. ASLR) A: It might be similar to certain parameters in Windows, which can be an ordinal value or a pointer. An ordinal value will be <64K. On that operating system, any legal pointer will be >64K. (On older 16-bit versions of Windows, only 4K was reserved.) This code may be doing the same thing. A "resource" may be a built-in or registered value referred to by a small number, or a pointer to an ad-hoc object. This macro is used to decide whether to use it as-is or look it up in the table instead.
doc_1741
Example: dir: src/ file: hook.py function: send_message_via_webhook When I start to type send - auto-import sees send_message_via_webhook which is fine BUT the path is from hook import send_message_via_webhook instead of from src.hook import send_message_via_webhook. Can anyone please help me? It's driving me crazy and I can't find anything to help me. Thanks a lot! A: Okay I think I found the issue. I made 2 changes. First I deleted the added item in Python › Analysis: Extra Paths - there was src that I (probably) added. And then I unchecked Python › Analysis: Auto Search Paths. That made the difference.
doc_1742
I have written a Windows Desktop app that goes out and hits each server and each url combo. (using the httpWebRequest.Proxy to do this). It's usually just for 2 servers at a time. So a total of 60 requests. The first problem was the 2 connection limit, so I added this to the Form Load: ServicePointManager.DefaultConnectionLimit = 500 That helped, but then I seem to run into another limit. After we roll code out for these sites, they can take a while to respond. The init process takes like 30-40 seconds! That's another story though. But there seems to be a Windows XP connection limit. If I have IE open and am trying to access a site, while I a running my app to check sites, the IE takes a long time until it gets a page back. Once the app starts getting requests back and closes them, then IE gets it's response back as well. Also the page we are calling gives us back timings of how long it took to call other WebService calls. These times are sometimes slow, but sometimes quite fast. I have a timer on each HTTP Request I make that starts the timer once I make the request. Sometime the difference between the page's specified response time and the HTTP request's timer is quite large, like 40 seconds. So what I think is happening is the request is being queued up and it's timer is running, but has not yet been sent to the page. Does anyone know what I would need to change to increase the total connection limit in Windows XP? I have read about registry changes or tcpip.sys editing, but would like a definitive answer from the wise and intelligent group at Stackoverflow. Thanks and I hope this makes sense. A: Could you try addding this to your app.config: <configuration> <system.net> <connectionManagement> <add address="*" maxconnection="65535" /> </connectionManagement> </system.net> </configuration>
doc_1743
Was wondering if anyone out there has managed to get a reading? - (void)viewDidLoad { [super viewDidLoad]; if([CMAltimeter isRelativeAltitudeAvailable]){ CMAltimeter *altimeterManager = [[CMAltimeter alloc]init]; [altimeterManager startRelativeAltitudeUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAltitudeData *altitudeData, NSError *error) { // This never fires. NSString *data = [NSString stringWithFormat:@"Altitude: %f %f", altitudeData.relativeAltitude.floatValue, altitudeData.pressure.floatValue]; NSLog(@"%@", data); self.altimeterLabel.text = data; }]; NSLog(@"Started altimeter"); self.altimeterLabel.text = @"-\n-"; } else { NSLog(@"Altimeter not available"); } } I've tried taking this on a quick walk, but there's only one story of altitude to lose/gain around here. A: I'm pretty embarrased to answer my own question with such a huge oversight. In the original post I had the CMAltimiter declared in the scope of viewDidLoad, thus it goes out of scope and is deallocated. I moved it to be an iVar and the callback now fires. #import "ViewController.h" @import CoreMotion; @interface ViewController () @property (nonatomic, strong) CMAltimeter *altimeterManager; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; if([CMAltimeter isRelativeAltitudeAvailable]){ self.altimeterManager = [[CMAltimeter alloc]init]; [self.altimeterManager startRelativeAltitudeUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAltitudeData *altitudeData, NSError *error) { // This now fires properly NSString *data = [NSString stringWithFormat:@"Altitude: %f %f", altitudeData.relativeAltitude.floatValue, altitudeData.pressure.floatValue]; NSLog(@"%@", data); self.altimeterLabel.text = data; }]; NSLog(@"Started altimeter"); self.altimeterLabel.text = @"-\n-"; } else { NSLog(@"Altimeter not available"); } } A: You need to call [altimeterManager stopRelativeAltitudeUpdates]; for the references to be released to the dispatch queue.
doc_1744
In the previous version when cloning a database (Enterprise) with a different name (NewEnterprise) the views kept their original structure, example: CREATE VIEW customerPayments AS select ID, FIRST_NAME, LAST_NAME from customer; In the current version, when it is cloned, the structures change, being in the new database, the views refer to the previous example: CREATE VIEW customerPayments AS select ID, FIRST_NAME, LAST_NAME from Enterprise.custome Where should something like CREATE VIEW customerPayments AS select ID, FIRST_NAME, LAST_NAME from NewEnterprise.custome Or as it happened that left it without the alias of the database. I hope I have made myself understood, otherwise please let me know and I will try to expand the information A: This is really a side-effect of how MySQL handles views — they are strictly defined with the database, table, and column names all needing to be explicitly referenced in the view (for instance, a view of SELECT * FROM `bar`; gets interpreted and stored as SELECT `id`, `name` FROM `foo`.`bar`;. So even though you may not have explicitly set the database name or even column names in the view, that's how MySQL stores them. When copying a database, phpMyAdmin should do the helpful thing and ask you to adjust these; it doesn't right now. I've added a feature request at https://github.com/phpmyadmin/phpmyadmin/issues/16214 to add that functionality.
doc_1745
M005E globalpickesequense = 6627, globalallocationsequense = 7080, globalputawaysequence = 4268 so these numbers need to equal the same numbers as the M005D 7607,8068,5256. M006E same thing needs to equal M007D globals. and so forth... I have to do this update for a total of 235 rows but in the image I am just adding part of rows in the database. So if this possible to do? a query that can update all at the same time without updating row by row individually I have been using this query where it works but I have do one by one changing the ids so that would take me too much time for all my 235 row I need a query that can do the update all at the same time UPDATE lc1 SET lc1.globalPickSequence = lc2.globalPickSequence, lc1.globalAllocationSequence = lc2.globalAllocationSequence, lc1.globalPutAwaySequence = lc2.globalPutAwaySequence from mytable lc1 JOIN mytable lc2 ON lc1.id = 27234 AND lc2.id = 16358
doc_1746
doc_1747
For example, with the class: class MyClass: def __init__(self, values): self.mydict = values list_of_objects = [MyClass({'a':1, 'b':2}), MyClass({'b':1, 'c':1}] # Desired output: ['a', 'b', 'b', 'c'] I know that to get a list of the keys in all the objects, you can do [key for object in list_of_objects for key in object.mydict] But is there a way to do it with itertools without defining __iter__()? With __iter__(), could just do return(iter(self.mydict)), but I'd rather not (either __iter__ is already defined for another purpose, or it clutters up the class) A: So apparently I'm an idiot. Thanks to chepner, the syntax I was looking for was: itertools.chain.from_iterable(object.mydict for object in list_of_objects) which created an iterator over the dictionaries, and let chain.from_iterable collect the keys of the dictionaries.
doc_1748
For example, if you move the Door/Window/Opening shape near the Wall shape (Walls, Doors and Windows stencil) then it will snap nicely to the wall, even from a larger distance, regardless of the global snap strength settings. It will also adjust it's height to the wall's height and set protection on the height. So, that's a bit more complex behavior than just glueing to connection points. I suppose its done with some programmability features, a macro or addon? I've already played a bit with shapesheets but I couldn't find anywhere in the shapesheet a place to set this snap strength. I guess, e.g., in case of the walls and doors, that the shapesheet rules are adjusted programmatically when moving near the wall. On the other hand I don't see any macros in the Walls, Doors and Windows stencil. So, my question is how to create that strong snapping behavior between my Visio custom shapes, similar to the Walls, Doors and Windows stencil.
doc_1749
1 + NaN => NaN Is there any operator which will stop this spreading. I mean something like: <operator> NaN => number or NaN <operator> <operand> => number or <operand> <operator> NaN => number NaN => number A: Actually in Ecmascript definition of (**) operator for numbers. Has a special case when second operand is +0 or -0. https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-numeric-types-number-exponentiate So actually: console.log(NaN ** 0) // will log 1 A: The Javascript has a built-in method that detect a NaN, but you will need check this "Possible number" for each operand. let possibleNumber = "4f"; console.log(isNaN(Number(possibleNumber))); possibleNumber = "44"; console.log(isNaN(Number(possibleNumber))); Output: true false You can do some function to check and return some number that you want function checkIfIsNaN(number,numIfTrue,numIfFalse){ if(isNaN(Number(number))){ return numIfTrue} else{return numIfFalse}; } console.log(checkIfIsNaN("44",4,10));
doc_1750
var myOptions = new ModalOptions() { Animation = ModalAnimation.FadeInOut(1) }; I have done some digging and it seems that the Animation parameter may have been replaced by the AnimationType parameter. This new parameter is an enum and doesn't take a value for fade speed. I have replaced the code above with the following line, which builds: var messageOptions = new ModalOptions() { AnimationType = ModalAnimationType.FadeInOut }; However, I'm concerned about fade speed. Is there a way to specify the value for fade speed in the latest versions of the library?
doc_1751
Date <- seq(as.Date("2000-01-01"), as.Date("2003-12-31"), by = "quarter") Sales <- c(2.8,2.1,4,4.5,3.8,3.2,4.8,5.4,4,3.6,5.5,5.8,4.3,3.9,6,6.4) rData <- data.frame(Date, Sales) tsData <- ts(data = rData$Sales, start = c(2000, 1), frequency = 4) > tsExcelData Qtr1 Qtr2 Qtr3 Qtr4 2000 2.8 2.1 4.0 4.5 2001 3.8 3.2 4.8 5.4 2002 4.0 3.6 5.5 5.8 2003 4.3 3.9 6.0 6.4 myModel <- auto.arima(tsData) myForcast <- forecast(myModel, level = 95, h = 8) The end result should be a data frame with an additional column and a graph with to plots, one for the actual data and one for the forecast data. Something like this. Actual Data vs Forecast Data: A: did you mean something like this, for the past values? If so just add this to your code: extract_fitted_values <- myModel$fitted plot(tsData, xlab = "Time", ylab = "Sales", type = "b", pch = 19) lines(extract_fitted_values, col = "red") As you see, you can extract the fitted values from the model fit. Regarding your question: the data prior the time for the forecast IS actually analyzed when you run the auto.arima model. That is how the Arima model estimates the parameters (by using past data) and then proceeds to do the forecasts. It is just that with the auto-arima function it (in addition) chooses the model specification automatically. So basically the prior data analysis is a pre-requisite for the subsequent forecasts. It is worth noting that the red line that you see here represents the fitted values, i.e. your model is using all the data-points up to the last time point to calculate them and produce the numbers. Maybe see more here if that point is a bit unclear: https://stats.stackexchange.com/questions/260899/what-is-difference-between-in-sample-and-out-of-sample-forecasts If you wanted to do "out-of-sample" forecasts for the past data (2000-2004) then this is also possible, but you would just need to fit, say on 2000-2002, produce a forecast for 1 step, then roll 1 quarter forward and repeat the same etc. etc. A: If you want them into a data.frame and plot the real values vs the fitted + the predicted, you can try this: df <- data.frame( # your data and some NAs, for the forecasting real = c(tsData, rep(NA,length(data.frame(myForcast)$Point.Forecast ))) # in a vector the fitted and the predicted , pred = c(myModel$fitted, data.frame(myForcast)$Point.Forecast) # the time for the plot , time = c(time(tsData), seq(2004,2005.75, by = 0.25) )) plot(df$real, xlab = "time", ylab = "real black, pred red", type = "b", pch = 19,xaxt="n") lines(df$pred, col = "red") axis(1, at=1:24, labels=df$time) For the theory part, as already said, the fitted values are calculated when you run your model. Running the model is the base for the forecasting, but you can have the fitted without forecasting of course.
doc_1752
Following works until column Z1. But I have more columns after Z column. So, if I add ws.Cells["AA"].Value = "MyColumn";, following does not work.: ws.Cells["A1"].Value = "Number"; ws.Cells["B1"].Value = "First Name"; ws.Cells["C1"].Value = "Last Name"; ws.Cells["D1"].Value = "Country"; .... .... ws.Cells["Z1"].Value = "Country"; ws.Cells["AA"].Value = "MyColumn"; A: You're missing the row number? ws.Cells["AA1"].Value = "MyColumn";
doc_1753
I would like to find the camera matrix for the same. I used the following calculation to find cx,cy cx = shape[1]/2 cy = shape[0]/2 How do I find an approximate fx and fy? I tried to use shape[1] as my focal length but it doesn't seem to work for some reason :( A: As you mentioned, shape[1] is the width of your image. So you obviously can't use it as the focal length. There is no way to determine the focal length based on the image size alone. You either know the intrinsic parameters of your camera or you need to calibrate it. For more information, see the following docs: https://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html https://docs.opencv.org/3.4/dc/dbb/tutorial_py_calibration.html
doc_1754
The usual if (...) { mytext. addEventListener('keydown', myhandler ,true); } else { mytext.attachEvent('onkeydown', myhandler ); // older versions of IE } This works perfectly fine. My problem begins when somebody using my API register an event listener keydown as well. How can I ensure that certain events are not passed to his/her code unless I want so ? In short, that would imply that event-notification would reach me first which I believe is not guaranteed to be the case ? Note: this is nothing to do with event-propagation on parent events (bubbling up). I am just dealing with another listener on the same HTML element Any suggestions, ideas ? I thought of overriding the methods attachEvent and addEventListener but I am not sure if it's a sound idea or not. Thanks A: I also wouldn't recommend to override the addEventListener method. But I also think that it can't be bad to try certain things out for oneself to test and see if and where there are certain problems. So anyway, here is an idea of how you could do it: var f = Element.prototype.addEventListener; Element.prototype.addEventListener = function(type, func, x){ var that = this; if (that.evts === undefined) { that.evts = {}; } if (that.evts[type] === undefined) { that.evts[type] = []; f.call(that, type, function(){ for (var i = 0; i < that.evts[type].length; i++) { that.evts[type][i].apply(that, arguments); } }, x); } that.evts[type].push(func); }; I'm not a hundred percent confident that I didn't miss something but in theory this should override the method in a way, that the order in which eventlisteners are added should be the same as the order in which the handlers are executed. This is done by saving the handler functions in an array, every time the addEventListener method is called, and only add one single eventlistener that traverses that array and executes every function in it. Of course you would also have to change the removeEventListener method to remove the items in your array. And you would have to do the same for Document.prototype.addEventListener and Window.prototype.addEventListener. FIDDLE Note that I added a property called evts (which contains the function arrays) to the element to which the listener was added. This is probably not the best way to do it, since anyone can override that property. It probably would be better to store your arrays somewhere in a local variable or at least rename it to something that is unlikely to be overridden by accident.
doc_1755
docker-compose build && docker-compose push I pulled my code changes from git to the server but the server isn't reflecting my code changes.
doc_1756
Example Table 1 Field1 | Field2 | Field3 | date_posted -------------------------------------- Blah | Blah2 | Blah3 | 2013-02-01 Table 2 Field4 | Field 5 | date_posted ------------------------------ Blah4 | Blah5 | 2013-01-01 Result Field1 | Field2 | Field3 | Field4 | Field5 | date_posted -------------------------------------------------------- Blah | Blah2 | Blah3 | NULL | NULL | 2013-02-01 NULL | NULL | NULL | Blah4 | Blah5 | 2013-01-01 The reason for this is I have previously setup a database to display these tables on separate pages and now the client wants to combine them into a single page. If i run the queries separately and then combine the data in php there are certain issues such as pagination as well as having to select a set amount of each even if they are not the latest. A: No join necessary: select field1, field2, field3, null as field4, null as field5, date_posted from table_1 union all select null, null, null, field4, field5, date_posted from table_2 To sort by a specific column, just add an order by select field1, field2, field3, null as field4, null as field5, date_posted from table_1 union all select null, null, null, field4, field5, date_posted from table_2 order by date_posted Note that in a UNION the order by always works on the full result, not on the individual parts. So even if it's placed right after the second select, it will sort everything. To implement paging using LIMIT A: SELECT Field1, Field2, Field3, date_posted FROM Table1 UNION SELECT Field4, Field5, date_posted FROM Table2 ORDER BY date_posted LIMIT 20 A: Try this: select field1, field2, field3, null field4, null field5, date_posted from table1 union all select null field1, null field2, null field3, field4, field5, date_posted from table2 SQL Fiddle: http://sqlfiddle.com/#!2/69a46/1
doc_1757
The images are uiviews backed with a subclassed calayer, the images are drawn on separate thread to minimise scrolling sticking. This is great but this means while you scroll down, loading so many images is now no problem, but the images just pop in when they are ready, with no finesse. So Just before the images come into view whilst scrolling I'm using an animation block to animate the images to 'spring' out. Obviously this causes sticking as I constantly keep committing animations on each image/view. Ive been looking at using lower level ca-transactions or ca grouping, but does anyone know directly if there is an advanced way of whilst scrolling, adding/feeding these animation blocks(or a low level alternative to blocks) into the animation tree whilst the render is passing (in flight), without any blocking? Each image has its own calayer, is grouping these layers causing the animations to delay? Thanks apologies for my short understanding, in all the advanced explanations of core animations on apple and in forums no one has directly spoken about this problem or a way around this ( most discussion is on implicit changes to the presentation tree on existing animation objects, rather than a way a dynamically adding animation objects to the same rendering tree real time ) or could i be missing something simple on performance, has anyone had a similar problem of animating views whilst scrolling?
doc_1758
container.Register(Component.For<ISession>().LifestylePerWebRequest().ImplementedBy<SessionImpl>()); This is all the relevant code as far as I'm aware. Resolving for ISession works fine, receiving a SessionImpl object. SessionImpl is just a dummy object I created to show the problem: public class SessionImpl : ISession { public SessionImpl() { //Called once } public void Dispose() { //Called once } } I first noticed the problem when the ISession I got on the next request was already disposed - so I am sure I am getting the same ISession every time. Any ideas what I can have done wrong? It says Castle Windsor 3.0.0 in Solution Explorer -> References. A: You have a lifestyle mismatch. Fix it.
doc_1759
can u help me? XSLT: <xsl:for-each select="//n1:Invoice/cbc:Note"> <b>Not: </b> <xsl:value-of select="."/> <xsl:text> krş.</xsl:text> <br/> </xsl:for-each>
doc_1760
Also, if I was to initialise an array with the obstacles in an array how would I best code this to avoid those certain plots. Thank you. A: Sounds like you're looking for a pathfinding algorithm. The only one that comes to mind is A-Star, or "A*". The short version is that it recursively picks a random "next node" from the nodes it hasn't checked, being more likely to pick nodes that are physically closer to the goal. This is a commonly-used function that you may want to find a tutorial for (it doesn't have to be a JavaScript tutorial as long as you can reuse the concepts in JavaScript)
doc_1761
NOTE This is happening within an ephemeral docker container for testing. Any pointers or help with this, would be greatly appreciated. A: If you want to run fish functions from outside fish, use fish -c with a fish command line as one string. For example, this fails... env __fish_pwd ...but this works: env fish -c __fish_pwd This is because env runs executables, not fish functions. I assume spin is like this too.
doc_1762
This is my code: func reloadData() { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Person") do { let results = try managedContext.executeFetchRequest(fetchRequest) let people = results as! [NSManagedObject] for person in people { collectionViewData.append(person) } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } dispatch_async(dispatch_get_main_queue()) { self.collectionView?.reloadData() } } } How to implement this with NSPrivateQueueConcurrencyType and stuff like that in Swift? A: Your code will almost certainly fail. You are accessing your main managed object context from a background thread. From your code it seems that you do not need a background fetch. Remove all GCD (grand central dispatch) parts of your code and you should be fine. For reference, this is how you do a background operation in Core Data: let moc = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) moc.parentContext = <insert main context here> moc.performBlock { // make changes, fetch, save } After saving, your main context will have the changes. To update a table view, implement NSFetchedResultsController and its delegate methods to do it automatically.
doc_1763
× 31:15 Expected to return a value in arrow function. Here is the code : to.map(item => { if (currencies[item]) { loading.succeed(`${chalk.green(money.convert(amount, {from, to: item}).toFixed(2))} ${`(${item})`} ${currencies[item]}`); } else { loading.warn(`${chalk.yellow(` The ${item} currency not found `)}`); } }); If you want, you can also view the full file HERE. I was searching for a eslint rule, but i couldn't find one :( What should i do to ignore/fix this error? A: XO Code Style is pointing out that your map callback never returns a value, but map expects the callback to do so. What should i do to ignore/fix this error? Use the right tool for the job. If you're not mapping the entries into a new array, don't use map; use forEach (or any of the many other ways to loop through an array). The purpose of map is to create a new array with entries that are a transformation of some kind of the original array's entries. A: You forgot to return a value in the .map's arrow function, which is not intended unless you want an array of undefineds. Use a for..of loop instead.
doc_1764
python alex_net.py I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcublas.so locally I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcudnn.so locally I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcufft.so locally I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcuda.so.1 locally I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcurand.so locally ^[I tensorflow/core/common_runtime/gpu/gpu_device.cc:951] Found device 0 with properties: name: GeForce GTX TITAN X major: 5 minor: 2 memoryClockRate (GHz) 1.076 pciBusID 0000:05:00.0 Total memory: 11.92GiB Free memory: 11.81GiB I tensorflow/core/common_runtime/gpu/gpu_device.cc:972] DMA: 0 I tensorflow/core/common_runtime/gpu/gpu_device.cc:982] 0: Y I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN X, pci bus id: 0000:05:00.0) I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN X, pci bus id: 0000:05:00.0) --------------------------------- Run id: alexnet_oxflowers17 Log directory: /tmp/tflearn_logs/ --------------------------------- Training samples: 132162 Validation samples: 14685 -- -- Traceback (most recent call last): File "alex_net.py", line 114, in <module> snapshot_epoch=False, run_id='alexnet_oxflowers17') File "/home/psxts3/.virtualenv/lib/python2.7/site-packages/tflearn/models/dnn.py", line 188, in fit run_id=run_id) File "/home/psxts3/.virtualenv/lib/python2.7/site-packages/tflearn/helpers/trainer.py", line 277, in fit show_metric) File "/home/psxts3/.virtualenv/lib/python2.7/site-packages/tflearn/helpers/trainer.py", line 684, in _train feed_batch) File "/home/psxts3/.virtualenv/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 717, in run run_metadata_ptr) File "/home/psxts3/.virtualenv/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 894, in _run % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape()))) ValueError: Cannot feed value of shape (64, 277, 277, 3) for Tensor u'InputData/X:0', which has shape '(?, 227, 227, 3)' I am using cv2 to read in the images and resize them to 277 by 277 pixels, all of the images are then stored in an array, X, which has the shape of [146847, 277, 277, 3]. The labels are stored in multiple csv files and are read into an array, Y, and has shape of [146847, 5]. Each label has 5 different classes, ranging from 0 to 1 in 0.2 steps. The network code is as follows: net = input_data(shape=[None, 227, 227, 3]) net = conv_2d(net, 96, 11, strides=4, activation='relu') net = max_pool_2d(net, 3, strides=2) net = local_response_normalization(net) net = conv_2d(net, 256, 5, activation='relu') net = max_pool_2d(net, 3, strides=2) net = local_response_normalization(net) net = conv_2d(net, 384, 3, activation='relu') net = conv_2d(net, 384, 3, activation='relu') net = conv_2d(net, 256, 3, activation='relu') net = max_pool_2d(net, 3, strides=2) net = local_response_normalization(net) net = fully_connected(net, 4096, activation='tanh') net = dropout(net, 0.5) net = fully_connected(net, 4096, activation='tanh') net = dropout(net, 0.5) net = fully_connected(net, num_classes, activation='softmax') net = regression(net, optimizer='momentum', loss='categorical_crossentropy', learning_rate=0.001) where the num_classes = 5. model = tflearn.DNN(net, checkpoint_path='model_alexnet', max_checkpoints=1, tensorboard_verbose=2) model.fit(X, Y, n_epoch=1000, validation_set=0.1, shuffle=True, show_metric=True, batch_size=64, snapshot_step=200, snapshot_epoch=False, run_id='alexnet_oxflowers17') Any further information need please ask. A: As nessuno said in the first comment, you are feeding the wrong size image in to the graph. Change your first line to the following. net = input_data(shape=[None, 277, 277, 3])
doc_1765
I'm passing the selected value from DropDownList through QueryString and showing items according that value in child page. I'm writing code in C# in ASP.Net using visual studio 2011. if (!IsPostBack) { ViewState["id"] = null; if (drpdwnCategory.Items.Count < 1) { fillDropList(); } } if (Request.QueryString["catId"] != null) { drpdwnCategory.SelectedIndex = _drpdwnCategory.Items.IndexOf(drpdwnCategory.Items.FindByValue(enrpt.getdecrept(Request.QueryString["catId"]))); } A: if(!IsPostback) { // code to only run at first page load here // fill dropdown } A: You still have to bind the dropdown on page load of the child pages, otherwise your dropdown would not have any values inside. What you can do is to check for the querystring on your masterpage, and then set the SelectedValue property of the dropdown to whatever is in the querystring during your dropdown databind. A: You can check if dropdown has items. and if it has items you dont bind again.
doc_1766
It does so with Firefox, however, the background does not cover the content to the right of the scrollbar. Furthermore, IE and Chrome both push #content down, and don't even show a scrollbar. EDIT. Below is an image showing my desired appearance. Note that #content has a scroll bar. How is this accomplished? https://output.jsbin.com/huwagajome body,div {margin:0;padding:0;} #header { height:60px; background:url(http://s1.postimg.org/e250ntgmz/header.png) repeat-x #e2e2e2;} #footer { height:60px; background:url(http://s8.postimg.org/3td1ckaph/footer.png) repeat-x #e2e2e2;} #wrapper { background-image:url(http://s24.postimg.org/781yqtfdh/background2.jpg); background-repeat: no-repeat; background-size: cover; background-position: center; height:840px; } #sidebar { background: rgba(255, 255, 255, .3); border-right: 4px solid #f15a29; height:100%; width:50px; float:left; } #sidebar p { -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -o-transform: rotate(-90deg); -ms-transform: rotate(-90deg); transform: rotate(-90deg); position: relative; top: 50%; font-size:30px; white-space: nowrap; } #content { margin:0 auto; padding-top:45px; width: 960px; height:100%; /*overflow-x:auto;*/ overflow:auto; /* position:relative; */ /* clear:both; */ } <div id="header"></div> <div id="wrapper"> <div id="sidebar"><p>Sidebar</p></div> <div id="content"> Ius ne quod posidonium, agam apeirian gubergren id eos, dolores percipit vis ex. Ex discere liberavisse his, sonet nominati conclusionemque et vis. Et admodum oporteat sit, eam facer affert mediocritatem ad, mea id omnium instructior. Pri ex natum option incorrupte, sit unum pertinax theophrastus ut. Nam an saperet delectus tractatos. Ad option persecuti appellantur usu. Dicta habemus fuisset per ea, ius adhuc iracundia ei. Te timeam integre pro, ex dolore possim audiam vis. Nam te tamquam omittam, eu diceret complectitur ius, quem omnesque sensibus in vel. Has eirmod accumsan atomorum ut, vel ei quod omittantur, expetendis neglegentur eu vim. Ad audiam fuisset cum. Quis mutat fabellas te nam, usu ut sumo suscipiantur, eos at lorem aeque graeci. In paulo disputationi ius, vide dissentias sadipscing eos cu. Usu te graece vivendo, ludus latine nonumes te has. Pri id quando tantas offendit, nam ea viderer dissentiet. Facilis consequat concludaturque sea ut, an mel persius evertitur eloquentiam. Facilisis repudiare conceptam sit an. </div> </div> <div id="footer"></div> A: Add a min-width to #wrapper. Not only will it work with IE and Chrome, FF will cover all content. #wrapper{min-width: 1015px;/*960px(content)+50px(sidebar)+ a little extra for good measures*/} https://output.jsbin.com/nuholiguso
doc_1767
Property Name Data Year \ 467 GALLERY 37 2018 477 Navy Pier, Inc. 2016 1057 GALLERY 37 2015 1491 Navy Pier, Inc. 2015 1576 GALLERY 37 2016 2469 The Chicago Theatre 2016 3581 Navy Pier, Inc. 2014 4060 Ida Noyes Hall 2015 4231 Chicago Cultural Center 2015 4501 GALLERY 37 2017 5303 Harpo Studios 2015 5450 The Chicago Theatre 2015 5556 Chicago Cultural Center 2016 6275 MARTIN LUTHER KING COMMUNITY CENTER 2015 6409 MARTIN LUTHER KING COMMUNITY CENTER 2018 6665 Ida Noyes Hall 2017 7621 Ida Noyes Hall 2018 7668 MARTIN LUTHER KING COMMUNITY CENTER 2017 7792 The Chicago Theatre 2018 7819 Ida Noyes Hall 2016 8664 MARTIN LUTHER KING COMMUNITY CENTER 2016 8701 The Chicago Theatre 2017 9575 Chicago Cultural Center 2017 10066 Chicago Cultural Center 2018 GHG Intensity (kg CO2e/sq ft) 467 7.50 477 22.50 1057 8.30 1491 23.30 1576 7.40 2469 4.50 3581 17.68 4060 11.20 4231 13.70 4501 7.90 5303 18.70 5450 NaN 5556 10.30 6275 14.10 6409 12.70 6665 8.30 7621 8.40 7668 12.10 7792 4.40 7819 10.20 8664 12.90 8701 4.40 9575 9.30 10066 7.50 A: Here is an example, with a a different data frame to test: import pandas as pd df = pd.DataFrame(data={'x': [3, 5], 'y': [4, 12]}) def func(df, arg1, arg2, arg3): ''' agr1 and arg2 are input columns; arg3 is output column.''' df = df.copy() df[arg3] = df[arg1] ** 2 + df[arg2] ** 2 return df Results are: print(func(df, 'x', 'y', 'z')) x y z 0 3 4 25 1 5 12 169 A: You can try this code def GHG_Intensity(PropertyName, Year): Intensity = df[(df['Property Name']==PropertyName) & (df['Data Year']==Year)]['GHG Intensity (kg CO2e/sq ft)'].to_list() return Intensity[0] if len(Intensity) else 'GHG Intensity Not Available' print(GHG_Intensity('Navy Pier, Inc.', 2016))
doc_1768
x[i:j] = y[k:l] How can I do that in Scala or even Java? A: You can use a combination of .patch and .slice: scala> val a = Array.range(1, 20) a: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) scala> val b = Array.range(30, 50) b: Array[Int] = Array(30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49) scala> a.patch(5, b.slice(5, 10), 5) res5: Array[Int] = Array(1, 2, 3, 4, 5, 35, 36, 37, 38, 39, 11, 12, 13, 14, 15, 16, 17, 18, 19) The parameters of .slice are: * *the element to start from (i in your python exemple) *the array to insert (y[k:l], here using .slice to select from k to l) *the number of element to replace in the array (unclear about what happens in your exemple when i:j is smaller than k:l, but I would guess it would be j-i here)
doc_1769
I've got a function that checks drives if they're flash drives, and only those are supposed to be selectable by the user. The Dialog does have a filter, but all I've seen it used with are file endings, and I'm not sure how I'd go about to limiting drives. Is there any possible way or will I have to restrict this myself in the program? A: You can reject attempts to change to certain drives via IFileDialogEvents::OnFolderChanging, but that's about it. See IFileDialog
doc_1770
The fragments are not changing when clicking on the bottom navigation view. Note: I am trying to implement the bottom navigation view inside another fragment. (Not an activity like in the codelab example) MainActivity.kt: class MainActivity : AppCompatActivity() { // Data binding private lateinit var mainActivityBinding: MainActivityBinding // On activity creation starting override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Set activity layout mainActivityBinding = DataBindingUtil.setContentView(this, R.layout.main_activity) } } main_activity.xml <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".activity.MainActivity"> <data> </data> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/main_activity_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/main_activity_nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="0dp" android:layout_height="0dp" app:defaultNavHost="true" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph="@navigation/activity_navigation" /> </androidx.constraintlayout.widget.ConstraintLayout> </layout> activity_navigation.xml: <?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_navigation" app:startDestination="@id/mainFragment"> <fragment android:id="@+id/mainFragment" android:name="com.appz.abhi.moneytracker.view.main.MainFragment" android:label="main_fragment" tools:layout="@layout/main_fragment" /> </navigation> MainFragment.kt: class MainFragment : Fragment() { // Data binding private var mainFragmentBinding: MainFragmentBinding? = null // On fragment view creation starting override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the fragment layout mainFragmentBinding = DataBindingUtil .inflate(inflater, R.layout.main_fragment, container, false) // Return root view return mainFragmentBinding!!.root } // On fragment view creation completion override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Initialize UI initUI() } // Initialize UI private fun initUI() { // Setup action bar (activity as AppCompatActivity).setSupportActionBar(mainFragmentBinding?.mainFragmentToolbar) // Setup bottom navigation view setUpBottomNavigationView() } // Setup bottom navigation view private fun setUpBottomNavigationView() { // Nav host fragment val host: NavHostFragment = activity?.supportFragmentManager ?.findFragmentById(R.id.main_fragment_nav_host_fragment) as NavHostFragment? ?: return // Set up Action Bar val navController = host.navController // Setup bottom navigation view mainFragmentBinding?.mainFragmentBottomNavigationView?.setupWithNavController(navController) } } main_fragment.xml: <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".view.main.MainFragment"> <data> </data> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/main_fragment_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.appbar.AppBarLayout android:id="@+id/main_fragment_app_bar_layout" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.appcompat.widget.Toolbar android:id="@+id/main_fragment_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@drawable/toolbar_background" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" tools:title="Money Tracker" /> </com.google.android.material.appbar.AppBarLayout> <fragment android:id="@+id/main_fragment_nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="0dp" android:layout_height="0dp" app:defaultNavHost="true" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/main_fragment_app_bar_layout" app:navGraph="@navigation/bottom_navigation_view_navigation" /> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/main_fragment_bottom_navigation_view" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@color/white" app:itemIconTint="@color/bottom_navigation" app:itemTextColor="@color/bottom_navigation" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:menu="@menu/bottom_navigation_view_menu"/> </androidx.constraintlayout.widget.ConstraintLayout> </layout> bottom_navigation_view_navigation.xml: <?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/bottom_navigation_view_navigation" app:startDestination="@id/settingsFragment"> <fragment android:id="@+id/homeFragment" android:name="com.appz.abhi.moneytracker.view.home.HomeFragment" android:label="Home" tools:layout="@layout/home_fragment" /> <fragment android:id="@+id/settingsFragment" android:name="com.appz.abhi.moneytracker.view.settings.SettingsFragment" android:label="Settings" tools:layout="@layout/settings_fragment" /> </navigation> bottom_navigation_view_menu: <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@id/homeFragment" android:icon="@drawable/ic_home_black_24dp" android:title="@string/home" app:showAsAction="ifRoom" /> <item android:id="@id/settingsFragment" android:icon="@drawable/ic_settings_black_24dp" android:title="@string/settings" app:showAsAction="ifRoom" /> </menu> HomeFragment.kt: class HomeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.home_fragment, container, false) } } SettingsFragment.kt: class SettingsFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.settings_fragment, container, false) } } A: It doesn't seem like you ever get to the setupWithNavController line. You use findFragmentById(R.id.main_fragment_nav_host_fragment) with the activity's FragmentManager, but the NavHostFragment in the activity is under the id main_activity_nav_host_fragment. You should be using childFragmentManager if you want to get the nested NavHostFragment in your MainFragment's layout: // Nav host fragment val host: NavHostFragment = childFragmentManager .findFragmentById(R.id.main_fragment_nav_host_fragment) as NavHostFragment? ?: return Note that there are very few cases where you actually want or need a nested NavHostFragment like this. As per the Listen for navigation events documentation, generally if you want global navigation such as a BottomNavigationView to only appear on some screens, you'd add an OnDestinationChangedListener and change its visibility there. A: NOTE: I don't have experience with Kotlin but I'm assuming the implementation is similar enough in Java. It seems odd that you are doing the bottom navigation inside a fragment where in my experience the bottom nav bar goes in the activity and you programmatically set the first fragment. The fragments that come into view using the navigation bar populate a FrameLayout that sits above the nav bar in the activity. Here is an example in Java. MainActivity.java public class HomeActivity extends AppCompatActivity { private String currentFragmentTag; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { /* I just put some filler code but each fragment type will probably be different */ switch (item.getItemId()) { case R.id.fragment_one: CustomFragment fragment = new CustomFragment(); if (!currentFragmentTag.equals(fragment.fragmentTag)) { switchFragment(customFragment, null); } return true; case R.id.fragment_two: CustomFragment fragment = new CustomFragment(); if (!currentFragmentTag.equals(fragment.fragmentTag)) { switchFragment(customFragment, null); } return true; case .... } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); currentFragmentTag = "FIRST_FRAGMENT"; BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); } /** * Select fragment. */ public void switchFragment(Fragment fragment, String tag) { getSupportFragmentManager().beginTransaction().replace(R.id.home_frame, fragment, tag) .addToBackStack(tag).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit(); } MaiActivity layout file <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activities.MainActivity"> <android.support.design.widget.BottomNavigationView android:id="@+id/navigation" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@color/background_grey" app:itemIconTint="@color/white" app:itemTextColor="@color/white" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:menu="@menu/navigation" /> <FrameLayout android:id="@+id/home_frame" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" app:layout_constraintBottom_toTopOf="@+id/navigation" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> </FrameLayout> </android.support.constraint.ConstraintLayout> A: For whatever reason, findNavController(R.id.nav_host_fragment) and setupActionBarWithNavController() are methods you'd call in an Activity, not in a Fragment. (I could not find any reference to it in the docs, so if anyone does, please add it in the comments, only stated on SO for now). I was doing just as you to setup my bottomNavigation // Setup bottom navigation view mainFragmentBinding?.mainFragmentBottomNavigationView?.setupWithNavController(navController) // or with kotlin synthetic bottomNavigation.setupWithNavController(findNavController()) Note: I expected the kotlin synthetic way to work since I call findNavController() from the fragment's onActivityCreated() and the fragment contains a default navHost in its layout. But nothing happened... and could not grasp why. Then this question and this great article, gave me hints on how to reach my navHost. Workaround: Reach for the activity, then you can specify the id of your navHost in the findNavController(R.id.nav_host_fragment) // find navController using navHostFragment val navController = requireActivity().findNavController(R.id.main_fragment_nav_host_fragment) // setup navigation with root destinations and toolbar NavigationUI.setupWithNavController(bottomNavigation, navController)
doc_1771
Suppose i have a rule like this: when $list: ProductList() $product: Product() from $list $product2: Product(this != product) from $list then // do something end if $list contains 2 products, A and B, this rule will fire for combinations: * *A-B *B-A For some reason I am not able to make the rule fire only once (either ONLY A-B or ONLY B-A) Does anybody know if there is a standard way to achieve the desired result? Many Thanks in advance! Regards, Kim A: You need to have a Product attribute that is comparable and unique. I'm assuming a product number: rule comp2prod when $list: ProductList() $product: Product( $pn: productNumber ) from $list $product2: Product( productNumber > $pn ) from $list then // do something end
doc_1772
namespace ProgrammingAssignment { public partial class Form1 : Form { Employee[] myEmployee = new Employee[15]; public string theFirst; public string theLast; public int theID; public double theSalary; public bool continueLoop; public Form1() { InitializeComponent(); } private void addEmployees() { do { try { theFirst = Convert.ToString(firstBox.Text); theLast = Convert.ToString(lastBox.Text); theID = Convert.ToInt32(idBox.Text); theSalary = Convert.ToDouble(salaryBox.Text); if (theFirst.Length > 0 && theLast.Length > 0 && theID > 0 && theSalary > 0) { for (int i = 0; i < myEmployee.Length; i++) { Employee emp = new Employee(theFirst, theLast, theID, theSalary); myEmployee[i] = emp; } } continueLoop = false; } catch (DivideByZeroException dz) { Console.WriteLine(dz.Message); Console.WriteLine("Zero is an invalid number."); } catch (FormatException fe) { Console.WriteLine(fe.Message); Console.WriteLine("Please add a valid number."); } } while (continueLoop); } private void lowestSalaryCheck() { var theSal = myEmployee.Min(em => em.yearlySalary); var theMin = myEmployee.Where(em => em.yearlySalary == theSal); foreach (var emp in theMin) { string message = string.Format("Lowest Salary: {0} {1} {2} {3}", emp.firstName, emp.lastName, emp.id, theSal); lowestList.Items.Add(message); } } private void saveBtn_Click(object sender, EventArgs e) { addEmployees(); } private void lowestSalary_Click(object sender, EventArgs e) { lowestSalaryCheck(); } } } A: Employee[] myEmployee = new Employee[15]; //Fill your data double minS = myEmployee.ToList().Min(x => x.theSalary); var message = myEmployee.ToList() .Where(x => x.theSalary == minS) .Select( x => string.Format("Lowest Salary: {0} {1} {2} {3}", x.theFirst, x.theLast, x.theID, x.theSalary)); A: When you add a new Employee, you seem to replace all existing Employees in your list to the newly added one: for (int i = 0; i < myEmployee.Length; i++) { Employee emp = new Employee(theFirst, theLast, theID, theSalary); myEmployee[i] = emp; } This loop runs 15 times every time you call your addEmployees function and replaces every element of your myEmployee array to a newly created Employee. In my opinion, you should use dynamic collections, so instead of Employee[] myEmployee = new Employee[15]; you could use List<Employee> myEmployee = new ArrayList<Employee>(); Then instead of for (int i = 0; i < myEmployee.Length; i++) { Employee emp = new Employee(theFirst, theLast, theID, theSalary); myEmployee[i] = emp; } You could use Employee emp = new Employee(theFirst, theLast, theID, theSalary); myEmployee.Add(emp); Your code should work after this, as I can see no problem with your LINQ queries.
doc_1773
<ObjectDataProvider x:Key="mthd" ObjectType="{x:Type l:MyClass}" MethodName="MyStaticMethod"> <ObjectDataProvider.MethodParameters> <sys:String>Test</sys:String> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> I have tried this with the static class and it fails. Since the static class cannot be instantiated with the exception of "Object reference not set to an instance of an object". Can something similar to this be done for static classes in .Net 4.0? Thanks in advance! A: Creating something like an ObjectDataProvide is really simple, you just need to use a bit of reflection. Get the class type via a Type property right from XAML along with the method name and parameters, then use GetMethod with the right BindingFlags and invoke it with the passed parameters.
doc_1774
I am able to set the PMI Modules themself, but not their submodules. I already read that some of the submodules can only be changed with JVM profiling enabled, which I've already done. I do have the problem of listing the submodules. For listing the modules, I have used the following: #------------------------------------------------# # retrieve ids # # > Server # # > PMIService # # > PMIModules # #------------------------------------------------# serverID = AdminConfig.getid("/Server:" + server + "/") pmiID = AdminConfig.list("PMIService", serverID) ... if level == "custom": pmim = AdminConfig.list('PMIModule', serverID) pmiList = AdminConfig.showAttribute(pmim,'pmimodules')[1:-1].split(" ") for modules in pmiList: modName = AdminConfig.showAttribute(modules,'moduleName') if modName == "jvmRuntimeModule": AdminConfig.modify(modules, [ ["enable", "2,1,5,4,3" ] ]) With this code, I am able to set PMI for all the modules I want. Currently I am trying this, but the result is always false: if modName == "jvmRuntimeModule>GC": AdminConfig.modify(modules, [ ["enable", "11,12,13" ] ]) modName will never be jvmRuntimeModule>GC because it's a submodule... Does anyone know if there is a possibility to list the submoules as well ? Thanks a lot for your help, Jérôme
doc_1775
What a string looks like? body, html{ font-family:'Poppins', sans-serif; background-color:white; overflow-x:hidden; } body{ overflow-y:hidden; } header{ position:relative; z-index:2; } What should the result be? body, html{ } body{ } header{ } I have $string = 'body, html{ overflow-x:hidden; } body{overflow-y:hidden; } header{ position:relative; z-index:2; }'; and need to get $string = 'body, html{} body{} header{}'; A: try this regex preg_replace("/\{.*\}/sU", "{}", $input_lines); A: The warnings from others are founded. As careful as a regex pattern can be designed, it is still vulnerable to fringe cases and character anomalies that will silently break the method. The following is my most-carefully crafted bandaid solution. It is using alternatives and recursion in an attempt to safeguard against nested brackets, commented curly braces, and braces that exist inside of quoted substrings. I am sure that I have not considered all of the possible monkeywrenches, but this is a rabbit hole that I don't wish to spend any more time on. Code: (Demo with two sample inputs) echo preg_replace('~(?:\s*/\*.*?\*/\s*)|\{\K(?:\'[^\']*\'|"[^"]*"|/\*.*?\*/|(?:(?R)|[^}]))*~', '', $css); Or have a play with this Pattern Demo.
doc_1776
await page.waitForSelector('.modal-body', {visible: true}); There are multiple .modal-body matches, but this only seems to work if the first match is the one that becomes visible. I'm assuming the waitForSelector just finds the first match on the selector right away (regardless of whether or not it is visible) and then waits for it to become visible rather than waiting for any element to match both the selector and the option. I could create logic to count which modal should be opening.. but I'm wondering if there is a way to just wait for any element to match the entire thing (selector + option)? A: Yep, you're right. Basically, waitForSelector runs a querySelector, which grabs the first element, then blocks until that element is visible. At the time of writing, I don't believe there's a built-in way to wait for the first element matching the selector to become visible, but it's possible to implement it with the general-purpose page.waitForFunction. Here's an approach that uses Puppeteer's visibility check: const puppeteer = require("puppeteer"); // ^16.2.0 const html = ` <!DOCTYPE html> <html> <head> <style> h1 { visibility: hidden; } </style> </head> <body> <h1>foo</h1> <h1>bar</h1> <h1>baz</h1> <script> setTimeout(() => { ////////////////////////////////////////////////////////////////// // pick the index of the element you want to make visible here: // const el = document.querySelectorAll("h1")[2]; // ////////////////////////////////////////////////////////////////// el.style.visibility = "visible"; }, 5000); // delay before visibility </script> </body> </html> `; let browser; (async () => { browser = await puppeteer.launch({headless: false}); const [page] = await browser.pages(); await page.setContent(html); await page.evaluate(() => { window.isVisible = element => { // checkWaitForOptions from Puppeteer src/common/util.ts // https://github.com/puppeteer/puppeteer/blob/32400954c50cbddc48468ad118c3f8a47653b9d3/src/common/util.ts#L354 const style = window.getComputedStyle(element); const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox(); return isVisible; function hasVisibleBoundingBox() { const rect = element.getBoundingClientRect(); return !!(rect.top || rect.bottom || rect.width || rect.height); } }; }); const el = await page.waitForFunction(() => [...document.querySelectorAll("h1")].find(isVisible) ); console.log(await el.evaluate(el => el.textContent)); // will time out unless [0] is set above // await page.waitForSelector("h1", {visible: true}); })() .catch(err => console.error(err)) .finally(() => browser?.close()) ; You can change the index of the first-visible element and see that when it's 0, the foo element is found; 1, the bar element; 2 gives baz. If you use page.waitForSelector("h1", {visible: true}) then it will time out for indices 1 and 2 as expected. Yes, this is a lot of code but you can put it in a helper until (if) it becomes part of the API. Puppeteer waitForSelector on multiple selectors is sort of related but isn't exactly specific to visibility. If you want to get all elements that first become visible on a mutation, my answer in that thread shows the idea and only needs the isVisible check thrown in.
doc_1777
Now i want to create 20 routes fetching title from the Blog table with minimal code or method in routes file. And i dont want to create it manually. like whenever i add new entry to table, new route need to be created.
doc_1778
Master, Row, Job, Fields, [Detail Status Grouped Count / Summary Object] Edited: sms_jobs collection example data is : // 1 { "_id": NumberInt("1"), "company": { "id": NumberInt("1"), "name": "", "sms_gateway_id": NumberInt("1"), "sms_gateway_parameters": { "password": "", "username": "" }, "is_active": true }, "source_type": "form", "source": { "id": NumberInt("2"), "company_id": NumberInt("1"), "title": "Import Data Demo", "description": "<p>Üst Açıklama</p>", "footer_description": "<p>Alt Açıklama</p>", "thanks_message": "Katiliminiz icin tesekkur ederiz.", "sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )", "digest": null, "ts_digest": null, "is_active": true, "is_locked": false }, "description": "Import Data Demo", "status": "waiting", "job_count": NumberInt("22145"), "updated_at": ISODate("2020-08-15T17:00:49.252Z"), "created_at": ISODate("2020-08-15T16:59:10.899Z") } sms_job_details collection example data is : // 1 { "_id": NumberInt("221462"), "sms_job_id": NumberInt("1"), "gsm": "", "schedule_at": ISODate("2020-08-15T19:41:44.827Z"), "raw_message": "{name} {surname} {id_number} {form_link} {reject_link}", "message": "", "status": "waiting", // I want this statuses grouped count my master table rows in line object "expire_at": "2020-08-18T17:40:44.967Z", "updated_at": ISODate("2020-08-15T18:45:53.727Z"), "created_at": ISODate("2020-08-15T18:45:53.727Z") } // 2 { "_id": NumberInt("221463"), "sms_job_id": NumberInt("1"), "gsm": "", "schedule_at": ISODate("2020-08-15T19:41:44.827Z"), "raw_message": "{name} {surname} {id_number} {form_link} {reject_link}", "message": "", "status": "failed", // I want this statuses grouped count my master table rows in line object "expire_at": "2020-08-18T17:40:44.967Z", "updated_at": ISODate("2020-08-15T18:45:53.727Z"), "created_at": ISODate("2020-08-15T18:45:53.727Z") } // 3 { "_id": NumberInt("221464"), "sms_job_id": NumberInt("1"), "gsm": "", "schedule_at": ISODate("2020-08-15T19:41:44.827Z"), "raw_message": "{name} {surname} {id_number} {form_link} {reject_link}", "message": "", "status": "success", // I want this statuses grouped count my master table rows in line object "expire_at": "2020-08-18T17:40:44.967Z", "updated_at": ISODate("2020-08-15T18:45:53.727Z"), "created_at": ISODate("2020-08-15T18:45:53.727Z") } I experimented for approximately 4-5 hours. I could get the closest result with the following query. db.getCollection("sms_jobs").aggregate([{ $lookup: { from: "sms_job_details", localField: "_id", foreignField: "sms_job_id", as: "data" } }, { $unwind: "$data" }, { $group: { _id: { id: "$_id", status: "$data.status" }, qty: { $sum: 1 } } }, { $project: { _id: "$_id.id", qty: 1, status: "$_id.status" } }]) And get this result : // 1 { "qty": 22145, "_id": NumberInt("4"), "status": "success" } // 2 { "qty": 1, "_id": NumberInt("3"), "status": "success" } // 3 { "qty": 22142, "_id": NumberInt("1"), "status": "success" } // 4 { "qty": 1, "_id": NumberInt("1"), "status": "failed" } // 5 { "qty": 2, "_id": NumberInt("1"), "status": "waiting" } // 6 { "qty": 1, "_id": NumberInt("3"), "status": "failed" } // 7 { "qty": 3, "_id": NumberInt("3"), "status": "waiting" } What do I want ? The query result I want is as follows. // 1 { "_id": NumberInt("1"), "company": { "id": NumberInt("1"), "name": "", "sms_gateway_id": NumberInt("1"), "sms_gateway_parameters": { "password": "", "username": "" }, "is_active": true }, "source_type": "form", "source": { "id": NumberInt("2"), "company_id": NumberInt("1"), "title": "Import Data Demo", "description": "<p>Üst Açıklama</p>", "footer_description": "<p>Alt Açıklama</p>", "thanks_message": "Katiliminiz icin tesekkur ederiz.", "sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )", "digest": null, "ts_digest": null, "is_active": true, "is_locked": false }, "description": "Import Data Demo", "status": "waiting", "job_count": NumberInt("22145"), "updated_at": ISODate("2020-08-15T17:00:49.252Z"), "created_at": ISODate("2020-08-15T16:59:10.899Z"), // Added part... "status_countes": { "success": NumberInt("20"), "failed": NumberInt("2"), "waiting": NumberInt("11"), "canceled": NumberInt("0"), "total": NumberInt("33") }, } Thank you in advance for your help...
doc_1779
myImage.startAnimation(myAnimation); myImage.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //DO SOMETHING } }); myAnimation comes from an XML in anim folder which does a translational animation: <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:interpolator="@android:anim/accelerate_interpolator" android:repeatCount="infinite" android:repeatMode="reverse" android:fromYDelta="0%p" android:toYDelta="40%p" android:duration="1000"/> </set> This works fine, although this click listener is set on the space that has the image on the layout (activity_main.xml) and does not follow the animation inserted in the image. If I click on the space which belongs to the image in the layout, the click listener starts even if the image is not there due to the animation. Is there a way in which the click listener is attach to the imageview in motion? Thank you A: This happens because the xml Translate animation you are using, does not really animate the View's property, it just moves the pixels on the screen and so it just looks like it has changed position, that is why the OnClickListener is still active on the View's original position, because Android thinks the View never really moved. Simple solution use ObjectAnimator or even better ViewPropertyAnimator. Both will animate the View's property and so the OnClicklistener will also change it's position with it.
doc_1780
Here is the code (server.java): (InWorker - receive messages from users, OutWorker - send messages to users) every user has own class (thread) - MiniServer (contain two threads: InWorker and OutWorker). class InWorker implements Runnable{ String slowo=null; ObjectOutputStream oos; ObjectInputStream ois; ConcurrentMap<String,LinkedBlockingQueue<Message>> map=new ConcurrentHashMap<String, LinkedBlockingQueue<Message>>(); Message message=null; InWorker(ObjectInputStream ois,ConcurrentMap<String,LinkedBlockingQueue<Message>> map) { this.ois=ois; this.map=map; } public void run() { while(true) { //synchronized(queue) { try { message = (Message) ois.readObject(); slowo=message.msg; if(slowo!=null && !slowo.equals("Bye")) { if(!map.containsKey(message.id)) { map.putIfAbsent(message.id, new LinkedBlockingQueue<Message>()); try { map.get(message.id).put(message); } catch (InterruptedException ex) { Logger.getLogger(Communicator.class.getName()).log(Level.SEVERE, null, ex); } } else { try { map.get(message.id).put(message); } catch (InterruptedException ex) { Logger.getLogger(Communicator.class.getName()).log(Level.SEVERE, null, ex); } } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //} Thread.yield(); } } } class OutWorker implements Runnable{ String tekst=null; ObjectOutputStream oos=null; String id; Message message; ConcurrentMap<String,LinkedBlockingQueue<Message>> map=new ConcurrentHashMap<String, LinkedBlockingQueue<Message>>(); OutWorker(ObjectOutputStream oos,String id,ConcurrentMap<String,LinkedBlockingQueue<Message>> map) { this.oos=oos; this.id=id; this.map=map; } public void run() { while(true) { //synchronized(queue) { if(map.containsKey(id)) { while(!map.get(id).isEmpty()) { try { message=map.get(id).take(); } catch (InterruptedException ex) { Logger.getLogger(OutWorker.class.getName()).log(Level.SEVERE, null, ex); } try { oos.writeObject(message); oos.flush(); } catch (IOException e) { e.printStackTrace(); } } } //} Thread.yield(); }}} Here is the MiniServer and Server class: class MiniSerwer implements Runnable{ Socket socket=null; ExecutorService exec=Executors.newCachedThreadPool(); ObjectOutputStream oos=null; ObjectInputStream ois=null; String id; Queue<Message> queue=new LinkedList<Message>(); MiniSerwer(ObjectOutputStream oos,ObjectInputStream ois,String id,Queue<Message> queue) { this.oos=oos; this.ois=ois; this.id=id; this.queue=queue; } public void run() { exec.execute(new InWorker(ois,queue)); // input stream exec.execute(new OutWorker(oos,id,queue)); //output stream Thread.yield(); } } public class Serwer implements Runnable{ ServerSocket serversocket=null; ExecutorService exec= Executors.newCachedThreadPool(); int port; String id=null; Queue<Message> queue=new LinkedList<Message>(); BufferedReader odczyt=null; ObjectInputStream ois=null; Message message=null; ObjectOutputStream oos=null; Serwer(int port) { this.port=port; } public void run() { try { serversocket=new ServerSocket(port); while(true) { Socket socket=null; try { socket = serversocket.accept(); /* first message is login*/ oos=new ObjectOutputStream(socket.getOutputStream()); oos.flush(); ois=new ObjectInputStream(socket.getInputStream()); message = (Message) ois.readObject(); id=message.sender; System.out.println(id+" log in to the server"); exec.execute(new MiniSerwer(oos,ois,id,queue)); // create new thread } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { int port; port=8821; ExecutorService exec=Executors.newCachedThreadPool(); exec.execute(new Serwer(port)); } Can anyone help me ? Edit: I change queue to ConcurrentHashMap but sometimes messages are send to the wrong user. Why ? A: This is a classic producer/consumer scenario. ditch the synchronized blocks and use a BlockingQueue (InWorker calls put() and OutWorker calls take()). also, in your Server class, you should be creating a new queue per connection, not sharing the same one across all connections.
doc_1781
And how do the two resolvers work? the order?If the one with highest priority can not find a file using the String or ModelAndView returned from controller ,the next one resolver continues resolving ?? A: InternalResourceViewResolver extends UrlBasedViewResolver You can override 2 methods. Gor them from the Spring sources @Override protected View loadView(String viewName, Locale locale) throws Exception { AbstractUrlBasedView view = buildView(viewName); View result = applyLifecycleMethods(viewName, view); return (view.checkResource(locale) ? result : null); } protected AbstractUrlBasedView buildView(String viewName) throws Exception { AbstractUrlBasedView view = (AbstractUrlBasedView) BeanUtils.instantiateClass(getViewClass()); view.setUrl(getPrefix() + viewName + getSuffix()); String contentType = getContentType(); if (contentType != null) { view.setContentType(contentType); } view.setRequestContextAttribute(getRequestContextAttribute()); view.setAttributesMap(getAttributesMap()); Boolean exposePathVariables = getExposePathVariables(); if (exposePathVariables != null) { view.setExposePathVariables(exposePathVariables); } Boolean exposeContextBeansAsAttributes = getExposeContextBeansAsAttributes(); if (exposeContextBeansAsAttributes != null) { view.setExposeContextBeansAsAttributes(exposeContextBeansAsAttributes); } String[] exposedContextBeanNames = getExposedContextBeanNames(); if (exposedContextBeanNames != null) { view.setExposedContextBeanNames(exposedContextBeanNames); } return view; } As you can see loadView() creates view and then checks view.checkResource(locale) if the result is null you replace suffix and try to get the secondary view for the same name.
doc_1782
FILE *fp; fp=fopen("output.txt","w"); for(int i=0;i<7990272;i++) { fprintf(fp,"%f\n",y[i]); } fclose(fp); A: maintain a counter to track the values written on each line as follows? FILE *fp; fp=fopen("output.txt","w"); const int NUM_VALUES_PER_LINE = 2448; int count = 0; for(int i=0;i<7990272;i++) { fprintf(fp,"%f ",y[i]); count++; if (count == NUM_VALUES_PER_LINE) { fprintf(fp, "\n"); count = 0; } } fclose(fp); A: for (int i = 0; i < 3264; i++) { for (int j = 0; j < 2448; j++) fprintf(fp, "%f", y[i*2448+j]); putc('\n', fp); } The residual issue is that there won't be any spaces between the numbers as written. There are various ways to handle that; I usually use a variation on: for (int i = 0; i < 3264; i++) { const char *pad = ""; for (int j = 0; j < 2448; j++) { fprintf(fp, "%s%f", pad, y[i*2448+j]); pad = " "; } putc('\n', fp); } If you don't like the recomputation of the array subscript, you can keep another variable that simply increments monotonically: index = 0; for (int i = 0; i < 3264; i++) { const char *pad = ""; for (int j = 0; j < 2448; j++) { fprintf(fp, "%s%f", pad, y[index++]); pad = " "; } putc('\n', fp); }
doc_1783
So I have: case class Character(id: Long, foreName: String, middleNames: String, lastName: String, age: Int) //class Characters(tag: Tag) extends Table[(Int, String, String, String, Int)](tag, "characters") class Characters(tag: Tag) extends Table[Characters](tag, "characters") { def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def foreName = column[String]("forename") def middleNames = column[String]("middlenames") def lastName = column[String]("lastname") def age = column[Int]("age") // def * = (id, foreName, middleNames, lastName, age) def * = (id, foreName, middleNames, lastName, age) <> (Character.tupled, Character.unapply _) } But I get: Expression of type MappedProjection[Character, (Long, String, String, String, Int)] doesn't conform to expected type ProvenShape[Characters] But why is that? It's basically the same as: http://de.slideshare.net/rebeccagrenier509/slick-learn2 slide 7. Even if that is Slick 2 only, how can I achieve the same in Slick 3? A: It looks like you want ... extends Table[Character], not ... extends Table[Characters].
doc_1784
StringUtils.joinAll("|", obj.getAtt1(), id) the att1 is from Object and id is from listOf String which is in the Object only. Simply I want to implement below code into java8 Streams. Map<String, List<Object>> objMap = new HashMap<>(); for (Object obj : listOfObjects) { for (String id : obj.getIds()) { String key = StringUtils.joinAll("|", obj.getAtt(), id); if (objMap.containsKey(key)) { objMap.get(key).add(obj); } else { List<Objects> objList = new ArrayList<>(); objList.add(obj); objMap.put(key, objList ); } } } A: You can use stream functions like flatMap and toMap import java.util.AbstractMap.SimpleEntry; import static java.util.stream.Collectors.*; Map<String, List<Object>> objMap = listOfObjects.stream() .flatMap(obj -> obj.getIds().stream().map(id -> new SimpleEntry<>(obj.getAttr() + "|" + id, obj))) .collect(groupingBy(SimpleEntry::getKey, mapping(SimpleEntry::getValue, toList())));
doc_1785
Bitmap orig, face; public void onDraw(Canvas c) { c.drawBitmap(face); } public void onMustacheFlag() { face = Bitmap.create(orig); Canvas c = new Canvas(face); c.save(); c.scale(1f / face.getWidth(), 1f / face.getHeight()); // Draw lines, circle, rectangles with all vertices in the range [0.0f, 1.0f] c.restore(); } Also, this custom view forces height to be equal to width (it's a square form factor) A: The parameters to Canvas.scale(float, float) serve as coefficients for x e and y coordinates in drawing routines. Passing 1f / width means multiplying values assumed in the range (0, 1) by a number less then 1, thus the result of all drawing routines end up in the top left corner and is likely not visible. Instead, if I pass width and height, the code works as intended, because the range (0, 1) is mapped to (0, width): public void onMustacheFlag() { face = Bitmap.create(orig); Canvas c = new Canvas(face); c.save(); c.scale(face.getWidth(), face.getHeight()); // instead of 1 / width // Draw lines, circle, rectangles with all vertices in the range [0.0f, 1.0f] c.restore(); }
doc_1786
I've had a look at a few links on stackoverflow, but so far the easiest way I've found is to put the *.xml files into a particular folder location (e.g. WEB-INF/classes) and use something like this to retrieve them: Thread.currentThread().getContextClassLoader.getResourceAsStream("/WEB-INF/classes/data.xml") The above method is easy; however, it is obviously not Spring Injection. Is there a way to do this using Spring Injection instead? I would have thought that since configuration files can be loaded this way, that xml data could also be loaded similarly. Thanks. A: Spring provides a class called Resource which you can use to inject resource files into a spring bean. So you can do this: public class Consumer { public void setResource(Resource resource) { DataInputStream resourceStream = new DataInputStream(resource.getInputStream()); // ... use the stream as usual } ... } Then: <bean class="Consumer"> <property name="resource" value="classpath:path/to/file.xml"/> </bean> or, <bean class="Consumer"> <property name="resource" value="file:path/to/file.xml"/> </bean> You can also directly use the @Value annotation: public class Consumer { @Value("classpath:path/to/file.xml") private Resource resource; ... }
doc_1787
I could use the rpm release tag, but this is already used for release numbers and dates in case of snapshots. I don't want to overload this any further. Is there another tag or mechanism to store the last commit-id in an rpm? A: I'm not aware of anything in the Spec format specifically designed for this, but I do see a couple of options: * *Use the version tag * *You mentioned the release tag in your question, but this is for the package version, not the software version. A Git revision is much more like a software version than a package version. *For stable releases you can still use numeric tags like 1.0 if you want, but I'd advise you to make sure that this corresponds to a Git tag with the same name so your version will always be meaningful to Git. *Doing this means that you should probably also use the serial tag, so RPM can figure out how to order versions. (This may not be necessary if you tag properly and use the method below for determining your version.) *This will include the revision in the name of your package, or at least in the file name, and it sounds like you don't want that. *Name your source archive with the Git hash and then use a url tag like http://example.com/software/software-abcd123.zip. * *You will not need to include the revision in your package file name using this method. In the first case case (and possibly the second), it may be worthwhile to use git describe to determine your Git-aware version number, e.g. $ git describe HEAD 1.0.0-3-gabcd123 '-.-' | |'--.--' | | | `---- Short Git hash | | `-------- Indicates that a Git hash follows | `---------- Three commits ahead of the previous tag name `-------------- The name of the base tag Note that your RPM version cannot contain hyphens, so this version may have to be transcribed to something like 1.0.0_3_gabcd123.
doc_1788
I have a Tabbar Controller which displays a Navigation Controller. Another view controller that is being presented by the Navigation Controller displays a Modal View Controller. TabbarController --> NavigationController --> ViewController (presenting) -- | shows using modal segue | --> ViewController (presented) Steps to cause the crash: * *Access the View Controller (presenting) in hierarchy shown above. It is not root view cntrl but higher. *Trigger the segue to the modal view controller. *Pick a tab from the tab bar (whichever) and go back to the same View Controller (presenting). Picking a tab calls popToRoot on the Navigation Controller. *Again trigger the modal segue to the View Controller (presented) *Crash: Zombie object - View Controller (presented) - got messaged Why? It looks like on previous iOS when popToRoot was called and View Controller (presenting) was being cleaned up also the modal view was destroyed. So when it was accessed again it was recreated and presented. On iOS 6 from what Allocations Instrumentation shows the modal view is destroyed together with View Controller (presenting). But when it's being accessed for some reason UIKit creates a new modav view controller but then messages the old one that is not existent anymore. Doesn't make sense. One other thing that makes me wonder is that on iOS 5 Allocations Instrumentation tool never shows me the View Controller (presented) with retain count = 0 but iOS 6 does (afterwards it makes it -1). I know this is probably very difficult question to help me with but maybe someone was already tackling problems with iOS 6 and such segues? From Allocations Instrumentation tool I can tell that many things got changed in the implementation of segues on iOS 6. A: I've end up implementing custom segues for presenting those modal views. Seems like a quite good idea here. Maybe one is not supposed to display a modal view inside tab bar view?
doc_1789
index.html form to display the flights <p> <% unless @eligible_flights.empty? %> <% @eligible_flights.each do |f| %> <%= f.start_airport_id %> <% end %> <% else %> <%= "No Flights Found" %> <% end %> </p> flights controller to view def index @flights = Flight.all @eligible_flights = Flight.where("start_airport_id = ? AND end_airport_id = ? AND departure_time = ?", params[:start_airport], params[:end_airport], params[:departure_time]) end A: My best guess is that the date comparison is not working correctly, you should try implementing your query the Rails way with. @eligible_flights = Flight .where(start_airport_id: params[:start_airport]) .where(end_airport_id: params[:end_airport]) .where(departure_time: params[:departure_time])
doc_1790
Here's the text: labelText = "8 Pair Strength by JustUncleL" + "\n_____________" + "\n" + "\nAUD : " + AUD + "\nCAD : " + CAD + "\nCHF : " + CHF + "\nEUR : " + EUR + "\nGBP : " + GBP + "\nJPY : " + JPY + "\nNZD : " + NZD + "\nUSD : " + USD I don't see why it shouldn't work, but maybe I was dumb and missed something. Disclaimer: I am not JustUncleL. EDIT: So thanks to @e2e4 for the help. There are two things, however. When using the replay mode, it plots a new label every bar, which obviously overlaps with each other. I have the 'no overlapping labels' checked on, if that matters. After some playing around, this is the script for the creation of the label: if barstate.islast label.new(bar_index, low, text = labelText, style=label.style_label_down, color=#000000, size=size.normal, textcolor=color.white, yloc=yloc.abovebar) Another, probably impossible question: Is it possible to automatically order the values numerically, from highest to lowest? This isn't strictly required, so if you don't know, that is okay. A: Are AUD, CAD etc float variables ? You have to convert them to string with tostring() function: // debug AUD = 5 CAD = 5 CHF = 5 EUR = 5 GBP = 5 JPY = 5 NZD = 5 USD = 5 labelText = "8 Pair Strength by JustUncleL" + "\n_____________" + "\n" + "\nAUD : " + tostring(AUD) + "\nCAD : " + tostring(CAD) + "\nCHF : " + tostring(CHF) + "\nEUR : " + tostring(EUR) + "\nGBP : " + tostring(GBP) + "\nJPY : " + tostring(JPY) + "\nNZD : " + tostring(NZD) + "\nUSD : " + tostring(USD) if barstate.islast label.new(bar_index, low, text = labelText, style=label.style_circle)
doc_1791
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $twitter_access_token['oauth_token'], $twitter_access_token['oauth_token_secret']); $tweets = $connection->get('search/tweets', ['count' => 30, 'result_type' => 'mixed', 'q' => $hashtags]); return $tweets; Each tweet has property "text", which contains something like this: tweet object Here also can be images, quotes, etc. All of this is just text. Whithout html tags. But if I use widget, it returns something like this: tweet structure in widget As you can see, quotes, hashtags, images and other stuff are wrapped in html tags and are displayed not like just text. How can I get tweets with such text (with html tags), using search API v1.1? Thanks for any help.
doc_1792
Can we program with go language for Microsoft Sharepoint? A: Sharepoint is many things and it is unclear what you mean by "Can we program with Go for Sharepoint", but you may want to take a look at Sharepoint 2013 apps, which will support "Self-Hosted Apps", that could be written in any language. From the linked article: You could be a PHP developer with a Linux machine and still make SharePoint apps. If you're more interested in interacting with Sharepoint's APIs, it looks like Sharepoint 2013 provides a RESTful API, so again, no problem for Go. A: Q1: Unfortunately, googling for such library was not successful in my case. Q2: If MS Sharepoint (whatever that is) has some known or documented API or it can be accessed by some known or documented protocol(s) then the answer is definitely yes. A: My best guess is that this will not be possible. Sharepoint as far as I know is an ASP.NET application designed for the Microsoft IIS platform and depends on the closed-source .NET framework. Working with Sharepoint over APIs though, should be possible but judging by your question I don't think that's what you want.
doc_1793
The only potential solutions I'm seeing currently are writing to the trace and BigQuery APIs individually or querying the trace API on an ad hoc basis. The first isn't great because it would require a pretty big change to the application code (I currently just use OpenCensus with Stackdriver exporter to transparently write traces to Stackdriver). The second isn't great because it's a lot of lift to query the API for spans and write them to BigQuery and it has to be done on an ad hoc basis. A sink similar to log exporting would be great. A: Unfortunately, at this moment there is no way to Exporting Stackdriver traces to BigQuery. I noticed that exactly the same feature was already asked to be implemented on GCP side. GCP product team are already aware about this feature request and considering to implement this feature. Please note that the Feature Requests are usually not resolved immediately as it depends on how many users are demanding the same feature. All communication regarding this feature request will be done inside public issue tracker 1, also you can 'star' it to acknowledge that you are interested in it, but keep in mind that there is no exact ETA. A: Yes. It's a best practice that recommend you. * *the analysis is better, your logs are partitioned and the queries efficient. *the log format don't change. The values that you log can , but not your query structure *The logs have a limited retention period in stackdriver. With bigquery, you keep all the time that you want *It's free! At least, the sink process. You have to pay storage and bigquery processing I have 3 advices: * *think to purge your logs for reducing storage cost. However, data older than 90 days are cheaper. *before setting up a sink, select only the relevant logs entry that you want to save to bigquery. *don't forget the partition time, logs can be rapidly huge, and uncontrolled query expensive. Bonus: if you have to comply to RGPD and you have personal data in logs, be sure to list the process in your RGPD log book. A: You exporting logs to big-query , you have to create table in big-query and add data in bigquery. By default in GCP, all logs go via stack driver. To export logs in the big query from the stackdriver , you have to create Logger Sink using code or GCP logging UI Then create a Sink, add a filter. https://cloud.google.com/logging/docs/export/configure_export_v2 hen add logs to stack driver using code public static void writeLog(Severity severity, String logName, Map<String, String> jsonMap) { List<Map<String, String>> maps = limitMap(jsonMap); for (Map<String, String> map : maps) { LogEntry logEntry = LogEntry.newBuilder(Payload.JsonPayload.of(map)) .setSeverity(severity) .setLogName(logName) .setResource(monitoredResource) .build(); logging.write(Collections.singleton(logEntry)); } } private static MonitoredResource monitoredResource = MonitoredResource.newBuilder("global") .addLabel("project_id", logging.getOptions().getProjectId()) .build();
doc_1794
The relations between the tables is as follows: a company has many services, a service has many params, a service belongs to one company. I'm trying to join the companies with the services and the services with the params and return it as a json. my code is: $query = Companies::find() ->joinWith('services') ->leftJoin('params', '`services`.`id` = `params`.`serviceid`') ->asArray()->all(); return $query; However in the json i'm getting the relation between companies and services is working but the relation between services and params is not. If it helps this is the json i'm getting: Can anyone please help me? It looks like i'm missing something basic but can't figure out what it is. Thanks A: Did you set up also relations between those models ? It is much more easier to use, especialy if you need to use that relation on more than just one place. Yii2 - Working with Relational Data And then just use ActiveQuery with() method A: I found the solution. It was a nested relation issue, instead of: $query = Companies::find() ->joinWith('services') ->leftJoin('params', '`services`.`id` = `params`.`serviceid`') ->asArray()->all(); return $query; the query should look like this: $query = Companies::find() ->with('services.params') ->asArray()->all(); return $query; Yii2 understands the nested relations automatically if it's correctly set in your models. Thanks to this post Nested relations using `with` in yii2 Cheers!
doc_1795
I can access application by typing www.csxyz.com:8080/myApp from any browser/machine Now I need to access application if I type www.myApp.com
doc_1796
<?php setcookie("mycookie", "hello", time() + 3600 * 24 * 31); Then writing document.cookie in the browser's Javascript console shows the cookie. It works. Then I close and reopen the browser and go to http://www.example.com. Then writing document.cookie in the Javascript console doesn't show any cookie. How to modify this PHP code to make the cookie shared between http://example.com and http://www.example.com? A: Please correct the code like this - <?php setcookie("mycookie", "hello", time() + 3600 * 24 * 31, "/", ".example.com"); ?> This slash (/) might trigger both WWW and non WWW and also every page of the site It might work for http://example.com/* and also http://www.example.com/* It might work.
doc_1797
./aa ./b/aa ./b/bb ./c/aa ./c/d/ee I have a "sed script" dict.sed whose contents is like: s|aa|xx|g s|ee|yy|g Can I recursively find and rename files matching aa and ee to xx and yy, respectively, and preserving the directory structure, using said sed script? At the moment I have: function rename_from_sed() { IFS='|' read -ra SEDCMD <<< "$1" find "." -type f -name "${SEDCMD[1]}" -execdir mv {} "${SEDCMD[2]}" ';' } while IFS='' read -r line || [[ -n "${line}" ]]; do rename_from_sed "$line" done < "dict.sed" This seems to work, but is there a better way, perhaps using sed -f dict.sed instead of parsing dict.sed line-by-line? The current approach means I need to specify the delimiter, and is also limited to exact filenames. The closest other answer is probably https://stackoverflow.com/a/11709995/3329384 but that also has the limitation that directories may also be renamed. A: That seems odd: iterating over the lines in a sed script. You want: Can I recursively find and rename files So iterate over files, not over the sed script. find .... | while IFS= read -r file; do newfile=$(sed -f dict.sed <<<"$file") mv "$file" "$newfile" done Related https://mywiki.wooledge.org/BashFAQ/001 and https://mywiki.wooledge.org/BashFAQ/020 but is there a better way Sure - do not use Bash and do use Sed. Write the whole script in Python or Perl - it will be 1000 times faster to use a tool which will do all the operations in a single thread without any fork() calls. Anyway, you can also parse sed script line by line and run a single find call. find "." -type f '(' -name aa -execdir mv {} xx ';' ')' -o '(' -name ee -execdir mv {} yy ';' ')' You would have to build such call, like: findargs=() while IFS='|' read -r _ f t _; do if ((${#findargs[@]})); then findargs+=('-o'); fi findargs+=( '(' -name "$f" -execdir {} "$t" ';' ')' ) done < "dict.sed" find . -type f "${findargs[@]}" A: Assuming lines in the file dict is in the form of from|to, below is an implementation in pure bash, without using find and sed. #!/bin/bash shopt -s globstar nullglob while IFS='|' read -r from to; do for path in ./**/*"$from"*; do [[ -f $path ]] || continue basename=${path##*/} echo mv "$path" "${path%/*}/${basename//"$from"/"$to"}" done done < dict -- $ cat dict aa|xx ee|yy Drop the echo if you are satisfied with the output.
doc_1798
* *Are there any performance increment when we use MySQL Views in a PHP 7 MySQL application? *Are there any security increment? *Can we use MySQL Views for JSON REST API requests? A: * *As far as I know. The view is like you save a query to a database. So you can save time to write a complex query. *I think yes. Because you can grant users access to view rather than directly to the table. *To get the data is yes, but a function like edit and delete I don't think so.
doc_1799
public static void Set(ref byte aByte, int pos, bool value) { if (value) { //left-shift 1, then bitwise OR aByte = (byte)(aByte | (1 << pos)); } else { //left-shift 1, then take complement, then bitwise AND aByte = (byte)(aByte & ~(1 << pos)); } } public static bool Get(byte aByte, int pos) { //left-shift 1, then bitwise AND, then check for non-zero return ((aByte & (1 << pos)) != 0); } In these methods when I want to change first bit I have to pass position 7 Which I guess is index of last of 8 bits. Why is that? Why is first bit in byte changed with index of last? A: Why is first bit in byte changed with index of last? Basically, bits are usually referred to such that the least-significant bit is bit 0, then the next is bit 1 etc. So for example: Bit: 76543210 Value: 01000110 So a byte with value 70 (decimal) has bits 1, 2 and 6 set. Just because we write down a byte with the most significant bit first doesn't mean that we regard that as the "first bit". (Indeed, I'd probably talk about it being the "most significant bit" or "high bit" instead of using "first" at all.) The good thing about this scheme is that it means you get the same value for a bit however long the value is - bit 0 is always "worth" 1, bit 1 is always worth 2, bit 7 is always with 128 etc. Now, none of that actually affects your code, which doesn't care about what we call things, but it cares about values. Fortunately, the naming convention helps us here, too. You just need to shift a value of 1 (which is "just bit 0 set") left by pos bits to get bit pos. For example, to get bit 5, we just shift 1 left by 5 bits to get 100000. If you think about the value of 1 as a full byte (00000001) it may become clearer: 00000001 << 0 = 00000001 00000001 << 1 = 00000010 00000001 << 2 = 00000100 00000001 << 3 = 00001000 00000001 << 4 = 00010000 00000001 << 5 = 00100000 00000001 << 6 = 01000000 00000001 << 7 = 10000000