text
stringlengths
64
89.7k
meta
dict
Q: Wrapping around a python list as a slice operation Consider the following simple python code >>> L = range(3) >>> L [0, 1, 2] We can take slices of this array as follows: >>> L[1:3] [1, 2] Is there any way to wrap around the above array by shifting to the left [1, 2, 0] by simply using slice operations? A: Rotate left n elements (or right for negative n): L = L[n:] + L[:n] Note that collections.deque has support for rotations. It might be better to use that instead of lists. A: Left: L[:1], L[1:] = L[-1:], L[:-1] Right: L[-1:], L[:-1] = L[:1], L[1:]
{ "pile_set_name": "StackExchange" }
Q: Associating the key in one dictionary to the values in another dictionary I have two dictionaries. 1 of them shows people and activities they like. my_dict= {'bob': ['skiing', 'soccer', 'ballet'], 'Angela': ['skiing', 'ballet', 'hiking'] } and so on... The other dictionary shows the number of people in each activity, like so: my_dict1= {'skiing': 5, 'soccer': 8, 'ballet': 33, 'hiking': 2 } and so on... I would like the resulting dictionary to look like this: my_dict= {'bob': 46, 'Angela': 40 } I need to assign the value of my_dict1 to the associated value in my_dict. Then I need to sum them. For example, 'bob': 46 is derived from 'bob': 5+8+33 A: my_dict= {'bob': ['skiing', 'soccer', 'ballet'], 'Angela': ['skiing', 'ballet', 'hiking'] } my_dict1= {'skiing': 5, 'soccer': 8, 'ballet': 33, 'hiking': 2 } new_dic ={} for i in my_dict: new_dic[i]=sum([my_dict1[i] for i in my_dict[i]]) print(new_dic)
{ "pile_set_name": "StackExchange" }
Q: Passing function instead of string for jquery easing using CoffeeScript I'm trying to pass my own function into a jquery animation to create my own easing function. This code is written in coffeescript and is actually called, but does not perform an easing function. It merely acts like a callback function. Has anyone else experienced this? easing : (x, t, b, c, d) -> if ((t/=d) < (1/2.75)) return c*(7.5625*t*t) + b else if (t < (2/2.75)) return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b else if (t < (2.5/2.75)) return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b else return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b show : () => @container.slideDown @config.animationTime, @easing(), () => @config.visible = true A: From the fine manual: As of jQuery 1.4.3, an optional string naming an easing function may be used. So the easing argument should be a string which names the easing to use, not an easing function itself. Furthermore, this is a method call: @easing() while this is a reference to your easing function: @easing If you want to define a custom easing, you have to do it globally by adding a property to $.easing: $.easing.whatever = (x, t, b, c, d) -> #... and then you reference it by name: @container.slideDown @config.animationTime, 'whatever', () => ...
{ "pile_set_name": "StackExchange" }
Q: How to run single instance of toolbar for mutiple tabs/window of ie I have developed a internet explorer toolbar in VC++,In which user needs to log-in then i just update that user details in a menu but whenever i change the tab ,the toolbar gets log-out. How can i stop running separate instance of toolbar for each tab. A: Toolbars are in-process COM servers and IE itself uses process isolation for tabs. To make your state data survive a tab close/crash you need to move it out of IE's processes and into a broker process. You can get the state data by asking the broker process via one of interprocess communication methods (e.g. named pipe). To sync the state between tabs, save the data to the broker process in old tab's DWebBrowserEvents2 ::WindowStateChanged event handler and ask the broker process for the state data in the new tab's DWebBrowserEvents2 ::WindowStateChanged event handler.
{ "pile_set_name": "StackExchange" }
Q: angular js: Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape? Am using the angular bootstrap to present a modal. But my requirement is to prevent pop-up dismissal when clicking outside the modal, or when the escape key is pressed. I followed the tutorial on the angular bootstrap site :http://angular-ui.github.io/bootstrap/ A: Use: backdrop: 'static' backdrop - controls presence of a backdrop. Allowed values: true (default), false (no backdrop), 'static' - backdrop is present but modal window is not closed when clicking outside of the modal window. For example: $modal.open({ templateUrl: 'myModalContent.html', controller: ModalInstanceCtrl, backdrop: 'static' }) A: Add both backdrop: static and keyboard: false to your modal options. The first one disables the background click, the second one the escape key. backdrop: 'static' - backdrop is present but modal window is not closed when clicking outside of the modal window. keyboard - indicates whether the dialog should be closable by hitting the ESC key, defaults to true. Example: $modal.open({ templateUrl: 'template.html', controller: TheController, backdrop: 'static', keyboard: false }) See the docs for more information. A: "backdrop - controls presence of a backdrop. Allowed values: true (default), false (no backdrop), 'static' - backdrop is present but modal window is not closed when clicking outside of the modal window." - in http://angular-ui.github.io/bootstrap/#/modal Try: <div ng-controller="ModalDemoCtrl" data-backdrop="static"> ... </div>
{ "pile_set_name": "StackExchange" }
Q: UIAnimator message sent to deallocated instance Hey guys, I'm getting crazy. *** -[UIAnimator removeAnimationsForTarget:]: message sent to deallocated instance 0x5ba13d0 It happens in different moments, when I scroll my tableview, when I switch my filter (a UISegmentedControl). Help me, I'm getting crazy with this guys :) How can I fix? A: I just solved the same problem. I thought it was related to UIAnimation, but it was related to UITableViewCell, instead. I found a good starting point looking at this article. http://marius.me.uk/blog/2011/mar/fixing-uianimator-removeanimationsfortarget-crash/ Good luck and let me know! A: I had the same symptom (crash caused by [UIAnimator removeAnimationsForTarget:] message being sent to deallocated UITableViewCell, but it turned out to have been caused by a reason different from the one cited in the above solution. It turned out that the reason was that my UI was being updated by a non-UI thread. Specifically, I was calling popViewController:animated: from a background thread. When I moved this invocation to the UI thread via a callback the problem went away.
{ "pile_set_name": "StackExchange" }
Q: You are trying to install in deployment mode after changing your Gemfile I'm trying to deploy my Rails app to my DigitalOcean server with cap production deploy But I'm getting an error, (Backtrace restricted to imported tasks) cap aborted! SSHKit::Runner::ExecuteError: Exception while executing as [email protected]: bundle exit status: 16 bundle stdout: You are trying to install in deployment mode after changing your Gemfile. Run `bundle install` elsewhere and add the updated Gemfile.lock to version control. You have deleted from the Gemfile: * rails-assets-angular-devise You have changed in the Gemfile: * rails-assets-angular-devise from `no specified source` to `rubygems repository https://rubygems.org/, https://rails-assets.org/` bundle stderr: Nothing written SSHKit::Command::Failed: bundle exit status: 16 bundle stdout: You are trying to install in deployment mode after changing your Gemfile. Run `bundle install` elsewhere and add the updated Gemfile.lock to version control. You have deleted from the Gemfile: * rails-assets-angular-devise You have changed in the Gemfile: * rails-assets-angular-devise from `no specified source` to `rubygems repository https://rubygems.org/, https://rails-assets.org/` bundle stderr: Nothing written Tasks: TOP => deploy:updated => bundler:install (See full trace by running task with --trace) The deploy has failed with an error: Exception while executing as [email protected]: bundle exit status: 16 bundle stdout: You are trying to install in deployment mode after changing your Gemfile. Run `bundle install` elsewhere and add the updated Gemfile.lock to version control. You have deleted from the Gemfile: * rails-assets-angular-devise You have changed in the Gemfile: * rails-assets-angular-devise from `no specified source` to `rubygems repository https://rubygems.org/, https://rails-assets.org/` bundle stderr: Nothing written alucardu@alucardu-VirtualBox:~/sites/movieseat(Deploy) $ source "https://rails-assets.org" do bash: https://rails-assets.org: No such file or directory alucardu@alucardu-VirtualBox:~/sites/movieseat(Deploy) $ gem "rails-assets-angular-devise" ERROR: While executing gem ... (Gem::CommandLineError) Unknown command rails-assets-angular-devise alucardu@alucardu-VirtualBox:~/sites/movieseat(Deploy) $ end There is something wrong with my Gemfile and the Gemfile.lock and it has to do with rails-assets-angular-devise but I can't figure out how to fix it. I've tried running bundle install on my server but still the same error. I've tried removing the Gemlock.file and doing bundle install on my local and then commiting it and pushing it to my deploy branch but still the same error. This is the rails-assets-angular-devise part in the gemfile. source "https://rails-assets.org" do gem "rails-assets-angular-devise" end A: Check bundler version on server in correctly gemset - probably you have old bundler version in your gemset or local gem (if you doesn't use rvm on server) I have the same problem, steps to resolved it: login to server switch rvm to correctly for your application $ gem update bundler close ssh session and try again cap [env] deploy
{ "pile_set_name": "StackExchange" }
Q: Println the return values of an executable I have deploy an matlab .m file into an windows console application. The matlab file that I deploy is in fact a matlab function which have no arguments and return a list of integer. I am running that .exe from java code using process to run my executable file. I am tried to read the return values using the following code: Process process = Runtime.getRuntime().exec("epidemic.exe"); //process.waitFor(); System.out.println("...."); InputStream in = process.getInputStream(); // To read process standard output InputStream err = process.getErrorStream(); // To read process error output while (process.isAlive()) { while (in.available() > 0 || err.available() > 0) { if (in.available() > 0) { System.out.print((char)in.read()); // You might wanna echo it to your console to see progress } if (err.available() > 0) { err.read(); // You might wanna echo it to your console to see progress } } Thread.sleep(1); } System.out.println("...."); EDIT: Based on the proposed changes I re-change my code. Again, it doesn't seem print the returned values. If this code is ok, how could I check if the executable indeed return values? A: Your while loop tries to read whole lines from the standard output of the started process. I highlighted the potential problems. If the process does not write a whole line, or it writes to its standard error for example, reader.readLine() will block forever. Also note that a process has 2 output streams: standard output and standard error. Both has a buffer, and if any of them gets filled without you reading it, the process will be blocked when trying to write more outputs. To ensure the process does not get blocked, you have to read both of its output streams, here is an example how to do it: InputStream in = process.getInputStream(); // To read process standard output InputStream err = process.getErrorStream(); // To read process error output while (proc.isAlive()) { while (in.available() > 0 || err.available() > 0) { if (in.available() > 0) in.read(); // You might wanna echo it to your console to see progress if (err.available() > 0) err.read(); // You might wanna echo it to your console to see progress } Thread.sleep(1); } If you want to print the data read from the output streams of the process, you can do it like this: System.out.print((char)in.read()); // read() returns int, convert it to char
{ "pile_set_name": "StackExchange" }
Q: SQL Age Computed Column Always +1 Incorrect I have a computed column that works out a persons age. What i have is as follows: DATEDIFF(year,[DOB],COALESCE([DOD], GETDATE()) So if person is alive it works out current age from DOB, if they are deceased it works it out based on DOD and DOB. However at present the values given are not correct, mostly they report +1. Can anyone offer any advice on how to fix this? Sample data: in all three instances it is reported +1 Thanks A: datediff() probably doesn't do what you really want. As is well documented, it counts the number of "period breaks" between two values. So, 2013-12-31 and 2014-01-01 are one year apart, according to this function. One method that might be close enough is to switch to months: DATEDIFF(month, [DOB], COALESCE([DOD], GETDATE()) / 12 Or, perhaps days are good enough: DATEDIFF(day, [DOB], COALESCE([DOD], GETDATE()) / 365.25 A more accurate solution would be to add the estimated years to the original date. If later than the current date, then subtract 1: datediff(year, dob, COALESCE([DOD], GETDATE())) + (case when dateadd(year, datediff(year, dob, COALESCE([DOD], GETDATE())), dob) > COALESCE([DOD], GETDATE()) then -1 else 0 end) Here is a SQL Fiddle example.
{ "pile_set_name": "StackExchange" }
Q: How does Facebook Sharer select Images and other metadata when sharing my URL? When using Facebook Sharer, Facebook will offer the user the option of using 1 of a few images pulled from the source as a preview for their link. How are these images selected, and how can I ensure that any particular image on my page is always included in this list? A: How do I tell Facebook which image to use when my page gets shared? Facebook has a set of open-graph meta tags that it looks at to decide which image to show. The keys one for the Facebook image are: <meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/> <meta property="og:image:secure_url" content="https://secure.example.com/ogp.jpg" /> and it should be present inside the <head></head> tag at the top of your page. If these tags are not present, it will look for their older method of specifying an image: <link rel="image_src" href="/myimage.jpg"/>. If neither are present, Facebook will look at the content of your page and choose images from your page that meet its share image criteria: Image must be at least 200px by 200px, have a maximum aspect ratio of 3:1, and in PNG, JPEG or GIF format. Can I specify multiple images to allow the user to select an image? Yes, you just need to add multiple image meta tags in the order you want them to appear in. The user will then be presented with an image selector dialog: I specified the appropriate image meta tags. Why isn't Facebook accepting the changes? Once a url has been shared, Facebook's crawler, which has a user agent of facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php), will access your page and cache the meta information. To force Facebook servers to clear the cache, use the Facebook Url Debugger / Linter Tool that they launched in June 2010 to refresh the cache and troubleshoot any meta tag issues on your page. Also, the images on the page must be publicly accessible to the Facebook crawler. You should specify absolute url's like http://example.com/yourimage.jpg instead of just /yourimage.jpg. Can I update these meta tags with client side code like Javascript or jQuery? No. Much like search engine crawlers, the Facebook scraper does not execute scripts so whatever meta tags are present when the page is downloaded are the meta tags that are used for image selection. Adding these tags causes my page to no longer validate. How can I fix this? You can add the necessary Facebook namespaces to your tag and your page should then pass validation: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="https://www.facebook.com/2008/fbml"> A: When you share for Facebook, you have to add in your html into the head section next meta tags: <meta property="og:title" content="title" /> <meta property="og:description" content="description" /> <meta property="og:image" content="thumbnail_image" /> And that's it! Add the button as you should according to what FB tells you. All the info you need is in www.facebook.com/share/ A: As of 2013, if you're using facebook.com/sharer.php (PHP) you can simply make any button/link like: <a class="btn" target="_blank" href="http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo urlencode(YOUR_TITLE);?>&amp;p[summary]=<?php echo urlencode(YOUR_PAGE_DESCRIPTION) ?>&amp;p[url]=<?php echo urlencode(YOUR_PAGE_URL); ?>&amp;p[images][0]=<?php echo urlencode(YOUR_LINK_THUMBNAIL); ?>">share on facebook</a> Link query parameters: p[title] = Define a page title p[summary] = An URL description, most likely describing the contents of the page p[url] = The absolute URL for the page you're sharing p[images][0] = The URL of the thumbnail image to be used as post thumbnail on facebook It's plain simple: you do not need any js or other settings. Is just an HTML raw link. Style the A tag in any way you want to.
{ "pile_set_name": "StackExchange" }
Q: What is this data structure/concept where a plot of points defines a partition to a space I encountered an algorithm to solve a real world problem, and I remember a class I took where I made something very similar for some for a homework problem. Basically it's a plot of points, and the lines are drawn to be equidistant between two points. It forms a perfect partition where the lines around the point form the shape of area that is closest to that point. Does this ring a bell to anyone? I've had a tough time googling descriptions and getting results. And I don't know how else to describe it. Hopefully the picture helps. A: What you described is Voronoi diagram. Here is an excerpt from Wikipedia. In the simplest case, shown in the first picture, we are given a finite set of points ${p_1, \cdots, p_n}$ in the Euclidean plane. In this case each site $p_k$ is simply a point, and its corresponding Voronoi cell $R_k$ consists of every point in the Euclidean plane whose distance to $p_k$ is less than or equal to its distance to any other points. Each such cell is obtained from the intersection of half-spaces, and hence it is a convex polygon. The line segments of the Voronoi diagram are all the points in the plane that are equidistant to the two nearest sites. The Voronoi vertices (nodes) are the points equidistant to three (or more) sites. A: You are looking for a Multi-Class Classification Algorithm. I suggest you have a look at: K-Nearest Neighbors algorithm (or KNN). Here is an introductory blog post. Support Vector Machines. You can start reading up on it here.
{ "pile_set_name": "StackExchange" }
Q: Class tufte-book and R listings code box width problem When I run the following MWE: \documentclass{tufte-book} \usepackage{Sweavel} \usepackage{amsthm} \usepackage{mathtools} \usepackage{soul} %%%%%%%%%% % R example %%%%%%%%%% \newtheoremstyle{rex}{}{}{}{.45\textwidth}{}{}{1 mm}{} \theoremstyle{rex} \newtheorem{rexample}{R example}[chapter] %%%%%%%%%% % boxes %%%%%%%%%% \usepackage[framemethod=TikZ]{mdframed} \mdfdefinestyle{style2}{ backgroundcolor=gray!10, } \usepackage[strict]{changepage} %%%%%%%%%% %%%%%%%%%% % crossref %%%%%%%%%% \usepackage[capitalize,noabbrev]{cleveref} \crefname{rexample}{Example}{Examples}% %%%%%%%%%% %%%%%%%%%% % layout %%%%%%%%%% \newcommand{\blankpage}{\newpage\hbox{}\thispagestyle{empty}\newpage} %%%%%%%%%% %%%%%%%%%% % listings %%%%%%%%%% \newcommand{\indexfunction}[1]{\index{#1@\texttt{#1}}} \usepackage{listings} \lstset{language = R, frame = single, } \def\Rcolor{\color{black}} \def\Routcolor{\color{black}} \def\Rcommentcolor{\color{red}} \def\Rbackground{\color[rgb]{0.992, 0.965, 0.894}} \def\Routbackground{\color[rgb]{0.894, 0.965, 0.992}} \definecolor{lightYellow}{rgb}{0.992, 0.965, 0.894} \sethlcolor{lightYellow} %%%%%%%%%% %%%%%%%%%% % book metadata %%%%%%%%%% \title[]{} \author[]{} \publisher{} %%%%%%%%%% \begin{document} \begin{Schunk} \begin{rexample}\label{set1}\hfill{}\begin{Sinput} setS <- letters[1:5] %>% print() \end{Sinput} \begin{Soutput} [1] "a" "b" "c" "d" "e" \end{Soutput} \end{rexample}\end{Schunk} \begin{Schunk} \begin{rexample}\label{set2}\hfill{}\begin{Sinput} "e" %in% setS \end{Sinput} \begin{Soutput} [1] TRUE \end{Soutput} \begin{Sinput} "f" %in% setS \end{Sinput} \begin{Soutput} [1] FALSE \end{Soutput} \end{rexample}\end{Schunk} \end{document} which contains R input and output code, the following output is produced Notice that the width of the input box is different from the width of the output box. How do I make those equal in width? This code requires Sweavel.sty available here sweavel.sty is generated when one runs knir on an .Rnw file which contains LaTeX and R code A: You need to redefine the definition of the style Routstyle for listings. In your used file Sweavel.sty it is defined as \lstdefinestyle{Routstyle}{% fancyvrb=false, literate={~}{{$\sim$}}1{R^2}{{$R^{2}$}}2{^}{{$^{\scriptstyle\wedge}$}}1{R-squared}{{$R^{2}$}}2,% frame=single, framerule=0.2pt, framesep=1pt, basicstyle=\Routcolor\Routsize\ttfamily,% backgroundcolor=\Routbackground} You can use the following code in your preamble instead: \lstdefinestyle{Routstyle}{% language=R,% basicstyle={\Routcolor\Sweavesize\ttfamily}, backgroundcolor=\Routbackground,% } So with the following complete code \documentclass{tufte-book} \usepackage{Sweavel} \usepackage{amsthm} \usepackage{mathtools} \usepackage{soul} %%%%%%%%%% % R example %%%%%%%%%% \newtheoremstyle{rex}{}{}{}{.45\textwidth}{}{}{1 mm}{} \theoremstyle{rex} \newtheorem{rexample}{R example}[chapter] %%%%%%%%%% % boxes %%%%%%%%%% \usepackage[framemethod=TikZ]{mdframed} \mdfdefinestyle{style2}{ backgroundcolor=gray!10, } \usepackage[strict]{changepage} %%%%%%%%%% %%%%%%%%%% % crossref %%%%%%%%%% \usepackage[capitalize,noabbrev]{cleveref} \crefname{rexample}{Example}{Examples}% %%%%%%%%%% %%%%%%%%%% % layout %%%%%%%%%% \newcommand{\blankpage}{\newpage\hbox{}\thispagestyle{empty}\newpage} %%%%%%%%%% %%%%%%%%%% % listings %%%%%%%%%% \newcommand{\indexfunction}[1]{\index{#1@\texttt{#1}}} \usepackage{listings} \lstset{language = R, frame = single, } \def\Rcolor{\color{black}} \def\Routcolor{\color{black}} \def\Rcommentcolor{\color{red}} \def\Rbackground{\color[rgb]{0.992, 0.965, 0.894}} \def\Routbackground{\color[rgb]{0.894, 0.965, 0.992}} \definecolor{lightYellow}{rgb}{0.992, 0.965, 0.894} \sethlcolor{lightYellow} %%%%%%%%%% \lstdefinestyle{Routstyle}{% <========================================== language=R,% basicstyle={\Routcolor\Sweavesize\ttfamily}, backgroundcolor=\Routbackground,% } % <=================================================================== %%%%%%%%%% % book metadata %%%%%%%%%% \title[]{} \author[]{} \publisher{} %%%%%%%%%% \begin{document} \begin{Schunk} \begin{rexample} \label{set1}\hfill{} \begin{Sinput} setS <- letters[1:5] %>% print() \end{Sinput} \begin{Soutput} [1] "a" "b" "c" "d" "e" \end{Soutput} \end{rexample} \end{Schunk} \begin{Schunk} \begin{rexample} \label{set2}\hfill{} \begin{Sinput} "e" %in% setS \end{Sinput} \begin{Soutput} [1] TRUE \end{Soutput} \begin{Sinput} "f" %in% setS \end{Sinput} \begin{Soutput} [1] FALSE \end{Soutput} \end{rexample} \end{Schunk} \end{document} with the following result:
{ "pile_set_name": "StackExchange" }
Q: How to use HTML generated by JavaScript for jQuery manipulation? I have created a map using LeafletJS and added a button which serve as a trigger powered via jQuery. However using .click() event listener didn't work. So I looked at source of the page and did some experimenting. I have discovered that almost all of the code generated via JavaScript was invisible to jQuery I could not use almost any of the map's elements as triggers or influence them in any way (for example using .css()). I'd like to know two things: Why is HTML generated via JavaScript is invisible to jQuery? And is it library(LeafletJS) specific Is there a way to reach HTML generated via JavaScript library using jQuery without modifying the library it self? A: The reason you can't touch anything in there with your jQuery is because the code in LeafletJS runs asynchronously. When you run your jQuery code, the elements in question have not yet been created. You have to run your jQuery code in the whenReady callback. If you're just trying to listen to click events, you could use event delegation: $(document).on('click', 'The CSS selector', function () { // Your code here... }); This'll work, but for performance reasons you should bind the event listener to the element on which you are calling LeafletJS.
{ "pile_set_name": "StackExchange" }
Q: defer log.SetOutput(os.Stdout) after log.SetOutput(ioutil.Discard) In go-nsq library (https://github.com/bitly/go-nsq/blob/master/writer_test.go#L38), I found the following code: log.SetOutput(ioutil.Discard) defer log.SetOutput(os.Stdout) Why does the author defer logging to stdout after discard the log? A: The log.SetOutput(ioutil.Discard) statement changes the standard logger output destination. The defer log.SetOutput(os.Stdout) statement attempts to reset the output destination back to its initial value when the function ends. However, it should have reset it back to os.Stderr. src/pkg/log/log.go var std = New(os.Stderr, "", LstdFlags)
{ "pile_set_name": "StackExchange" }
Q: form file upload phonegap Please could someone upload a very basic but working version of a file upload script written in javascript that will then be phonegap friendly I've trawled the internet trying to figure it out but most of the stuff out there is either out of date or the newer stuff seems to presume that you know all about the inner workings of phonegap I grasp how to transfer the file but I cannot figure out how to explore/access the phones/tablets file system to look for the desired file for upload In a perfect world phonegap would recognise the form file upload button and convert it so it works the same as if it were in a web browser but all it seems to do is disable it. I'm using php as the sever side. I've spend days trying to understand how to do it... any help would be massively appreciated! A: Try like following. Get the file first and pass the file path and type as parameters. function gotFile(file) { uploadFile(file.fullPath,file.type); } function uploadFile(imageURI,type) { var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = imageURI; options.mimeType = type; var params = {}; //params.filePath = "files/"; options.params = params; var ft = new FileTransfer(); ft.upload(imageURI, "http:/www.xx.com/fileUpload.php",function onFileTransferSuccess(e){ alert("File Success"); }, fail, options); } your PHP server side function is like(fileUpload.php): <?php $new_image_name = "file.pdf"; $type = $_FILES["file"]["type"]; $name = $_FILES["file"]["name"]; //$paramValue = $_POST['value1']; move_uploaded_file($_FILES["file"]["tmp_name"], "your storage location".$new_image_name); ?> let me know any difficulties.
{ "pile_set_name": "StackExchange" }
Q: How to enable Imagick in MAMP 4 (Lite)? I am trying to enable Image Magick in MAMP 4 (Lite, not Pro) for PHP 7.1.0. Everything I have found regarding this, is for MAMP 3. It states, that I have to uncomment the line: ;extension=imagick.so The guide said, I have to uncomment it this file: /Applications/MAMP/conf/php7.1.0/php.ini My phpinfo() says the loaded configuration file is: /Applications/MAMP/bin/php/php7.1.0/conf/php.ini I uncommented both and restarted the server, but the extension does not get loaded. Any ideas on how to do that? A: I seem to have found the issue. The extension_dir inside the php.ini does point to the non existing folder: /Applications/MAMP/bin/php/php7.1.0/lib/php/extensions/no-debug-non-zts-20151012/ The only folder that exists is: /Applications/MAMP/bin/php/php7.1.0/lib/php/extensions/no-debug-non-zts-20160303/ I don’t know why this is pointing to an older folder, but after changing it to the new one, Imagick gets loaded.
{ "pile_set_name": "StackExchange" }
Q: How can I populate the textbox of an HTML file input? This one has got me stumped. I am currently rendering a form using ASP MVC, it has a bunch of fields, one of them is an <input type="file"... The file upload works great, but when I return the form to the user, the textbox that contains the file is empty. I would like to show the filepath in the textbox, but it appears the value field does not populate this textbox. Ie. <input type="file" value="abc.txt" /> does not put "abc.txt" into the textbox. How can I populate the textbox of an HTML file input? Is there another property that I should be using other than the value property? Any help would be much appreciated, A: That textbox is readonly and you can't explicitly set the value of it.
{ "pile_set_name": "StackExchange" }
Q: Is there any way that I can manipulate the parent view controller so that the subviews will be underneath the UIPageControl? I'm implementing horizontal scrolling in an app by making use of an UIPageViewController which I set the navigation property to 'Horizontal' and the Transistion Style to 'scroll'. Everything works fine, I can add some subviews that are presented properly. I also want to make use of the built in UIPageControl that UIPageViewController has by making use of these two methods: -(NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController -(NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController This is actually showing what I'm looking for: dots that indicates which subview is shown. But, as you can see in the image, the UIPageControl is set at the bottom of the parent viewcontroller (the UIPageViewController). You can imagine that this is not the way I had in mind to present my UIPageControl. Is there any way that I can manipulate the parent view controller so that the subviews will be underneath the UIPageControl? Or is there any other good practice to achieve this? I know I could implement horizontal scrolling by using a scrollView instead of an UIPageViewController, but this seems much more efficient by me. http://i48.tinypic.com/2hd03ev.png For the clarity: The gray part is my subview and the red part is the underlaying UIPageViewController that I'm using. Thanks in advance for any answer! A: One solution would be to create and manage your own UIPageControl rather than using the built in one. If you created your own several options would work to display it at the depth you wanted, but I would recommend creating an overlay a view on top of the UIPageViewController and adding the UIPageControl to that so the two are completely independent. You could also position the page control wherever you wanted. To track page changes, implement the UIPageViewControllerDelegate of UIPageViewControllerand forward the view controller changes to your UIPageControl using setCurrentPage and setNumberOfPages.
{ "pile_set_name": "StackExchange" }
Q: ViewModel class throwing a null pointer when trying to display results from repository I am trying to display results from the api once someone clicks on the adapter, I am however experiencing a null pointer with the view model class. This is the method that I want to display results with in my MatchDetailActivity private TeamEntity entity; MatchViewModel viewModel; private MatchAdapter adapter; private ActivityMatchDetailBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_match_detail); if(getSupportActionBar()!=null) getSupportActionBar().hide(); binding.displayMatch.setLayoutManager(new LinearLayoutManager(this)); binding.displayMatch.setHasFixedSize(true); adapter = new MatchAdapter(this, entity); } private void getTeamEvents(){ viewModel.getTeamEvents(entity.getTeamId()).observe(this, eventsResults ->{ if(eventsResults != null){ adapter.setList(eventsResults); } }); } But I keep getting a null pointer here: viewModel.getTeamEvents(entity.getTeamId()).observe(this, eventsResults ->{ Below is my stack trace any help will be appreciated. java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sportsapp/com.sportsapp.presentation.ui.MatchDetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.lifecycle.LiveData com.sportsapp.presentation.viewmodels.MatchViewModel.getTeamEvents(java.lang.String)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3555) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3707) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:237) at android.app.ActivityThread.main(ActivityThread.java:8016) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1076) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.lifecycle.LiveData com.sportsapp.presentation.viewmodels.MatchViewModel.getTeamEvents(java.lang.String)' on a null object reference at com.sportsapp.presentation.ui.MatchDetailActivity.getTeamEvents(MatchDetailActivity.java:70) at com.sportsapp.presentation.ui.MatchDetailActivity.onCreate(MatchDetailActivity.java:54) A: You have not assigned value to your view model anywhere add the below line in onCreate() viewModel = new ViewModelProvider(this).get(MyViewModel.class); Hope this helps
{ "pile_set_name": "StackExchange" }
Q: A GUI-Less Browser to scrape with I'm writing a tool to get info from several websites, all require me to log in. My normal approach is to follow the requests and responses in Fiddler or alike, and follow that direct path. However, that feels a bit strict. A minimal change in the website could break my code. So I'm looking for something like a UI-less browser that I can use the following way: Browser.Load("https://sourceforge.net/account/login.php"); Browser.Document.ElementById("form_loginname").Value = "login"; Browser.Document.ElementById("form_pw").Value = "password"; (Browser.Document.ElementById("login") As WebButton).Click(); // the login button is named "login". After this code finishes I'd like to see the page I would get in a regular browser. Does something like I described exist? EDIT - C# support is preferred A: This is a lot like automated user testing for web applications, with the key difference being you don't own the tested application. Selenium is a popular library to automate driving a browser. If you want to run a program using Selenium in a headless fashion, you can use a headless X server such as Xvfb. Regarding not using Xvfb, there is a older question on alternatives. Since Selenium can drive many browsers from a variety of programming languages, I encourage you to explore the Selenium tag on StackOverflow. Of particular interest for you would be something like SimpleBrowser.WebDriver: Selenium bindings for an in-memory light weight browser for .Net. Actually, SimpleBrowser directly might address your needs, without the added complexity of Selenium.
{ "pile_set_name": "StackExchange" }
Q: Including procedure written in different file to package in PL/SQL I've searched a lot to find an answer if there is a way to include procedures, which are written in different files to package. Folders can look like: Packages | Package1 | Procedures | proc1.sql proc2.sql package1.sql ... in package1.sql I wish to have package head and body, but certain procedures should be stored in files proc1.sql etc. Is there any way to do it? It could realy help with large body package or with packages wchich have a lot of procedures. Thank in advance :) A: This isn't possible. A CREATE OR REPLACE PACKAGE or CREATE OR REPLACE PACKAGE BODY statement must be complete-- it has to contain the entire package specification or the entire package body. That means that the entire spec has to be in a single statement in a single file and the entire body has to be in a single statement in a single file. You can separate the header and the specification into different files, of course, but you can't separate either into multiple pieces unless you're using some preprocessing tool to reassemble the chunks before sending them to the database. At the point where a package is large enough that a single file becomes unwieldy to work with and where there are multiple subcomponents that could be logically grouped together into a smaller unit, I would strongly suspect that the right answer is to refactor the package into multiple smaller, better focused packages. It's very much like an object-oriented programmer that finds that one of their classes has, over time, grown into a god object/ Winnebago object that does too much and really covers the ground that two or three objects should be responsible. It's best to bite the bullet and to start refactoring rather than trying to solve the problem by breaking up the source.
{ "pile_set_name": "StackExchange" }
Q: Using collision on bounds of UIView I have an ImageView that moves around the UIView, is it possible to detect collision of the ImageView and the view its self? For example the ImageView hits the side of the view I want it to run an action. -(void)restart {} If this is possible can you detect which side it has collided with? A: You can create a custom UIImageVIew and implement the methods touchBegan and touchMoved (don't forget to add [self setUserInteractionEnabled:YES] in your init method). Then set the rect you want to interact with : customImageView.interactRect = myView.frame; And in your customImageView you can add something like: -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [[event allTouches] anyObject]; lastPosition = [touch locationInView: self.superview]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [[event allTouches] anyObject]; CGPoint position = [touch locationInView:self.superview]; CGRect currentFrame = self.frame; currentFrame.origin = CGPointMake(currentFrame.origin.x + position.x - lastPosition.x, currentFrame.origin.y + position.y - lastPosition.y); if (CGRectIntersectsRect(currentFrame, interactRect) && !CGRectIntersectsRect(self.frame, interactRect)) { NSLog(@"I'm in for the first time"); if(self.frame.origin.x + self.frame.size.width <= interactRect.origin.x && currentFrame.origin.x + currentFrame.size.width > interactRect.origin.x) { NSLog(@"Coming from the left"); } if(self.frame.origin.x >= interactRect.origin.x + interactRect.size.width && currentFrame.origin.x < interactRect.origin.x + interactRect.size.width) { NSLog(@"Coming from the right"); } } self.frame = currentFrame; lastPosition = position; }
{ "pile_set_name": "StackExchange" }
Q: Where is the maximum packet size for TCP identified as 65,535? In doing online searches, the value "65,535" is often referenced as the maximum packet size for TCP. Where is this stated? I ask because RFC 793 states, in relation to the "Maximum Segment Size" field... "If this option is present, then it communicates the maximum receive segment size at the TCP which sends this segment. This field must only be sent in the initial connection request (i.e., in segments with the SYN control bit set). If this option is not used, any segment size is allowed." Since this field is 16-bits wide, I can see where the maximum constrained segment size would be 65,535 bytes. But, absent the constraint, this reads that there is no limit on segment size. The "only workaround" I see is that RFC 1122 identifies a default of 576 if a value is not provided, which becomes a forcing factor that either defaults to 576 or to a supplied value...for which the maximum is 65,535. While I can see that the combination of RFCs 793 and 1122 lead to the 64,535 limit, is there anywhere where this is pulled together in a single reference? A: RFC 791 might be what your looking for. Search 65,535 to find it quickly in the doc. link For Ipv6 is rfc 2675 includes info on Jumbo link
{ "pile_set_name": "StackExchange" }
Q: Python For Loop using List - Trying to group number pairs based on last number used in loop Starting with list: l = [0,1,2,3,6,7,8,9] Trying to produce: nl [[0, 1], [1, 2], [2, 3], [6, 7], [7, 8], [8, 9]] Using a for loop, I was trying to iterate through the list, and use the previous number as my comparison to create a cluster group, with overlapping groups using numbers multiple times. It's not working, and I'm not sure why. It stops adding to the list once it gets to the 6. *Edit: Yes, only grouping number sequence pairs, 1,2,3,etc. and skip 3,6 Test Code: l = [0,1,2,3,6,7,8,9] nl = [] lastN = 0 for i in range(1,len(l)): lastN = l[i - 1] if i - lastN == 1: nl.append([lastN, i]) print('nl',nl) This results in: nl [[0, 1], [1, 2], [2, 3], [3, 4]] My goal was: nl [[0, 1], [1, 2], [2, 3], [6, 7], [7, 8], [8, 9]] A: Try this: https://repl.it/repls/SelfreliantNaturalDaemon l = [0,1,2,3,6,7,8,9] nl = [] for i in range(len(l)-1): if l[i+1] - l[i] == 1: nl.append([l[i], l[i+1]]) print('nl',nl) Returns: nl [[0, 1], [1, 2], [2, 3], [6, 7], [7, 8], [8, 9]]
{ "pile_set_name": "StackExchange" }
Q: slow unc resolution on a win 2008 share I've got some neworking issues with my sbs 2008 server. Basically if i try and access the server's shares via a unc path it takes a long time to resolve, but a mapped drive is quick (until i try to open a file then very often it can be slow). This behaviour even happens on the machine itself if i try and access it's own shares via it's unc path e.g \\servername\share\ Copying to it or from it once open is as fast as ever, and the behaviour is periodic - it sits for a while thinking then everything bursts into life and is quick, then after a while it is slow again. Things to note: 1) I've no virus guard on it (uninstalled it when i started to have trouble). 2) It is fully patched up. 3) I've checked the switch by continuous pings and don't lose any. 4) I've tried disabling shadow copies with no effect. 5) No backups are running. --edit additional information 1) macs don't seem to have a problem with shares 2) exchange has issues - entourage says it has problems copying an email to sent folder on a mac 3)The server has a Broadcom BCM5708C NetXtreme II NIC 4) TCP chimeny is now off, as is checksum offload is off, large send off load is off. TOE is enabled on the card but can't be disabled unless i turn it on in windows first i think. 5) using the ip address doesn't help. A: Are you using Symantec Enterprise Security 11? There is an issue with 2008 and server shares on older updated versions; not sure if this is your issue but something to look into if you are using symantec (I didn't see any statement about A/V software). http://www.symantec.com/connect/forums/mr3-locks-server-2008-file-shares I noticed this problem on my first 2008 file server after about 20/30 users started using it. It got progressively slower then finally just gave up sharing files but everything else (RDP, etc.) worked fine. After ripping hair out I found it to be the A/V problem stated above.
{ "pile_set_name": "StackExchange" }
Q: What definitions exist like __LP64__ and __arm64__ in Cocoa that differentiate platforms at compile time? Where or how are they defined? With the introduction of arm64 as a standard architecture for the iphoneos platform it's necessary in some cases to implement compile-time conditions for code that is specific to the 64/32 architecture. If you look at CoreGraphics/CGBase.h and how some popular open source projects are providing support for arm64 it's clear that you can check for the presence of the 64bit runtime like so: #if defined(__LP64__) && __LP64__ ... #else ... #endif It's also possible to check specifically for arm64 (as opposed to just a 64bit runtime) as mentioned in this fix for erikdoe/ocmock #ifdef __arm64__ ... #else .... #endif Is there a comprehensive list, or documentation for these kinds of definitions? Where or how are they defined? A: Those macros are not specific to Cocoa, they are specific to CLANG, and they can be listed on the command line with: clang -dM -E -x c /dev/null Different CLANG versions ship with varying amounts of feature flags which can get turned on and off at configuration time or depending on which platform and OS the compiler is running on. A fairly comprehensive list can be found in their testing headers with variants for each supported system also scattered around in the testing directory. Documentation for each depends on whether the flag is specific to CLANG, or defined in one of the standard libraries it links against (for example __llvm__ is defined by CLANG, but __WCHAR_WIDTH__ is defined by LibC). There is really no comprehensive list with definitive documentation for this reason. Different platforms are allowed to do things slightly differently so long as they adhere to language specifications. The majority of the interesting public Objective-C macros exist in Foundation near the bottom of Foundation/NSObjCRuntime.h.
{ "pile_set_name": "StackExchange" }
Q: Custom Single Page Portfolio Theme I'm thinking about creating single page portfolio theme, but I'm a little confused on how this would be done based on the different sections on the single page. I'll explain what I would like to do and hopefully someone can help me figure this out. I'm just looking for guidance on what I should do to handle the different sections (maybe custom post types?) Slider Portfolio ( 4 Columns -- -- -- -- ) About ( 2 Columns -- ------) Contact ( 2 Columns ------ -- ) Footer / Social Links If it is too much work for me I'll just pay to have this created, so if interested please leave a contact email and I will get back to you Thanks! A: In the page editor switch to HTML mode and wrap each section of content around divs you want to be a column. <div class="col2w col2a">Col 1</div> <div class="col2w col2b">Col 2</div> <div class="col3w col3a">Col 1</div> <div class="col3w col3b">Col 2</div> <div class="col3w col3c">Col 3</div> Next use CSS to style them to look like columns.
{ "pile_set_name": "StackExchange" }
Q: How do I return a struct value from a runtime-defined class method under ARC? I have a class method returning a CGSize and I'd like to call it via the Objective-C runtime functions because I'm given the class and method names as string values. I'm compiling with ARC flags in XCode 4.2. Method signature: +(CGSize)contentSize:(NSString *)text; The first thing I tried was to invoke it with objc_msgSend like this: Class clazz = NSClassFromString(@"someClassName); SEL method = NSSelectorFromString(@"contentSize:"); id result = objc_msgSend(clazz, method, text); This crashed with "EXC_BAD_ACCESS" and without a stack trace. I used this first because the documentation for objc_msgSend says, When it encounters a method call, the compiler generates a call to one of the functions objc_msgSend, objc_msgSend_stret, objc_msgSendSuper, or objc_msgSendSuper_stret. [...] Methods that have data structures as return values are sent using objc_msgSendSuper_stret and objc_msgSend_stret. Next, I used objc_msgSend_stret like this: Class clazz = NSClassFromString(@"someClassName); SEL method = NSSelectorFromString(@"contentSize:"); CGSize size = CGSizeMake(0, 0); objc_msgSend_stret(&size, clazz, method, text); Using the above signature gives me the following two compiler errors and two warnings: error: Automatic Reference Counting Issue: Implicit conversion of a non-Objective-C pointer type 'CGSize *' (aka 'struct CGSize *') to 'id' is disallowed with ARC warning: Semantic Issue: Incompatible pointer types passing 'CGSize *' (aka 'struct CGSize *') to parameter of type 'id' error: Automatic Reference Counting Issue: Implicit conversion of an Objective-C pointer to 'SEL' is disallowed with ARC warning: Semantic Issue: Incompatible pointer types passing '__unsafe_unretained Class' to parameter of type 'SEL' If I look at the declaration of the method, it is: OBJC_EXPORT void objc_msgSend_stret(id self, SEL op, ...) __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); which is identical to objc_msgSend: OBJC_EXPORT id objc_msgSend(id self, SEL op, ...) __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0); This explains the compiler errors to me but what do I use at the run-time level to invoke a class and its static method at run-time and return a struct value? A: You need to cast objc_msgSend_stret to the correct function pointer type. It's defined as void objc_msgSend_stret(id, SEL, ...), which is an inappropriate type to actually call. You'll want to use something like CGSize size = ((CGSize(*)(id, SEL, NSString*))objc_msgSend_stret)(clazz, @selector(contentSize:), text); Here we're just casting objc_msgSend_stret to a function of type (CGSize (*)(id, SEL, NSString*)), which is the actual type of the IMP that implements +contentSize:. Note, we're also using @selector(contentSize:) because there's no reason to use NSSelectorFromString() for selectors known at compile-time. Also note that casting the function pointer is required even for regular invocations of objc_msgSend(). Even if calling objc_msgSend() directly works in your particular case, it's relying on the assumption that the varargs method invocation ABI is the same as the ABI for calling a non-varargs method, which may not be true on all platforms. A: If you wish to retrieve a struct from your class method, you can use an NSInvocation as follows: Class clazz = NSClassFromString(@"MyClass"); SEL aSelector = NSSelectorFromString(@"testMethod"); CGSize returnStruct; // Or whatever type you're retrieving NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[clazz methodSignatureForSelector:aSelector]]; [invocation setTarget:clazz]; [invocation setSelector:aSelector]; [invocation invoke]; [invocation getReturnValue:&returnStruct]; At the end of this, returnStruct should contain your struct value. I just tested this in an ARC-enabled application and this works fine.
{ "pile_set_name": "StackExchange" }
Q: Want to get back into reverse engineering havn't for a few years whats a good starting point for getting back into it? I used to make maphacks for a game called Warcraft 3. I want to get back into reverse-engineering but with today's technologies (i.e. with the internet being fast enough to download data instead of it being pre-loaded) is it a lost art? Reverse-engineering applications and software does not interest me at all, can anyone recommend other games I might enjoy reversing? I always wanted to take a stab at reverse engineering games using the Quake engine but never got into it, could anyone recommend any tutorials? Also, my method usually involved writing a pure ASM DLL for injection (which just made it easier to create code caves, etc.). Would this work for other games, or are there different methods you have to go about injecting a modification? A: I know referring to another sites is not the best answer you want to get but Reddit has a pretty good and active REGames will give you a good revive.
{ "pile_set_name": "StackExchange" }
Q: Inconsistent results between tag search and tag merge search Searching for activity gives me 200 results, almost all of which are really android activities. But Merge Tags gives me Urp...Really? Are there really 1976 deleted questions with the [activity] tag on them, and if so, how do I verify that, so that I know this is working correctly? Do the deleted questions also get retagged? Do they really have to be retagged if they're already deleted? I don't really have a good solution for this. The retagging could use some better filtering options, but I have no idea what those would look like. Having the ability to filter the merge on another tag (in this case the [android] tag) comes to mind, but I don't know if that would be commonly useful or if it only applies to this particular situation. Retagging 200 questions manually seems like a real pain. A: You have the faq tab selected. The last tab selected on /questions is "sticky" between visits to that page (mine auto-selected unanswered).
{ "pile_set_name": "StackExchange" }
Q: Inline ASM jmp to new memory So I would like to load a set of assembly instructions from a file, and execute those instructions. OR I would like to load already compiled machine code again from a file (non-exe) My Thoughts: So far I've learned enough inline asm to work with c/c++ variables easily. asm volatile ( "mov %1, %%ecx;" // yes unnecessary, I know "add %2, %%ecx;" // I know they're already loaded in a register "mov %%ecx ,%0 ;"// just demonstrating what I've learned :"=r"(address) :"r"(address),"r"(offset) :"%ecx" ); I've begun to learn about op-codes, and I've gotten some x86 manuals. I understand (somewhat) how the hardware works at a basic level. I know that I can load the file into memory with c++ with fstream, and I'm wondering if there's a way to execute memory from that space, or if it's in a non-executable portion of memory or something.. Reason: Currently there are several reasons I'd like to do this. I have a desire to create a basic encyption for my program, for a simple key to run the program. And while I can easily encrypt and decrypt the actual code, I want the program to be unencrypted every run and never stored on the harddrive. I am aware of several problems, however I'm very interested in doing so. Final Questions: Can I execute machine code from memory space in a program from c++ in asm? Is asm necessary? Are there other ways to accomplish this task more efficiently, if so, what are those methods? I'm also reading up on some DLL injection for a mouse sharing program that I'm making (two computers next to each other, both have monitors, however you only have one mouse/keyboard. And I'm wondering where I can find some good resources on the topic? Google has been helpful, however I'm interested in perhaps some IRC channels or something similar. Anyways, thanks for reading! A: This sounds like you kind of want some JIT compiling of some x86 assembly in a separate file? I might have misunderstood, when you say 'memory space', your encapsulating a very broad term. I assume you don't mean that you want to compile it with a specific set of assembly but be able to interchange the assembly instructions at runtime? Have a read over the following Dynamically generating and executing x86 code You'll see #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> int main(int argc, char *argv[]) { uint8_t *buf = mmap(NULL, 1000, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); buf[0] = 0xb8; uint32_t u32 = 42; memcpy(buf + 1, &u32, 4); buf[5] = 0xc3; if (mprotect(buf, 1000, PROT_EXEC | PROT_READ) < 0) { fprintf(stderr, "mprotect failed: %s\n", strerror(errno)); return 1; } int (*ptr)(void) = (int (*)(void)) buf; printf("return is %d\n", ptr()); return 0; } Here you are allocating memory for a buffer. Putting the instructions into the buffer, then creating a function pointer from the allocated memory. Notice the memory is being protected also. Read over the article for a better understanding, it also gives you some Windows equivalents.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to have an OpenGL context inside a GTK3 application? I had a look at GtkGlExt, but it's only for GTK2. Unfortunately, after some hours of searching, it seems that no one take care of having something like an OpenGLDrawingArea… Any information will be welcomed. Even if it's like "it's not possible for now". A: It looks like you have a few options here. Use an in-development port of gtkglext to gtk3 Use SDL to draw into your GTK app by setting the SDL_WINDOWID environment variable Manage GLX yourself to create an OpenGL context for your GTK app. I found a app spectrum3d which implements both of the first two alternatives. The third option will be quite complex and is probably not worth pursuing.
{ "pile_set_name": "StackExchange" }
Q: what's the difference between a terminal services server and an application server I was watching this youtube video about cloud computing by eli the computer guy and his description for the application server is a lot like how the terminal services server work. Is there a fine line between both? A: A terminal server is a hardware device or server that provides terminals (PCs, printers, and other devices) with a common connection point to a local or wide area network. An application server is a software framework that provides both facilities to create web applications and a server environment to run them
{ "pile_set_name": "StackExchange" }
Q: echo command in system api call without \n? #include <stdio.h> #include<stdlib.h> void echoIt() { char* cmd_1 = "echo -ne {\"key\":\"value\"} > outFile"; char* cmd_2 = "echo -ne ,{\"key1\":\"value1\"} >> outFile"; system(cmd_1); system(cmd_2); } int main(int argc, char **argv) { echoIt(); } output came in 2 lines ,the option -ne is to remove \n that also came in outFile root@userx:/home/userx/work/lab/test# cat outFile -ne {key:value} -ne ,{key1:value1} expected result is on the same line : {key:value} ,{key1:value1} how to get it? A: I'm going to take your word for it that you have a concrete reason why you must use a subshell for this, rather than opening the file directly. The -n and -e options to echo are not part of the portable shell specification. Often, they work in the interactive shell you are accustomed to using, but don't work in the noninteractive shell used to interpret system command lines. On modern (post-2001) operating systems, it is better to use printf than echo: system("printf '%s' '{\"key\":\"value\"}' > outFile"); system("printf '%s' ',{\"key\":\"value\"}' >> outFile"); will do what you want. If there's a case where you do want a newline after the string, printf understands C-style backslash escapes in its first argument only: system("printf '%s\\n' ',{\"key\":\"value\"}' >> outFile"); Pay close attention to the quoting in all of these examples.
{ "pile_set_name": "StackExchange" }
Q: Error in util.java in facebook sdk I am integrating facebook with android.when i give referance to the facebook sdk then my project work fine,but when i close the ecllipse and reopen the ecllipse then error in util.java in facebook sdk project.why ? thanks........ A: Sometimes eclipse just get messed at startup. Nothing is like cleaning and building after opening eclipse and before getting started to work.
{ "pile_set_name": "StackExchange" }
Q: Trouble interfacing NewHaven oled display with stm32f4 The last two days I've been trying to interface a NewHaven Dislpay with my stm32f4 discovery board with no result. The datasheet gives poor written examples as to how to initialize this display and I'm having a really hard time figuring how this display works. I'm currently using SPI and while I made the appropriate connections (according to the datasheet) the display refuses to work. The stm32f4 is clocked at 168MHz The SPI initialization code is the following: hspi1.Instance = SPI1; hspi1.Init.Mode = SPI_MODE_MASTER; hspi1.Init.Direction = SPI_DIRECTION_1LINE; hspi1.Init.DataSize = SPI_DATASIZE_8BIT; hspi1.Init.CLKPolarity = SPI_POLARITY_LOW; hspi1.Init.CLKPhase = SPI_PHASE_1EDGE; hspi1.Init.NSS = SPI_NSS_SOFT; hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi1.Init.TIMode = SPI_TIMODE_DISABLE; hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi1.Init.CRCPolynomial = 10; The code I wrote is the following: void oled_Data(unsigned char Data) { HAL_GPIO_WritePin(GPIOE, GPIO_PIN_2, GPIO_PIN_SET); //Set the D/C Pin HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET); //Lower the CS HAL_SPI_Transmit(&hspi1, &Data, 1, 50); HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET); //Set the CS } void oled_Command(unsigned char address) { HAL_GPIO_WritePin(GPIOE, GPIO_PIN_2, GPIO_PIN_RESET); //Reset the D/C pin HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET); //Lower the CS pin HAL_SPI_Transmit(&hspi1, &address, 1, 50); HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET); //Set the CS pin HAL_GPIO_WritePin(GPIOE, GPIO_PIN_2, GPIO_PIN_SET); //Set the D/C pin } void Init() { unsigned int i=0,j,k; const unsigned char init_commands[]= { 0x06, // Display off 0x00, //Osc control //Export1 internal clock and OSC operates with external resistor 0x02, 0x01, // Disable OSC Power Down 0x04, 0x03, // Set normal driving current 0x04, 0x00, //Clock div ratio 1: freq setting 120Hz 0x03, 0x90, //Iref controlled by external resistor 0x80, 0x01, //Precharge time R 0x08, 0x04, //Precharge time G 0x09, 0x05, //Precharge time B 0x0A, 0x05, //Precharge current R 0x0B, 0x9D, //Precharge current G 0x0C, 0x8C, //Precharge current B 0x0D, 0x57, //Driving current R 0x10, 0x56, //Driving current G 0x11, 0x4D, //Driving current B 0x12, 0x46, //Display mode set //RGB,column=0-159, column data display=Normal display 0x13, 0x00, //External interface mode=MPU 0x14, 0x11, //Memory write mode //6 bits triple transfer, 262K support, Horizontal address counter is increased, //vertical address counter is increased. The data is continuously written //horizontally 0x16, 0x66, //Memory address setting range 0x17~0x19 to width x height 0x17, //Column start 0x00, 0x18, //Column end 0x19, //row start 0x00, 0x1A, //row end //Memory start address set to 0x20~0x21 0x20, //X 0x00, 0x21, //Y 0x00, //Duty 0x28, 0x7F, //Display start line 0x29, 0x00, //DDRAM read address start point 0x2E~0x2F 0x2E, //X 0x00, 0x2F, //Y 0x00, //Display screen saver size 0x33~0x36 0x33, //Screen saver columns start 0x00, 0x34, //Screen saver columns end 0x35, //screen saver row start 0x00, 0x36, //Screen saver row end //Display ON 0x06, 0x01, //Disable Power Save 0x05, 0x00, //End of commands 0xFF, 0xFF }; //Initialize interface and reset display driver chip HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET); HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_RESET); //Lower the RES pin HAL_Delay(500); HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_SET); //Set the RES pin HAL_Delay(500); //Send initialization commands for (i=0; ;i+=2) { j=(int)init_commands[i]; k=(int)init_commands[i+1]; if ((j==0xFF) && (k==0xFF)) break; oled_Command(j); oled_Data(k); } } Note that I'm fairly new to the embedded world and the code I wrote is not the optimal. I just ported the code examples (with slight changes) given in order to understand how to initialize this display. As soon as gain a better understanding I will write my own driver. To sum up: What I want to achieve: My goal at the moment is simply to initialize the display and print something e.g "hello world" What I know I'm fairly familiar with the Serial Peripheral Interface (SPI) and DMA as well as UART and STM timers. What I ask: I'm pretty sure that I've done something fundamentally wrong so my questions are: Is there something wrong with my code? My guess is that my delays are completely off but I can't be sure. In the code provided in the datasheet there is an instruction that bugs me graphic_delay(500000) This is some kind of delay but what kind of delay? And in what units? ms? μs? If someone has any experience at interfacing this particular display and is willing to provide me with a basic outline about how to initialize the display I would be grateful. EDIT I forgot to post the datasheet for the Display Driver and Controller EDIT no2 I removed the HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_RESET); as kindly suggested by Flanker. I also implemted properly the delays. The problem persists. I will now connect once more time the logic analyzer to ensure that my initialization commands are being sent correctly. A: So the problem seemed to be (apart from my mistake of reseting the device every time a command was sent) my SPI settings. After looking the datasheet for quite some time I realized that I had to change Clock Polarity fromhspi1.Init.CLKPolarity = SPI_POLARITY_LOW; to hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH; Furthermore I changed hspi1.Init.CLKPhase = SPI_PHASE_1EDGE; to hspi1.Init.CLKPhase = SPI_PHASE_2EDGE; Those two changes seem to solve the problem and I am currently able to fill my screen with e.g red pixels. For future reference I will post the code (the working one) so anyone who wants to interface this display (or one with the same driver) can port this code. SPI init: hspi1.Instance = SPI1; hspi1.Init.Mode = SPI_MODE_MASTER; hspi1.Init.Direction = SPI_DIRECTION_1LINE; hspi1.Init.DataSize = SPI_DATASIZE_8BIT; hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH; hspi1.Init.CLKPhase = SPI_PHASE_2EDGE; hspi1.Init.NSS = SPI_NSS_SOFT; hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi1.Init.TIMode = SPI_TIMODE_DISABLE; hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi1.Init.CRCPolynomial = 10; Display Init: (I simplified this section of code on purpose) void OLED_Init(void) { HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_RESET); HAL_Delay(500); HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_SET); HAL_Delay(500); oled_Command(0x04); oled_Data(0x03); //Set Normal Driving Current HAL_Delay(2); oled_Command(0x04); oled_Data(0x00); //Enable Power Save Mode, Set normal driving current HAL_Delay(2); oled_Command(0x02); oled_Data(0x01); // Set EXPORT1 Pin at Internal Clock oled_Command(0x03); oled_Data(0x90); // Set Frame Rate to 120Hz oled_Command(0x80); oled_Data(0x01); // Set Reference Voltage Controlled by External Register oled_Command(0x08); //Set Pre-charge Time of Red oled_Data(0x04); oled_Command(0x09); //Set Pre-charge Time of Green oled_Data(0x05); oled_Command(0x0A); //Set Pre-Charge Time of Blue oled_Data(0x05); oled_Command(0x0b); //Set Pre-Charge Current of Red oled_Data(0x9d); oled_Command(0x0C); //Set Pre-Charge Current of Green oled_Data(0x8C); oled_Command(0x0D); //Set Pre-Charge Current of Blue oled_Data(0x57); oled_Command(0x10); //Set Driving Current of Red oled_Data(0x56); oled_Command(0x11); //Set Driving Current of Green oled_Data(0x4D); oled_Command(0x12); //Set Driving Current of Blue oled_Data(0x46); oled_Command(0x13); oled_Data(0xa0); //Set Color Sequence oled_Command(0x14); oled_Data(0x01); //Set MCU Interface oled_Command(0x16); oled_Data(0x76); oled_Command(0x20); oled_Data(0x00); // Shift Mapping RAM Counter oled_Command(0x21); oled_Data(0x00); // Shift Mapping RAM Counter oled_Command(0x28); oled_Data(0x7F); // 1/128 Duty (0x0F~0x7F) oled_Command(0x29); oled_Data(0x00); // Set Mapping RAM Display Start Line (0x00~0x7F) oled_Command(0x06); oled_Data(0x01); // Display On (0x00/0x01) oled_Command(0x05); // Disable Power Save Mode oled_Data(0x00); // Set All Internal Register Value as Normal Mode oled_Command(0x15); oled_Data(0x00); // Set RGB Interface Polarity as Active Low HAL_Delay(10); } After the display is initialized you can fill the screen with a certain colour like this: void fillScreen(void) { //Set Column Address oled_Command(0x17); oled_Data(0x00); //x_start oled_Command(0x18); oled_Data(0x9F); //x_end //Set Row Address oled_Command(0x19); oled_Data(0x00); //y_start oled_Command(0x1A); oled_Data(0x7F); //y_end oled_Command(0x22); //write to RAM command for (int i=0;i<20480;i++) //for each 24-bit pixel...160*128=20480 { oled_Data(blue); oled_Data(green); oled_Data(red); } The oled_Command and oled_Data functions remain the same! P.S I think someone else suggested that I should change the clock polarity (a user without enough rep to leave a comment) but it seems that his answer was deleted for some reason.
{ "pile_set_name": "StackExchange" }
Q: Create a library without a class? I'd like to know if it's possible to create a library for Arduino that does not contain a class, just functions. I know how to create a library with a class, but I'd like to create a library of general purpose functions that don't need to be instantiated to be used. Just used like the standard functions included in the Arduino IDE: sizeof(), etc.. Is this possible? If so, can anyone point me in the direction of a template? I've been searching, but haven't found anything. Thanks! A: Yes, it's possible. Just don't make a class. Just make functions instead. Like a class-based one, have a .cpp and a .h file. In the .cpp file (or .c file if you don't want any of the C++ functionality or 90% of the Arduino API available to you) place your functions. In the .h file place prototypes for them. I am in the habit of adding the extern keyword, but you don't actually need to for functions. For example: foo.cpp: void doSomething() { // whatever } foo.h: extern void doSomething(); Then you can include your .h file and call your functions: #include <foo.h> // ... doSomething();
{ "pile_set_name": "StackExchange" }
Q: How to Decode HTML Entities using Jquery/Javascript AutoComplete I have an auto-complete script that uses php/jquery to retrieve information from database. <script type="text/javascript"> $(function() { var availableTags = <?php include('autocomplete.php'); ?>; $("#artist_name").autocomplete({ source: availableTags, autoFocus:true }); }); </script> The problem I'm having is displaying html characters "é", "&" and "ó" that are stored in the database as &eacute; &amp; and &eacute; I cannot get the javascript code to show the html characters for the user to select. If I change the html entity to the special character in the database, then the auto-complete script stops working altogether. I found this possible solution on Stackoverflow, but I do not know if how to implement it within the auto-complete javascript that I have or if it will solve my problem at all. <script> function htmlDecode(input){ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; } htmlDecode("&lt;img src='myimage.jpg'&gt;"); // returns "<img src='myimage.jpg'>" </script> I am not proficient in javascript coding. How can I decode the html entities within the auto-complete script. Please help. Thanks. Autocomplete.php code: <?php $connection = mysqli_connect("localhost","root","root","database_name") or die("Error " . mysqli_error($connection)); //fetch artist names from the artist table $sql = "select artist_name from artist_names"; $result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection)); $dname_list = array(); while($row = mysqli_fetch_array($result)) { $dname_list[] = $row['artist_name']; } echo json_encode($dname_list); ?> A: Please choose one of these (but not both) PHP Solution : if you want to decode html entities you could first use php's built-in html_​entity_​decode() function in autocomplete.php: $dname_list = array(); while($row = mysqli_fetch_array($result)) { $dname_list[] = html_​entity_​decode($row['artist_name']); } echo json_encode($dname_list); JS Solution : take a look at jQueryUI's doc, you can use this to build your own <li> element, so that would be something like : $("#artist_name").autocomplete({ source: availableTags, autoFocus: true, _renderItem: function(ul, item) { return $("<li>") .attr("data-value", item.value) //no need to unescape here //because htmlentities will get interpreted .append($("<a>").html(item.label)) .appendTo(ul); } });
{ "pile_set_name": "StackExchange" }
Q: Forcing conflation for $L(\mathbb{R})$ Here's a very silly mistake I made recently: I claimed that if $\mathbb{P}\in L(\mathbb{R})$ is a forcing which adds a real, then $$(*)\quad L(\mathbb{R})^{V^\mathbb{P}}=L(\mathbb{R})^\mathbb{P}.$$ While it is true (EDIT: no it isn't, see the answer below) that $L(\mathbb{R})^\mathbb{P}=L(\mathbb{R})^{(L(\mathbb{R})^\mathbb{P})}$, what I wrote above is nonsense: $V$ may have names for reals which are not in $\mathbb{R}$. Indeed, from large cardinals we can prove that $(*)$ fails - if it held, then examining $Col(\omega,\kappa)$ for $\kappa$ regular in $V$, we'd have that $L(\mathbb{R})$ contains a proper class of measurables; and this is known to not be the case, assuming large cardinals (specifically, from large cardinals there are no measurable cardinals in $L(\mathbb{R})$ above $\Theta$). My question is around principles of the form $(*)$. Specifically, for a definable class of forcings $\mathcal{C}$ which add a real, let (FC)$_\mathcal{C}$ ("forcing conflation") be the statement $(*)$ restricted to forcings in $\mathcal{C}\cap L(\mathbb{R})$. I'm interested in when (FC)$_\mathcal{C}$ is compatible with large cardinals - specifically, a proper class of Woodins - and when it adds large cardinal strength to ZFC+proper class of Woodins. To make this concrete, I'll ask: Is (FC)$_{proper}$ consistent with ZFC + "There is a proper class of Woodins," relative perhaps to even stronger large cardinal hypotheses? If so, does ZFC + "There is a proper class of Woodins" + (FC)$_{proper}$ have consistency strength beyond a proper class of Woodins? A: $(FC)_{\text{proper}}$ is false. If there are infinitely many Woodin cardinals with a measurable above, then after adding a single Cohen real, we do not have $L(\mathbb R)[c] = L(\mathbb R)^{V[c]}$. The reason is that $L(\mathbb R)[c]$ does not satisfy $\text{AD}$: in $L(\mathbb R)[c]$, the set of ground model reals is uncountable, but does not contain a perfect subset. (See Hamkins's answer to the question Is there a perfect set of ground model reals in the Cohen extension? which uses at worst countable choice.) On the other hand, $L(\mathbb R)^{V[c]}$ satisfies $\text{AD}$ by our large cardinal hypothesis. Note in this situation that $L(\mathbb R)^{V[c]}=L(\mathbb R)^{L(\mathbb R)[c]}\subsetneq L(\mathbb R)[c]$, since nice names for reals are all coded by reals. Therefore it is not true in general that $L(\mathbb R)^{L(\mathbb R)[r]} = L(\mathbb R)[r]$ (or that $L(\mathbb R)[r]\subseteq L(\mathbb R)^{V[r]}$) when $r$ is a generic real. The problem this time is that $\mathbb R$ (as computed in the ground model) need not be in $L(\mathbb R)^{L(\mathbb R)[r]}$. The large cardinal assumption can actually be reduced to the assumption that $\text{AD}$ holds in $L(\mathbb R)$, because it can be proved under this hypothesis that $ L(\mathbb R)^{V[c]} = L(\mathbb R)^{L(\mathbb R)[c]}$ satisfies $\text{AD}$. You might be interested in Kechris and Woodin's paper Generic Codes, in which they prove this fact and analyze forcing over $L(\mathbb R)$ with Levy collapses, showing that for $\kappa<\delta^2_1$ a reliable ordinal, if $G\subseteq \text{Col}(\omega, \kappa)$ is $L(\mathbb R)$-generic then in $L(\mathbb R)[G]$, there is a definable elementary embedding from $L(\mathbb R)$ into $L(\mathbb R)^{L(\mathbb R)[G]}$
{ "pile_set_name": "StackExchange" }
Q: Why there exists an element $ y\in G\setminus‎ L $ such that $ K/L_{G} = (\langle y \rangle L_{G})/L_{G} $? Let $ G $ is finite supersoluble group. Then $ G $ has a chief series. Let $ L $ be a subgroup of $ G $ and $ K/L_{G} $ a chief factor of $ G $ where $ L_{G} $ is the core of $ L $ in $ G $. Since $ G $ is supersoluble, $ K/L_{G} $ is a cyclic group with prime order. Clearly, $ K $ is not contained in $ L $. Why there exists an element $ y\in G\setminus‎ L $ such that $ K/L_{G} = (\langle y \rangle L_{G})/L_{G} $? A: Since $G$ is supersoluble, its chief factor is $1$ dimensional. So $|G|=|L_G||K/L_G|$. Since $|K/L_G|=p$, $K/L_G$ is generated by $yL_G$, $y\in G, y\notin L$, for otherwise $K/L_G=L_G$.
{ "pile_set_name": "StackExchange" }
Q: Firebase (Swift) - generate unique ID with numbers only? Right now, I'm generating unique IDs with childByAutoId(), but was wondering if there was a way to do this only generating numbers, no letters or other characters? The reason is I need to be able to automatically send this key through imessage (part of how I send invites) and when it contains letters you're not able to automatically select and copy the key without copying the entire text message. With numbers only the key will be underlined and selectable. Is there a way to either generate an ID with numbers only, or to selectively underline part of an iMessage with MFMessage in Swift? Thanks! A: I've need a similar option. When i create a new user; it will have a numberID which will be unique. I've tried .push() method which is for android, creates a uniqueID but with characters(letters) included. What i've done was something like this; When i add a new user, i increment a value from different branch which is User2Key in this situation. And gave the value as key(parent) of newly added user. When i delete or update a user, User2Key will be the same. If i add a new user then it will be incremented so every user will have uniqueID. You can use a similar approach. Hope this helps! Cheers!
{ "pile_set_name": "StackExchange" }
Q: Where I should put glue? I have application written with Java and Guice. For this application I have several views. Some of them use Guice, other - doesn't. Now I want to separate my code into independent modules. I can devide application logic, viewers interfaces and viewers implementations. In which module should I put Guice configuration per each view variant? I think there is two possible answers - into viewers module (in this case all viewers will depend from Guice) or contribute such ModuleConfiguration separately from module. What is the right way? If separably, what is the best way for such contribution? A: Just split the configuration into several Guice Modules near the code that they are wiring. Then use composition to construct an injector. Injector injector = Guice.createInjector(new ModuleA(), new ModuleB());
{ "pile_set_name": "StackExchange" }
Q: Wie spricht man von der deutschen Sprache? Es klingt fast wie eine Metafrage, aber wie spricht man eigentlich von der deutschen Sprache (oder von einer anderen)? Sagt man eher die Schönheit des Deutschen oder die Schönheit vom Deutschen ? (Ja, ich weiss, man kann die Schönheit der deutschen Sprache sagen aber das ist ein Ausweichen!) Ähnlich frage ich mich: heisst es ins Deutsche übersetzen oder auf Deutsch übersetzen ? Und soll ich im Deutschen habe ich Schwierigkeiten sagen oder auf Deutsch habe ich Schwierigkeiten ? A: Richtig ist die erste Variante Wichtig ist, dass man es nur mit bestimmtem Artikel verwenden darf, oder ganz ohne Artikel. (Das Deutsche ist eine schöne Sprache; Deutsch ist die Sprache der Dichter und Poeten). Nun ist es so, dass sich hinter dem Wort "vom" eigentlich "von dem" versteckt, und "dem" wiederum ist das gebeugte "der", bestimmter Artikel im 3. Fall. Kontrollieren kann man die richtige Anwendung, indem man den gesuchten Teil ("vom Deutschen") durch das Fragewort "Wem" ersetzt und den Satz zu einer Frage umformt: Wem seine Schönheit? Hier nun wird klar, dass es sich um keinen sauberen deutschen Satz handelt. Die Frage muss heißen: Wessen Schönheit? Wessen verlangt den 2. Fall (Genitiv), daraus ergibt sich, dass Die Schönheit des Deutschen die richtige Form ist. Die Ersetzung des Genitivs durch den Dativ ist ein bereits lang laufender Prozess, der vor allem in vielen Dialekten schon weit fortgeschritten ist. Dennoch gibt es wie in diesem Fall sehr viele Wendungen, die nicht mit dem Dativ bestreitbar sind. [1] Der Text ist auf Deutsch geschrieben. [1] Der Text ist in gutem/schlechtem Deutsch geschrieben. Aus den Beispielen schließe ich, dass man ins Deutsche übersetzt (es wird wie ein Adjektiv gebraucht) und auf Deutsch schreibt (Substantiv). Die letzte Frage, und wohl die schönste von allen ist Mit Deutsch habe ich (meine) Schwierigkeiten wohl am elegantesten beantwortet. A: richtig: Schönheit des Deutschen / der deutschen Sprache / des Deutschen Dativ anstelle des Genitivs benutzen nur Leute mit einer niedrigeren Bildung Ins Deutsche übersetzen, aber auf Deutsch sagen.
{ "pile_set_name": "StackExchange" }
Q: Mobile Push API I have a question on Message Keys for Mobile Push Batch API. I tried to search the documentation but could not find a relevant answer. Please note that we are using REST API for the calls. a. Do we need to provide Message keys for the Alert Title & Icon that appears on the device? b. Can these default from the setup of the message itself vs being passed in each API call or some other method c. What sort of keys should be configured at the application level in the application definition d. Is there an example setup for the application keys in place which we could look at? A: The AndroidLearning App has sample code. The data portion of the payload you receive on the device will resemble: { "alert": "Analytics Verification Alert", "_m": "MTExOjFxNDow3", "sound": "default", "et_big_pic": "http://short.url/2k3Qjzx", "sent_timestamp": "Fri, 31 Mar 2017 14:01:59 GMT" } The depicted payload is incomplete. The documentation should guide you to the other properties you can provide for icon, etc.
{ "pile_set_name": "StackExchange" }
Q: I18n - locale file - use ruby - use translation() In a I18n locale file (eg el.yml): can I use translation method in order to use an already defined translation? can I use ruby code inside? For example, in the locale yml file, in several places I want to use the word "Invalid". So one approach is to translate the word "Invalid" each time Another approach is to translate it once, at the top, and then in each translation inside the locale yml which contains this word I could use something like t(:invalid).. eg: el: # global translations - in order to be used later in the file locked: 'kleidomeno' invalid: 'mi egiro' password: 'kodikos' devise: failure: invalid: "#{Invalid} %{authentication_keys} or #{password}." locked: "Your account is #{locked}." last_attempt: "You have one more attempt before your account is #{locked}." not_found_in_database: "#{invalid} %{authentication_keys} ή #{password}." A: can I use translation method in order to use an already defined translation? Yes, that's what I18n translation comes for, e.g. t 'something' can I use ruby code inside? No, it's a .yml file, which does not accept Ruby or any other programming languages. Another approach is to translate it once To translate once, you can write a new Rake task to generate the target yml for you. Or maybe, wrap the official translation function with a new method, which can recognize your custom string syntax: # custom translate def ct(msg) msg.gsub(/#\{\s*([^\}]+)\s*\}/) {|_| t $1} end Call it like: ct 'Your account is #{locked}.' I think you'd better remove these failure strings out of your yml file if so.
{ "pile_set_name": "StackExchange" }
Q: Commenting out glfwWindowHint() makes code functional (OpenGL with GLFW), why? sorry I had a bit of trouble with the proper name for this question, however I've run into a roadblock and I'd like to at least be informed as to the source. I've been trying to learn to learn openGL and I'm following this tutorial: open.gl Lines in question: glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); While following through the tutorial I got an access violation exception in my code. Only after I commented out the following lines was I able to get the program working as the tutorial says it should have worked the first time. The tutorial states the following about the commented out lines: "You'll immediately notice the first three lines of code that are only relevant for this library. It is specified that we require the OpenGL context to support OpenGL 3.2 at the least. The GLFW_OPENGL_PROFILE option specifies that we want a context that only supports the new core functionality." My thought was that perhaps my drivers do not support OpenGL 3.2 or higher since when I commented out the lines in question my program ran fine. However, I downloaded a software called GPU caps viewer. When the software scanned my hardware it said that both my NVIDIA GeForce GT 540M and HD Graphics 3000 support OpenGL 4.3. So I'm very confused as to the source of my problem, what I am doing wrong, or is this a hardware issue? Here are snapshots of GPU CAPS and NVIDIA PORTAL: 2 pictures on imgur Doesn't Work: #include "stdafx.h" //necessary headers in here int _tmain(int argc, _TCHAR* argv[]) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr); // Windowed glfwMakeContextCurrent(window); while (!glfwWindowShouldClose(window)) { glfwSwapBuffers(window); glfwPollEvents(); if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); } glfwTerminate(); return 0; } Works: #include "stdafx.h" //necessary headers in here int _tmain(int argc, _TCHAR* argv[]) { glfwInit(); /** glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); **/ GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr); // Windowed glfwMakeContextCurrent(window); while (!glfwWindowShouldClose(window)) { glfwSwapBuffers(window); glfwPollEvents(); if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); } glfwTerminate(); return 0; } Header File #pragma once #define GLEW_STATIC #include <glew.h> #include "targetver.h" #include <stdio.h> #include <tchar.h> #include <iostream> #include <thread> #define GLFW_INCLUDE_GLU #include <glfw3.h> One last thing that came to mind, when I go to my NVIDIA control panel it shows Visual Studio 2013 only as using Intel HD 3000 graphics card. It doesn't give me an option to use my GeForce graphics with it, could this be the issue? EditOne: I tried running my Visual Studio 2013 through windows explorer by right clicking on it and choosing "Run with graphics processor..." but to no avail. I appreciate you looking through my question to help me solve it, and if you had this question yourself I hope it helped you solve your issue. A: Actual cause of the problem (as confirmed by OP) were out-of-date and/or not fully featured drivers. This is yet again a reminder that in case of OpenGL problems the first course of action should always be to upgrade to the latest version of the graphics drivers, obtained directly from the GPU maker's download site. Two reasons for this: OEM drivers usually lag a significant amount of releases behind the GPU vendors. much more important: The drivers installed through Windows update are stripped of propper OpenGL support by Microsoft for reasons only known by Microsoft. To make a long story short: Your program is probably going to get an OpenGL context for the Intel HD graphics which lacks the requested OpenGL capabilities. Thus when setting these GLFW windows hints the window creation fails and since your program does not check for this error it will try to use that window, which of course will cause trouble. What should you do? First and foremost add error checks! Here's an example how you can deal with the window creation failing: GLFWwindow* window = glfwCreateWindow( 800, 600, "OpenGL", nullptr, nullptr); if( !window ) { print_some_error_message(); exit(-1); } glfwMakeContextCurrent(window); Next you want to force the system to use the NVidia card. Don't do that "launch through explorer run on NVidia BS"; say you ship your program to someone else? Do you want to put that burden onto them? Or how about you, when you want to debug it? Do it properly: Tell the system that you want to run on the NVidia hardware in a Optimus configuration. Simply link the following into your program: extern "C" { _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; } The best place to put this would be right beside your program's main function, i.e. in your case #include "stdafx.h" //necessary headers in here extern "C" { _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; } int _tmain(int argc, _TCHAR* argv[]) { …
{ "pile_set_name": "StackExchange" }
Q: ng-options with an array of key-pair objects I have the following data that I got from a third-party: countries: [ {"US":"United States"}, {"CA":"Canada"}, {"AF":"Afghanistan"}, {"AL":"Albania"}, {"DZ":"Algeria"}, {"DS":"American Samoa"}, ..... ]; The way the data is organized is not how I would have done it, but now I need fit all of this in a select with ng-options so that both the value and the option displayed is the full name of the country I have tried ng-options="code as name for (code, name) in countries" but I get an Object as my select value. A: Working plunkr here: http://plnkr.co/edit/nbWHz8g4Gn0vGuSHM5o0?p=preview Though as Nicolas pointed out, it's probably better to transform the data? HTML: <!DOCTYPE html> <html ng-app="app"> <head> <script data-require="[email protected]" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-controller="AppCtrl"> <select id="countries" name="countries" ng-model="selectedCountry" ng-options="getKey(country) as country[getKey(country)] for country in countries"></select> Selected country: {{selectedCountry}} </body> </html> JS: // Code goes here angular.module('app',[]).controller("AppCtrl", ["$scope", function($scope) { $scope.countries = [ {"US":"United States"}, {"CA":"Canada"}, {"AF":"Afghanistan"}, {"AL":"Albania"}, {"DZ":"Algeria"}, {"DS":"American Samoa"} ]; $scope.getKey = function(country) { return Object.keys(country)[0]; } }]);
{ "pile_set_name": "StackExchange" }
Q: Amazon Elastic Map Reduce: Job flow fails because output file is not yet generated I have an Amazon EMR job flow that performs three tasks, the output from the first being the input to the subsequent two. The second task's output is used by the third task DistributedCache. I've created the job flow entirely on the EMR web site (console) but the cluster fails immediately because it cannot find the distributed cache file - because it has not yet been created by step #1. Is my only option to create these steps from the CLI via a boostrap action, and specify the --wait-for-steps option? It seems strange that I cannot execute a multi-step job flow where the input of one task relies on the output of another. A: In the end I got around this by creating an Amazon EMR cluster that bootstrapped but had no steps. Then I SSH'd into the head and ran the hadoop jobs on the console. I now have the flexibility to add them to a script with individual configuration options per job.
{ "pile_set_name": "StackExchange" }
Q: Regex for overlapping matches For a linguistics project I am trying to match all occurrences of one or two consonants between vowels in some text. I am trying to write a very simple matcher in PHP (preg_match_all), but once the match is consumed, it cannot match again. The following is very simple and should do the trick, but only matches the first occurrence: [aeiou](qu|[bcdfghjklmnprstvwxyz]{1,2})[aeiou] In: officiosior: offi and osi are returned, but not ici because the trailing i is the first part of the match in the second match. As far as I can tell, it's impossible to do, but is there a decent way to work around the issue? A: You can use a Positive Lookahead assertion to achieve this. (?=([aeiou](?:qu|[^aeiou]{1,2})[aeiou])) A lookahead does not consume any characters on the string. After looking, the regular expression engine is back at the same position on the string from where it started looking. From there, it can start matching again... Explanation: (?= # look ahead to see if there is: ( # group and capture to \1: [aeiou] # any character of: 'a', 'e', 'i', 'o', 'u' (?: # group, but do not capture: qu # 'qu' | # OR [^aeiou]{1,2} # any character except: 'a', 'e', 'i', 'o', 'u' # (between 1 and 2 times) ) # end of grouping [aeiou] # any character of: 'a', 'e', 'i', 'o', 'u' ) # end of \1 ) # end of look-ahead Working Demo
{ "pile_set_name": "StackExchange" }
Q: cannot load such file -- app.rb (LoadError) Just deployed a ruby app using capistrano. I'm pretty sure I did everything as usual. Passenger though outputs the following: cannot load such file -- app.rb (LoadError) config.ru:1:in `require' config.ru:1:in `block in <main>' /home/deploy/apps/blog/shared/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb:55:in `instance_eval' /home/deploy/apps/blog/shared/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb:55:in `initialize' config.ru:1:in `new' config.ru:1:in `<main>' /home/deploy/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:108:in `eval' /home/deploy/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:108:in `preload_app' /home/deploy/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:153:in `<module:App>' /home/deploy/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:29:in `<module:PhusionPassenger>' /home/deploy/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:28:in `<main>' **Application root** /home/deploy/apps/blog/current The app.rb actually is in this directory. A: Use the below in your config.ru instead require "./app" run Sinatra::Application It is path issues
{ "pile_set_name": "StackExchange" }
Q: Does "all have sinned" (Rom. 3:23, 5:12) include every single human being? My mother and I go round and round on various Catholic vs. Protestant beliefs and in particular the Catholic belief in the pseudo-divinity of Mary. One item is whether Mary was sinless. I pointed to Paul's statement: Romans 3:23For all have sinned… or Romans 5:12…by one man sin entered into this world and by sin death: and so death passed upon all men, in whom all have sinned. That would seem to include Mary among the "all". Yet her retort is the "all" would then have to mean babies in the womb, infants, etc., who weren't capable of sin. My thinking is Paul might have meant "all" as referring to those actually capable of sinning or old enough to know better. According to the Catholic Church, what did Paul really mean by that declaration? Does "all" really mean "all"? A: According to Catholicism: Does “all have sinned” (Rom. 3:23, 5:12) include every single human being? According to Catholicism the short answer is: No. The two exceptions according to the Church were Jesus called the Christ and his mother Mary. The belief that Mary lived without sin from the moment of her conception springs from Church tradition. It evolved over a period of time and was not formally defined as a teaching of the Church until 1854. It is not found explicitly in Scripture, but seems for Catholics to flow naturally from the testimony of Scripture that Mary was “full of grace” (Luke 1:28) and “blessed” (Luke 1:42). In Catholic understanding, the belief in Mary’s “immaculate conception” does not say so much about Mary as it is about Christ’s saving power. We believe that God created the human person to be in God’s own image. Grace is more original than sin. Our natural state was to be “full of grace.” Sin is our universal experience, but it’s not what God intended for us in the past nor wants for us in the future. We are saved from sin through Christ. Mary’s being conceived without sin takes place in the context of the entire saving act of Christ. In being “full of grace” she is a model of what we human beings were intended to be and who we are redeemed to be through God’s saving power. She is the first sign of God’s victory over sin in Christ. - Where in the Bible does it say that Mary, mother of Jesus, is sinless? And if it is not in the Bible, why does the Catholic Church act like she is? The Catechism of the Catholic Church explains it this way: 490 To become the mother of the Saviour, Mary “was enriched by God with gifts appropriate to such a role.” The angel Gabriel at the moment of the annunciation salutes her as “full of grace”. In fact, in order for Mary to be able to give the free assent of her faith to the announcement of her vocation, it was necessary that she be wholly borne by God's grace. 491 Through the centuries the Church has become ever more aware that Mary, “full of grace” through God, was redeemed from the moment of her conception. That is what the dogma of the Immaculate Conception confesses, as Pope Pius IX proclaimed in 1854: The most Blessed Virgin Mary was, from the first moment of her conception, by a singular grace and privilege of almighty God and by virtue of the merits of Jesus Christ, Saviour of the human race, preserved immune from all stain of original sin. 8 Things You Need to Know About the Immaculate Conception
{ "pile_set_name": "StackExchange" }
Q: polytime transformation from a graph to a set of binary strings $d_H$ denotes the Hamming distance between two binary strings of the same size. The problem is stated as follows. Given any undirected graph $(V, A)$, does there always exist a one-to-one correspondence $f : V \mapsto \Omega$, $f$ computable in polynomial time, where $\Omega$ is a set of binary strings of the same size and such that $\exists \alpha > 0$, $\forall v_i, v_j \in V$, $$d_H(f(v_i), f(v_j)) = \left\lbrace\begin{array}{ll} \alpha & \mbox{ if } (v_i, v_j) \in A,\\ \mbox{some value strictly greater than $\alpha$,}& \mbox{otherwise.} \end{array}\right.$$ For instance, if $(V, A)$ is a clique of size $3$, i.e., $V = \{v_1, v_2, v_3\}$ and $A = V \times V$, then such a function $f$ can be defined as follows: $f(v_1) = 100$, $f(v_2) = 010$, $f(v_3) = 001$. We have $d_H(v_1, v_2) = d_H(v_2, v_3) = d_H(v_1, v_3) = 2$. As another example, consider a line $(V, A)$ of size $3$, i.e., $V = \{v_1, v_2, v_3\}$ and $A = \{(v_1, v_2), (v_2, v_1), (v_2, v_3), (v_3, v_2)\}$, then such a function $f$ can be defined as follows: $f(v_1) = 00$, $f(v_2) = 10$, $f(v_3) = 11$. We have $d_H(v_1, v_2) = d_H(v_2, v_3) = 1$ and $d_H(v_1, v_3) = 2$. A: Yes. If the graph is regular there is a trivial scheme. Fix some ordering of the edges, and define $f(v)$ to be $0$ at the corresponding position of a particular edge if $v$ is not incident to that edge, and $1$ is $v$ is incident to the edge. If the graph is $k$-regular, then $d_H(f(v),f(u))$ is $2k-2$ if $u$ and $v$ are adjacent, and $2k$ if they are not. If the graph is not regular, then we may pad the graph with additional degree $1$ vertices such that all of the original vertices have the same degree. Then the above scheme will work.
{ "pile_set_name": "StackExchange" }
Q: Circular random walk Suppose we have a circumference divided in N arcs of the same length. A particle can move on the circumference jumping from an arc to the adjacent, with probability $P_{k \to k-1}=P_{k\to k+1}=\frac{1}{2}$. I have some difficulty to find the probability that the particle fulfilled at least one complete turn on the circumference after $M$ jumps with $M\gt N$. Thanks A: The time needed to visit at least once each vertex of a graph is called the cover time of the graph. Let $C_n$ denote the cover time of the discrete circle of size $n$. Then $\mathrm E(C_n)=\frac12n(n-1)$. The expression of the distribution of $C_n$ for any fixed $n$ is cumbersome but a result due to Jean-Pierre Imhof in 1985 describes the asymptotics as follows: when $n\to\infty$, $n^{-2}C_n\to C$ in distribution, where the distribution of $C$ has density $$ \sqrt{\frac{8}{\pi t^3}}\cdot\sum_{k=1}^{+\infty}(-1)^{k-1}k^2\mathrm e^{-k^2/(2t)}\cdot[t\gt0]. $$ A different, equivalent, expression of the limit distribution is in Amine Shihi's PhD thesis. A related (and somewhat counterintuitive) result might be worth mentioning: for every $n\geqslant2$, the last vertex visited, that is, the position of the particle at time $C_n$ is uniformly distributed on the $n-1$ vertices which are not the starting one.
{ "pile_set_name": "StackExchange" }
Q: How to create an Orbit Chart in R? (Plotly/ggplot2) I have spent time researching with no direction on how to create an orbit chart I would ideally like to be able to create interactive versions (such as Plotly) but a ggplot2 would suffice as well. Any suggestions are much appreciated! A: For a weekly vis contest some time ago, I created some charts like this. I think the commonly accepted term now is "connected scatterplot". Here is the skeleton plotly code I used. plot_ly( df, x = x_var, y = y_var, group = group_var, mode = "markers") %>% add_trace( x = x_var, y = y_var, xaxis = list(title = ""), yaxis = list(title = ""), group = group_var, line = list(shape = "spline"), showlegend = FALSE, hoverinfo = "none") You can look at the github repo for my submission which includes the code for both ggplot and plotly to produce connected scatterplots.
{ "pile_set_name": "StackExchange" }
Q: Curves and Surfaces Suppose $$S=\{(x,y,z) \in \mathbb{R}^3 : x^2+y^2+(z-1)^2=1\}$$ and $$T=\left\{(x,y,z) \in \mathbb{R}^3 : \frac{(z+1)^2}{4}=x^2+y^2, z \geq-1 \right\}.$$ (1) Find the $z$-coordinates of the points of intersection of $S$ and $T$ and sketch the projection into the $xy$-plane of the curves of intersection. I tried to solve simultaneously and found that $z=1/5, 1$. Not sure if this is correct. Also am unsure about the sketch. Thanks! A: Here are 2 pictures of the intersection:
{ "pile_set_name": "StackExchange" }
Q: How to add mutiple extra tabs on product page Magento 2 I want to display multiple tabs(inconstant number) on product page, with the code below by using layout(catalog_product_view) i am only able to add fixed amount of tabs. <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="product.info.details"> <block class="AbdusSalam\AddTab\Block\ProductTabs" name="extratab" template="AbdusSalam_AddTab::product_tabs.phtml" group="detailed_info"> <arguments> <argument name="title" xsi:type="string">Extra Tab</argument> </arguments> </block> </referenceBlock> </body> A: I suggest you visit this link. https://knowthemage.com/create-dynamic-custom-tabs-on-product-view-page/ This worked for me.
{ "pile_set_name": "StackExchange" }
Q: create menu item with special characters in nwjs / node-webkit Is it possible in node-webkit to create menu items that contain special characters like "ü", "ä", "ö"? When you create a new menu item with a special character in the label, it will display it like this (same goes for tooltips): var menu = new nw.Menu(); menu.append(new nw.MenuItem({ label: "Spalte einfügen" })); screenshot A: You'll need to encode special characters in order for them to appear correctly. The following should work for you: var menu = new nw.Menu(); menu.append(new nw.MenuItem({ label: "Spalte einf\u00FCgen" })); You can use the table at https://unicode-table.com/en/ for others, it will just be \u{Unicode Number}
{ "pile_set_name": "StackExchange" }
Q: Download file from url angular 2 i have url : http://localhost:9999/file/bongda.PNG i using nodejs serve for public file : application.use(express.static(path.join(__dirname, 'uploads'))); and application.get('/file/:name', function (req, res, next) { var options = { root: __dirname + '/uploads/', dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true } }; console.log('Express server listening downloads '); var fileName = req.params.name; res.type('png'); res.sendFile(fileName, options, function (err) { if (err) { next(err); } else { console.log('Sent:', fileName); } }); }); i want to download file from url i using <a href="window.location.href='http://localhost:9999/file/bongda.PNG'">123123</a> or <a href="http://localhost:9999/file/bongda.PNG">123123</a> but it not success . please help me ? A: <a href="http://localhost:9999/video.mp4" download> Dowload Video </a> i using html5 href .it's OK
{ "pile_set_name": "StackExchange" }
Q: RS232 beginner tutorials I am really beginner in Linux and in electronics but I want to learn programming hardware using raspberry pi board, since I have one (model B). I have installed raspbian os, now I want to understand how to connect RS232 and control my raspberry using my Linux PC (I learn how to do it using ssh). For me this is very interesting area but I don't know where to start and how to start. My problem is I totally don't know how to work with RS232, how to connect it and what should happen if I correctly connect RS232 to my Linux PC. Can you give some good tutorials for totally beginners (would be great with some videos) If I made mistake in question please don't close it, let me know reason I will correct it. Thanks A: If you know nothing about RS232 I'd suggest you start with a different project. However, there are people who have produced the sort of RS232 interface you mention. Robert Davage Adding a RS232 serial port to the Raspberry Pi is actually quite simple. [All] you need is a RS-232 level shifter and a four wire leads to connect to the GPIO header. So .. what [is] a level shifter you ask. A level shifter is a circuit that can take the low voltage (±3.3VDC) TTL signals for serial transmit (TX) and receive (RX) from the UART on the Pi and shift them to ±5VDC the voltage signals required for RS232 standard communication. Code and Life So in this short tutorial, I’ll show you how to use a MAX3232CPE transceiver to safely convert the normal UART voltage levels to 3.3V accepted by Raspberry Pi, and connect to the Pi MadLab The Pi has 2 rows of general purpose input / output (GPIO) pins at 3.3V (top left in the picture), but that means that we can’t use an RS232 serial connection directly as the voltage levels are too high. Rather than build or buy a converter, we used a simpler method. Most modern Linux distributions, including Debian Squeeze, provide support for USB serial ports, so getting hold of a USB serial cable was the first job. This connects to one of the USB ports on the Pi, and has a 9 pin D serial connector on the other end. You can purchase ready-made parts Ebay example Pi232 board FTDI Sparkfun Adafruit Raspy Juice
{ "pile_set_name": "StackExchange" }
Q: Acquire WriteLock before writing shared resource I am a beginner in multi-threading and came across this example on ReadWriteLock. ScoreBoard public class ScoreBoard { private boolean scoreUpdated = false; private int score = 0; String health = "Not Available"; final ReentrantReadWriteLock rrwl = new ReentrantReadWriteLock(); public String getMatchHealth() { rrwl.readLock().lock(); if (scoreUpdated) { rrwl.readLock().unlock(); rrwl.writeLock().lock(); try { if (scoreUpdated) { score = fetchScore(); scoreUpdated = false; } rrwl.readLock().lock(); } finally { rrwl.writeLock().unlock(); } } try { if (score % 2 == 0 ){ health = "Bad Score"; } else { health = "Good Score"; } } finally { rrwl.readLock().unlock(); } return health; } public void updateScore() { try { rrwl.writeLock().lock(); //perform more task here scoreUpdated = true; }finally { rrwl.writeLock().unlock(); } } private int fetchScore() { Calendar calender = Calendar.getInstance(); return calender.get(Calendar.MILLISECOND); } } ScoreUpdateThread public class ScoreUpdateThread implements Runnable { private ScoreBoard scoreBoard; public ScoreUpdateThread(ScoreBoard scoreTable) { this.scoreBoard = scoreTable; } @Override public void run() { for(int i= 0; i < 5; i++) { System.out.println("Score Updated."); scoreBoard.updateScore(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } } Main public class Main { public static void main(String[] args) { final int threadCount = 2; final ExecutorService exService = Executors.newFixedThreadPool(threadCount); final ScoreBoard scoreBoard = new ScoreBoard(); exService.execute(new ScoreUpdateThread(scoreBoard)); exService.execute(new ScoreHealthThread(scoreBoard)); exService.shutdown(); } } Wont in the ScoreBoard while updating the health variable , we need to acquire the WriteLock since we are updating a shared variable ? A: Wont in the ScoreBoard while updating the health variable , we need to acquire the WriteLock since we are updating a shared variable ? You are correct that the class's getMatchHealth() method performs a modification of the shared health variable without holding the write lock. There being no other mechanism in the class for synchronizinging those writes, this produces a data race when two threads invoke getMatchHealth() on the same ScoreBoard without engaging some form of external synchronization. This appears to be a flaw in the method, and the method appears to have some other, more subtle synchronization issues, too. Nevertheless, the program presented appears not ever to invoke getMatchHealth() at all, and the other ScoreBoard methods appear to be free of synchronization flaws, so the particular program presented is not affected by the flaws. Still, unless those flaws are intentional -- for didactic purposes, for instance -- I would recommend finding a better source of tutorial material than the one that provided the example program.
{ "pile_set_name": "StackExchange" }
Q: Scheduling and coloring problem A group of students plan to take part in exams in the courses ${C_1}, \ldots ,{C_6}$ as follows: $$\begin{array}{l} {\rm{Student A}} \hspace{7 mm} {C_1}\,\,\,\,\,{C_3}\\ {\rm{Student B}} \hspace{7 mm} {C_1}\,\,\,\,\,{C_4}\,\,\,\,\,{C_5}\\ {\rm{Student C}} \hspace{7 mm} {C_2}\,\,\,\,\,{C_6}\\ {\rm{Student D}} \hspace{6.8 mm} {C_2}\,\,\,\,\,{C_3}\,\,\,\,\,{C_6}\\ {\rm{Student E}} \hspace{7.2 mm} {C_3}\,\,\,\,\,{C_4}\\ {\rm{Student F}} \hspace{7.2 mm} {C_3}\,\,\,\,\,{C_5}\\ {\rm{Student G}} \hspace{6.8 mm} {C_5}\,\,\,\,\,{C_6} \end{array}$$ Draw a graph with nodes ${C_j},\,j = 1,2, \ldots ,6$ so that there is an edge between $C_j$ and $C_k$ if and only if there is at least one student that plans to take part in the exams in courses $C_j$ and $C_k$. Determine the chromatic number of this graph, that is the smallest number of colors needed to color the nodes so that if there is an edge between two nodes, then they get different colors. What does this number tell us in this case? My attempt: One of the possible graphs:           I have already colored it, and i know how to explain the way i did it. From this graph we see that $\chi{(G)} = 3$ and to prove that the chromatic number cannot be smaller than $3$ we just analyse the topmost cycle, which requires minimum $3$ colors. My question is regarding the graph. Did i get it right? Does it satisfy all conditions? My doubts are regarding the students that take $3$ exams. I hope i don't need to draw the edge, say for example for student $B$, $\left( {{C_4},{C_5}} \right)$, because from the edges $\left( {{C_1},{C_4}} \right),\,\left( {{C_1},{C_5}} \right)$ we already see that student $B$ will take exams ${C_1},\,{C_4}$ and ${C_5}$, but i'm not sure if i'm right? A: Since there is a student (student B) taking both exams $C_4$ and $C_5$, the definition you're given says that there should indeed be an edge $(C_4,C_5)$. Note that the coloring you provided puts these exams at the same time, which is bad news for Student B.
{ "pile_set_name": "StackExchange" }
Q: Add a dynamic supervisor to ejabberd Is it possible to start a supervisor module in ejabberd which I can add a gen_fsm module to, per connection? Specifically, I want to create a supervisor which I start when the server starts (or when connections come in). And I have a couple of gen_servers which I want to start, but the part I'm looking for some guidance on is how to dynamically add a gen_fsm module to my supervisor when I see this user's presence become available? A: You might want to have a look to the Simple one for on supervisor, which: is a simplified one_for_one supervisor, where all child processes are dynamically added instances of the same process ... When started, the supervisor will not start any child processes. Instead, all child processes are added dynamically by calling: supervisor:start_child(Sup, List) ... Basically, you use this kind of supervisors when: All the children are of the same type You want to add children dynamically Which appears to be your case.
{ "pile_set_name": "StackExchange" }
Q: How to execute RemoveAliasMapping in ElasticSearch using JEST I am trying to remove an alias mapping for an index in ES using jest. Here is what I have tried : // create Jest Client. JestClient client = factory.getObject(); // create RemoveAliasMapping Object. RemoveAliasMapping removeAliasMapping = new RemoveAliasMapping.Builder("oldIndex", "alias").build(); After creating the removeAliasMapping object, I couldn't find a way to execute it. If I use the api : client.execute(removeAliasMapping), it says : The method execute(Action<T>) in the type JestClient is not applicable for the arguments (RemoveAliasMapping) Also, I couldn't find any other api exposed to execute AliasMapping. Can anyone help me out with this here? If possible, please put an example too. A: Try this: ModifyAliases modifyAliases = new ModifyAliases.Builder(new RemoveAliasMapping.Builder("oldIndex", "alias").build()).build(); JestResult result = client.execute(modifyAliases);
{ "pile_set_name": "StackExchange" }
Q: How can I add a triangular shape with the thickness of my loop cuts? I'm trying to make a simple shape but can't seem to do it right. It's basically a right-angle shape with edges. Hard to explain, here are the pics: http://imgur.com/vB0sT16 This is where I'm stuck: http://imgur.com/GrUy4G4 All I need to do now is add in the triangles on the sides with the thickness shown by my loop cuts. Any ideas?? A: Create additional geometry and use Bridge Edge Loops to achieve the final result. Bridging won't work from the beginning as there aren't 2 edge loops; however you can split existing faces and bridge the result. For that select edge between faces which form the base for the desired triangles. Press V to rip it and Esc to cancel moving. You have 2 edge loops now. Switch to Face Select mode, choose both faces and execute Ctrl+E > Bridge Edge Loops. Internal faces will be deleted for you. Remove doubles (which were made with that ripped edge) via W menu. Also in 3D View header find Select > Non-Manifold operator (switch to Vertice or Edge Select mode to use it). Edge in the corner will be selected, delete it. Note that tris may be undesired topology (e.g. if subdividing this surface or adding more loopcuts) so use it if you know this part of model will be mostly flat and not needing further subdividing.
{ "pile_set_name": "StackExchange" }
Q: How to recover basic networking utilities on Debian? I am administrating a small server for LAN, providing basic services such as web-proxy, ldap, kerberos, afs, etc. Yesterday there was a power cut so server halted. When I restarted it no network interfaces were available and configured. I tried restarting networking daemon but it just exited with 0 status. So I tried to run one of the interfaces manually, but ifup and ifdown commands simply are not there. No only in PATH, but they disappeared from /sbin. So my question is: how can I recover these network utilities? A: Are there any messages in /var/log/messages, /var/log/syslog, /var/log/boot.log, etc. indicating an I/O error or an error mounting a partition or an error activating LVM or MD or RAID? Was there a "Filesystem unclean" or "fsck" message when the server powered up? Are all partitions currently mounted? Are there any files in /sbin? To fix the exact problem you mention, assuming all partitions were correctly mounted, I would boot from a Debian boot CD in recovery/rescue mode, start a shell, find where your /sbin (or probably the / (root)) partition is mounted, then run chroot <that path> /bin/bash, then you can run sudo apt-get install ifupdown to re-install /sbin/ifup, then reboot. But you should try to find out if anything else is broken. Try installing debsums, i.e. sudo apt-get install debsums.
{ "pile_set_name": "StackExchange" }
Q: Как сделать смену кнопок play/close? Подскажите пожалуйста как сделать, чтобы при click на кнопке play данная кнопка скрывалась и отображалась кнопка close, а когда закрываю видео, кнопка close скрывалась и появлялась кнопка play ? <section class="section_1"> <div id="wideo"> <div id="play"> <i class="far fa-play-circle"></i> (кнопка плей) </div> <div id="close"> <i class="fas fa-times-circle"></i> (кнопка клозе) </div> <iframe style="display: none;" id="video" width="100%" height="100vh" src="https://www.youtube.com/embed/-yQ8kxikSJQ" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> <a href="http://127.0.0.1:49217/index.html"></a> </div> </section> #play { color: #fff; position: absolute; font-size: 60px; left: 48%; top: 50%; cursor: pointer; transition: all 0.5s ease; } #close { color: #fff; position: absolute; top: 5px; left: 84%; font-size: 25px; } .section_1 { background-image: url(image/video_image.jpg); background-position: center; background-size: cover; background-repeat: no-repeat; height: 100vh; position: relative; } $('#close').find('#play').on('click', function() { $('#video').slideToggle(function(){ if($('#close')){ $('#close').hide(); } }); }); A: Вариант 1: отображение/скрытие play/close происходит независимо от выполнения slideToggle(). $('#play, #close').on('click', function(e) { $('#video').slideToggle(); $('#play, #close').toggle(); }); $('#play, #close').on('click', function(e) { $('#video').slideToggle(); $('#play, #close').toggle(); }); body { background: #444; } #play { color: #fff; position: absolute; font-size: 60px; left: 48%; top: 50%; cursor: pointer; transition: all 0.5s ease; } #close { display: none; color: #fff; position: absolute; top: 5px; left: 84%; font-size: 25px; } .section_1 { background-image: url(image/video_image.jpg); background-position: center; background-size: cover; background-repeat: no-repeat; height: 100vh; position: relative; } <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="section_1"> <div id="wideo"> <div id="play"> <i class="far fa fa-play-circle"></i> (кнопка плей) </div> <div id="close"> <i class="fas fa fa-times-circle"></i> (кнопка клозе) </div> <iframe style="display: none;" id="video" width="100%" height="100vh" src="https://www.youtube.com/embed/-yQ8kxikSJQ?r=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> <a href="http://127.0.0.1:49217/index.html"></a> </div> </section> Вариант 2: отображение/скрытие play/close происходит после выполнения slideToggle(). Чтобы ответ не был копией другого, добавлен старт/стоп видео в iframe при нажатии на кнопки. (!) В сниппете не работает, работает на jsfiddle. (!) Для работы в ссылку на видео необходимо добавить параметр, например r=0: https://www.youtube.com/embed/-yQ8kxikSJQ?r=0 $('#play, #close').on('click', function(e) { let obj = this; //e.target.id может работать нестабильно let video_src = $("#video").attr('src').replace(/\&autoplay\=\d+/, ''); $('#video').slideToggle(function(){ $('#play, #close').toggle(); $("#video").attr('src', video_src + ((obj.id == 'play') ? '&autoplay=1' : '')); }); }); $('#play, #close').on('click', function(e) { let obj = this; //e.target.id может работать нестабильно let video_src = $("#video").attr('src').replace(/\&autoplay\=\d+/, ''); $('#video').slideToggle(function(){ $('#play, #close').toggle(); $("#video").attr('src', video_src + ((obj.id == 'play') ? '&autoplay=1' : '')); }); }); body { background: #444; } #play { color: #fff; position: absolute; font-size: 60px; left: 48%; top: 50%; cursor: pointer; transition: all 0.5s ease; } #close { display: none; color: #fff; position: absolute; top: 5px; left: 84%; font-size: 25px; } .section_1 { background-image: url(image/video_image.jpg); background-position: center; background-size: cover; background-repeat: no-repeat; height: 100vh; position: relative; } <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="section_1"> <div id="wideo"> <div id="play"> <i class="far fa fa-play-circle"></i> (кнопка плей) </div> <div id="close"> <i class="fas fa fa-times-circle"></i> (кнопка клозе) </div> <iframe style="display: none;" id="video" width="100%" height="100vh" src="https://www.youtube.com/embed/-yQ8kxikSJQ?r=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> <a href="http://127.0.0.1:49217/index.html"></a> </div> </section>
{ "pile_set_name": "StackExchange" }
Q: Alternate for environment dependent global variables There are a couple of places in my Ruby on Rails project where I need to access a value dependent on which environment Ruby on Rails was started in. Specifically, it is the name of the MongoDB database that I need to make a connection to. Currently I just have something like: MONGO_DB = "database_name" in config/environments/< environment >.rb. Then in the code I can call things like Mongo::Connection.new.db(MONGO_DB). Is there a better way to do this without global variables? Just using global variables rubs me the wrong way, though they never change once the application has been started. A: Hopefully, there is a much better way. Find inspiration in YAML Configuration File. Having all datas in YAML files is a really clean way to handle multiple cases.
{ "pile_set_name": "StackExchange" }
Q: HTML Form Directing to PHP File or Include PHP File Which has higher security? Including the PHP file on a web page for form use, or directing the user to a PHP file when they press a form button? Example 1: include 'filename'; Example 2: form action="sendingtheuserhere.php" method="post" Thank you A: Generally, it wouldn't matter whether you include the PHP code that handles form data into the file that contains the form or to have a separate PHP file for the same purpose. What would matter is how you handle the form data. Below is an example: form.php - has the HTML form <html> <head></head> <body> <form action="send.php" method="post"> <input name="subject" /> <textarea name="message"></textarea> <button>Send</button> </form> </body> </html> send.php - handles form data <?php $user_subject = $_POST['subject']; $user_message = $_POST['message']; $send_to = '[email protected]'; mail($send_to, $user_subject, $subject_message); ?> Now with the above code, there are a couple things you should know. The send.php file has unsafe code. Visiting the send.php will send an email to the $send_to address whether someone files the form or not. Now if you were to have to separate files, every time you visit the send.php file, an email would be sent. That is whether you fill in the form or you simply visit send.php link. Second, if you were to combine the two files, you would have an email sent to you every time someone opens your form. That is because the mail(); function is triggered every time. To combat this, you have to make sure the mail function triggers only when the form is submitted. You can do so by changing the code in send.php to the following: new send.php <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // checks whether a POST request actually exists or not. $user_subject = strip_tags(trim($_POST['subject'])); $user_message = strip_tags(trim($_POST['message'])); $send_to = '[email protected]'; mail($send_to, $user_subject, $subject_message); } else { echo 'form not filled'; } ?> Now, in the above code, the first thing we did is to check whether a POST request actually existed. If not, you'll see "Form not filled". After that, to make the request a little more secure to any sort of code injections we used the PHP trim(); and strip_tags(); function. You can combine the two PHP files like so: form.php <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // checks whether a POST request actually exists or not. $user_subject = strip_tags(trim($_POST['subject'])); $user_message = strip_tags(trim($_POST['message'])); $send_to = '[email protected]'; mail($send_to, $user_subject, $subject_message); } ?> <html> <head></head> <body> <form action="form.php" method="post"> <input name="subject" /> <textarea name="message"></textarea> <button>Send</button> </form> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Extract fundamental data with interactive broker from specific tags in python 3 all. I want to extract the specific fundamental data from Interactive Broker API (Python 3), however, it shows the xml version. I can't get for example Market capitalization (by ' print(callback.fundamental_Data_data.find("MKTCAP"))') import pandas as pd import time from IBWrapper import IBWrapper, contract from ib.ext.EClientSocket import EClientSocket from ib.ext.ScannerSubscription import ScannerSubscription import re stocks=[ '5' ] for x in stocks: callback = IBWrapper() tws = EClientSocket(callback) host = "127.0.0.1" port = 7496 clientId = 25 tws.eConnect(host, port, clientId) create = contract() callback.initiate_variables() contract_Details = create.create_contract(x, 'STK', 'SEHK', 'HKD') tickerId = 8001 tws.reqFundamentalData(tickerId, contract_Details, "ReportSnapshot" ) time.sleep(5) print(callback.fundamental_Data_data) print(callback.fundamental_Data_data.find("AATCA")) print(callback.fundamental_Data_data.find("ACFSHR")) print(callback.fundamental_Data_data.find("ADIV5YAVG")) print(callback.fundamental_Data_data.find("MKTCAP")) print(callback.fundamental_Data_data.find("QTANBVPS")) print(callback.fundamental_Data_data.find("REVCHNGYR")) print(callback.fundamental_Data_data.find("REVTRENDGR")) tws.eDisconnect() time.sleep(5) tws.eDisconnect() Output: It is all in xml format, most fundamental data can be shown. <?xml version="1.0" encoding="UTF-8"?> <RepportSnapshot Major="1" Minor="0" Revision="1"> <CoIDs> <CoID Type="RepNo">AC317</CoID> <CoID Type="CompanyName">HSBC Holdings plc (Hong Kong)</CoID> </CoIDs> <Issues> <Issue ID="1" Type="C" Desc="Common Stock" Order="1"> <IssueID Type="Name">Ordinary Shares</IssueID> <IssueID Type="Ticker">5</IssueID> <IssueID Type="CUSIP">G4634U169</IssueID> <IssueID Type="ISIN">GB0005405286</IssueID> <IssueID Type="RIC">0005.HK</IssueID> <IssueID Type="SEDOL">6158163</IssueID> <IssueID Type="DisplayRIC">0005.HK</IssueID> <IssueID Type="InstrumentPI">312270</IssueID> <IssueID Type="QuotePI">1049324</IssueID> <Exchange Code="HKG" Country="HKG">Hong Kong Stock Exchange</Exchange> <MostRecentSplit Date="2009-03- 12">1.14753</MostRecentSplit> </Issue> </Issues> <CoGeneralInfo> <CoStatus Code="1">Active</CoStatus> <CoType Code="EQU">Equity Issue</CoType> <LastModified>2018-07-20</LastModified> <LatestAvailableAnnual>2017-12-31</LatestAvailableAnnual> <LatestAvailableInterim>2018-03-31</LatestAvailableInterim> <Employees LastUpdated="2018-03-31">228899</Employees> <SharesOut Date="2018-07-24" TotalFloat="19882952713.0">19952507521.0</SharesOut> <ReportingCurrency Code="USD">U.S. Dollars</ReportingCurrency> <MostRecentExchange Date="2018-07-24">1.0</MostRecentExchange> </CoGeneralInfo> <TextInfo> <Text Type="Business Summary" lastModified="2017-03- 06T22:03:17">HSBC Holdings plc (HSBC) is the banking and financial services company. The Company manages its products and services through four businesses: Retail Banking and Wealth Management (RBWM), Commercial Banking (CMB), Global Banking and Markets (GB&amp;M), and Global Private Banking (GPB). It operates across various geographical regions, which include Europe, Asia, Middle East and North Africa, North America and Latin America. RBWM business offers Retail Banking, Wealth Management, Asset Management and Insurance. CMB services include working capital, term loans, payment services and international trade facilitation, among other services, as well as expertise in mergers and acquisitions, and access to financial markets. GB&amp;M supports government, corporate and institutional clients across the world. GPB's products and services include Investment Management, Private Wealth Solutions, and a range of Private Banking services.</Text> <Text Type="Financial Summary" lastModified="2018-07- 20T09:20:11">BRIEF: For the three months ended 31 March 2018, HSBC Holdings plc (Hong Kong) interest income increased 10% to $7.46B. Net interest income after loan loss provision increased 11% to $7.29B. Net income applicable to common stockholders decreased 1% to $3.09B. Net interest income after loan loss provision reflects Asia segment increase of 22% to $3.86B, Net Interest Margin, Total -% increase of 2% to 1.67%, Net Interest Spread.</Text> </TextInfo> <contactInfo lastUpdated="2018-07-20T09:20:26"> <streetAddress line="1">8 Canada Square</streetAddress> <streetAddress line="2"></streetAddress> <streetAddress line="3"></streetAddress> <city>LONDON</city> <state-region></state-region> <postalCode>E14 5HQ</postalCode> <country code="GBR">United Kingdom</country> <contactName></contactName> <contactTitle></contactTitle> <phone> <phone type="mainphone"> <countryPhoneCode>44</countryPhoneCode> <city-areacode>20</city-areacode> <number>79918888</number> </phone> <phone type="mainfax"> <countryPhoneCode>44</countryPhoneCode> <city-areacode>20</city-areacode> <number>79924880</number> </phone> </phone> </contactInfo> <webLinks lastUpdated="2016-11-07T05:00:04"><webSite mainCategory="Home Page">http://www.hsbc.com/</webSite><eMail mainCategory="Company Contact/E- mail"></eMail></webLinks> <peerInfo lastUpdated="2018-07-20T09:20:26"> <IndustryInfo> <Industry type="TRBC" order="1" reported="0" code="5510101010" mnem="">Banks - NEC</Industry> <Industry type="NAICS" order="1" reported="0" code="52211" mnem="">Commercial Banking</Industry> <Industry type="NAICS" order="2" reported="0" code="52393" mnem="">Investment Advice</Industry> <Industry type="NAICS" order="3" reported="0" code="52392" mnem="">Portfolio Management</Industry> <Industry type="SIC" order="0" reported="1" code="6035" mnem="">Federal Savings Institutions</Industry> <Industry type="SIC" order="1" reported="0" code="6029" mnem="">Commercial Banks, Nec</Industry> <Industry type="SIC" order="2" reported="0" code="6282" mnem="">Investment Advice</Industry> </IndustryInfo> </peerInfo> <officers> <officer rank="1" since="01/01/2013"> <firstName>John</firstName> <mI>Michael</mI> <lastName>Flint</lastName> <age>48 </age> <title startYear="2018" startMonth="02" startDay="21" iD1="CEO" abbr1="CEO" iD2="EDR" abbr2="Exec. Dir.">Chief Executive, Executive Director</title> </officer> <officer rank="2" since="09/24/2010"> <firstName>Iain</firstName> <mI>J.</mI> <lastName>Mackay</lastName> <age>56 </age> <title startYear="2010" startMonth="12" startDay="03" iD1="FID" abbr1="Fin. Dir." iD2="EDR" abbr2="Exec. Dir.">Group Finance Director, Executive Director</title> </officer> <officer rank="3" since="08/01/2015"> <firstName>Andy</firstName> <mI></mI> <lastName>Maguire</lastName> <age>51 </age> <title startYear="2015" startMonth="08" startDay="01" iD1="COO" abbr1="COO" iD2="MDR" abbr2="Mgng.Dir.">Group Chief Operating Officer, Group Managing Director</title> </officer> <officer rank="4" since="11/26/2010"> <firstName>Marc</firstName> <mI>M.</mI> <lastName>Moses</lastName> <age>60 </age> <title startYear="2014" startMonth="01" startDay="01" iD1="CRO" abbr1="CRO" iD2="EDR" abbr2="Exec. Dir.">Group Chief Risk Officer, Executive Director</title> </officer> <officer rank="5" since="NA"> <firstName>Elaine</firstName> <mI></mI> <lastName>Arden</lastName> <age>49 </age> <title startYear="NA" startMonth="" startDay="" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Managing Director, Group Head of Human Resources</title> </officer> <officer rank="6" since="01/01/2011"> <firstName>Samir</firstName> <mI></mI> <lastName>Assaf</lastName> <age>57 </age> <title startYear="2011" startMonth="01" startDay="01" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Group Managing Director, Chief Executive - Global Banking &amp; Markets</title> </officer> <officer rank="7" since="NA"> <firstName>Colin</firstName> <mI></mI> <lastName>Bell</lastName> <age>50 </age> <title startYear="NA" startMonth="" startDay="" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Managing Director, Group Head of Financial Crime Risk</title> </officer> <officer rank="8" since="10/01/2013"> <firstName>Peter</firstName> <mI>W.</mI> <lastName>Boyles</lastName> <age>62 </age> <title startYear="2013" startMonth="10" startDay="01" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Group Managing Director; Chief Executive of Global Private Banking</title> </officer> <officer rank="9" since="08/01/2015"> <firstName>Patrick</firstName> <mI>J.</mI> <lastName>Burke</lastName> <age>56 </age> <title startYear="2015" startMonth="08" startDay="01" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Group Managing Director; President and Chief Executive of HSBC USA</title> </officer> <officer rank="10" since="08/01/2015"> <firstName>Pierre</firstName> <mI></mI> <lastName>Goad</lastName> <age>56 </age> <title startYear="2016" startMonth="" startDay="" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Group Managing Director, Group Head of Employee Insight and Communications</title> </officer> </officers> <Ratios PriceCurrency="HKD" ReportingCurrency="USD" ExchangeRate="7.84640" LatestAvailableDate="2017-12-31"> <Group ID="Price and Volume"> <Ratio FieldName="NPRICE" Type="N">75.05000</Ratio> <Ratio FieldName="NHIG" Type="N">86.00000</Ratio> <Ratio FieldName="NLOW" Type="N">71.45000</Ratio> <Ratio FieldName="PDATE" Type="D">2018-07- 25T00:00:00</Ratio> <Ratio FieldName="VOL10DAVG" Type="N">12.50806</Ratio> <Ratio FieldName="EV" Type="N">2466752.00000</Ratio> </Group> <Group ID="Income Statement"> <Ratio FieldName="MKTCAP" Type="N">1505191.00000</Ratio> <Ratio FieldName="AREV" Type="N">321663.20000</Ratio> <Ratio FieldName="AEBITD" Type="N">177752.30000</Ratio> <Ratio FieldName="ANIAC" Type="N">86082.85000</Ratio> </Group> <Group ID="Per share data"> <Ratio FieldName="AEPSXCLXOR" Type="N">4.28869</Ratio> <Ratio FieldName="AREVPS" Type="N">27.04842</Ratio> <Ratio FieldName="ABVPS" Type="N">74.66691</Ratio> <Ratio FieldName="ACSHPS" Type="N">108.96660</Ratio> <Ratio FieldName="ACFSHR" Type="N">5.83985</Ratio> <Ratio FieldName="ADIVSHR" Type="N">4.01226</Ratio> </Group> <Group ID="Other Ratios"> <Ratio FieldName="AGROSMGN" Type="N">-99999.99000</Ratio> <Ratio FieldName="AROEPCT" Type="N">6.72498</Ratio> <Ratio FieldName="APR2REV" Type="N">2.77242</Ratio> <Ratio FieldName="APEEXCLXOR" Type="N">17.49954</Ratio> <Ratio FieldName="APRICE2BK" Type="N">1.13825</Ratio> <Ratio FieldName="Employees" Type="N">228899</Ratio> </Group> </Ratios> <ForecastData ConsensusType="Mean" CurFiscalYear="2018" CurFiscalYearEndMonth="12" CurInterimEndCalYear="2018" CurInterimEndMonth="3" EarningsBasis="PRX"> <Ratio FieldName="ConsRecom" Type="N"> <Value PeriodType="CURR">1.9167</Value> </Ratio> <Ratio FieldName="TargetPrice" Type="N"> <Value PeriodType="CURR">86.00753</Value> </Ratio> <Ratio FieldName="ProjLTGrowthRate" Type="N"> <Value PeriodType="CURR">6.9100</Value> </Ratio> <Ratio FieldName="ProjPE" Type="N"> <Value PeriodType="CURR">13.07573</Value> </Ratio> <Ratio FieldName="ProjSales" Type="N"> <Value PeriodType="CURR">433073.04033</Value> </Ratio> <Ratio FieldName="ProjSalesQ" Type="N"> <Value PeriodType="CURR">276091.27680</Value> </Ratio> <Ratio FieldName="ProjEPS" Type="N"> <Value PeriodType="CURR">5.73964</Value> </Ratio> <Ratio FieldName="ProjEPSQ" Type="N"> <Value PeriodType="CURR">1.64774</Value> </Ratio> <Ratio FieldName="ProjProfit" Type="N"> <Value PeriodType="CURR">168752.58051</Value> </Ratio> <Ratio FieldName="ProjDPS" Type="N"> <Value PeriodType="CURR">4.03148</Value> </Ratio> </ForecastData> </ReportSnapshot> -1 8993 -1 8486 -1 -1 -1 A: If you get XML then use lxml or BeautifulSoup to get data from XML. You can see lxml in use at the end of this code: data = b'''<?xml version="1.0" encoding="UTF-8"?> <ReportSnapshot Major="1" Minor="0" Revision="1"> <CoIDs> <CoID Type="RepNo">AC317</CoID> <CoID Type="CompanyName">HSBC Holdings plc (Hong Kong)</CoID> </CoIDs> <Issues> <Issue ID="1" Type="C" Desc="Common Stock" Order="1"> <IssueID Type="Name">Ordinary Shares</IssueID> <IssueID Type="Ticker">5</IssueID> <IssueID Type="CUSIP">G4634U169</IssueID> <IssueID Type="ISIN">GB0005405286</IssueID> <IssueID Type="RIC">0005.HK</IssueID> <IssueID Type="SEDOL">6158163</IssueID> <IssueID Type="DisplayRIC">0005.HK</IssueID> <IssueID Type="InstrumentPI">312270</IssueID> <IssueID Type="QuotePI">1049324</IssueID> <Exchange Code="HKG" Country="HKG">Hong Kong Stock Exchange</Exchange> <MostRecentSplit Date="2009-03- 12">1.14753</MostRecentSplit> </Issue> </Issues> <CoGeneralInfo> <CoStatus Code="1">Active</CoStatus> <CoType Code="EQU">Equity Issue</CoType> <LastModified>2018-07-20</LastModified> <LatestAvailableAnnual>2017-12-31</LatestAvailableAnnual> <LatestAvailableInterim>2018-03-31</LatestAvailableInterim> <Employees LastUpdated="2018-03-31">228899</Employees> <SharesOut Date="2018-07-24" TotalFloat="19882952713.0">19952507521.0</SharesOut> <ReportingCurrency Code="USD">U.S. Dollars</ReportingCurrency> <MostRecentExchange Date="2018-07-24">1.0</MostRecentExchange> </CoGeneralInfo> <TextInfo> <Text Type="Business Summary" lastModified="2017-03- 06T22:03:17">HSBC Holdings plc (HSBC) is the banking and financial services company. The Company manages its products and services through four businesses: Retail Banking and Wealth Management (RBWM), Commercial Banking (CMB), Global Banking and Markets (GB&amp;M), and Global Private Banking (GPB). It operates across various geographical regions, which include Europe, Asia, Middle East and North Africa, North America and Latin America. RBWM business offers Retail Banking, Wealth Management, Asset Management and Insurance. CMB services include working capital, term loans, payment services and international trade facilitation, among other services, as well as expertise in mergers and acquisitions, and access to financial markets. GB&amp;M supports government, corporate and institutional clients across the world. GPB's products and services include Investment Management, Private Wealth Solutions, and a range of Private Banking services.</Text> <Text Type="Financial Summary" lastModified="2018-07- 20T09:20:11">BRIEF: For the three months ended 31 March 2018, HSBC Holdings plc (Hong Kong) interest income increased 10% to $7.46B. Net interest income after loan loss provision increased 11% to $7.29B. Net income applicable to common stockholders decreased 1% to $3.09B. Net interest income after loan loss provision reflects Asia segment increase of 22% to $3.86B, Net Interest Margin, Total -% increase of 2% to 1.67%, Net Interest Spread.</Text> </TextInfo> <contactInfo lastUpdated="2018-07-20T09:20:26"> <streetAddress line="1">8 Canada Square</streetAddress> <streetAddress line="2"></streetAddress> <streetAddress line="3"></streetAddress> <city>LONDON</city> <state-region></state-region> <postalCode>E14 5HQ</postalCode> <country code="GBR">United Kingdom</country> <contactName></contactName> <contactTitle></contactTitle> <phone> <phone type="mainphone"> <countryPhoneCode>44</countryPhoneCode> <city-areacode>20</city-areacode> <number>79918888</number> </phone> <phone type="mainfax"> <countryPhoneCode>44</countryPhoneCode> <city-areacode>20</city-areacode> <number>79924880</number> </phone> </phone> </contactInfo> <webLinks lastUpdated="2016-11-07T05:00:04"><webSite mainCategory="Home Page">http://www.hsbc.com/</webSite><eMail mainCategory="Company Contact/E- mail"></eMail></webLinks> <peerInfo lastUpdated="2018-07-20T09:20:26"> <IndustryInfo> <Industry type="TRBC" order="1" reported="0" code="5510101010" mnem="">Banks - NEC</Industry> <Industry type="NAICS" order="1" reported="0" code="52211" mnem="">Commercial Banking</Industry> <Industry type="NAICS" order="2" reported="0" code="52393" mnem="">Investment Advice</Industry> <Industry type="NAICS" order="3" reported="0" code="52392" mnem="">Portfolio Management</Industry> <Industry type="SIC" order="0" reported="1" code="6035" mnem="">Federal Savings Institutions</Industry> <Industry type="SIC" order="1" reported="0" code="6029" mnem="">Commercial Banks, Nec</Industry> <Industry type="SIC" order="2" reported="0" code="6282" mnem="">Investment Advice</Industry> </IndustryInfo> </peerInfo> <officers> <officer rank="1" since="01/01/2013"> <firstName>John</firstName> <mI>Michael</mI> <lastName>Flint</lastName> <age>48 </age> <title startYear="2018" startMonth="02" startDay="21" iD1="CEO" abbr1="CEO" iD2="EDR" abbr2="Exec. Dir.">Chief Executive, Executive Director</title> </officer> <officer rank="2" since="09/24/2010"> <firstName>Iain</firstName> <mI>J.</mI> <lastName>Mackay</lastName> <age>56 </age> <title startYear="2010" startMonth="12" startDay="03" iD1="FID" abbr1="Fin. Dir." iD2="EDR" abbr2="Exec. Dir.">Group Finance Director, Executive Director</title> </officer> <officer rank="3" since="08/01/2015"> <firstName>Andy</firstName> <mI></mI> <lastName>Maguire</lastName> <age>51 </age> <title startYear="2015" startMonth="08" startDay="01" iD1="COO" abbr1="COO" iD2="MDR" abbr2="Mgng.Dir.">Group Chief Operating Officer, Group Managing Director</title> </officer> <officer rank="4" since="11/26/2010"> <firstName>Marc</firstName> <mI>M.</mI> <lastName>Moses</lastName> <age>60 </age> <title startYear="2014" startMonth="01" startDay="01" iD1="CRO" abbr1="CRO" iD2="EDR" abbr2="Exec. Dir.">Group Chief Risk Officer, Executive Director</title> </officer> <officer rank="5" since="NA"> <firstName>Elaine</firstName> <mI></mI> <lastName>Arden</lastName> <age>49 </age> <title startYear="NA" startMonth="" startDay="" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Managing Director, Group Head of Human Resources</title> </officer> <officer rank="6" since="01/01/2011"> <firstName>Samir</firstName> <mI></mI> <lastName>Assaf</lastName> <age>57 </age> <title startYear="2011" startMonth="01" startDay="01" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Group Managing Director, Chief Executive - Global Banking &amp; Markets</title> </officer> <officer rank="7" since="NA"> <firstName>Colin</firstName> <mI></mI> <lastName>Bell</lastName> <age>50 </age> <title startYear="NA" startMonth="" startDay="" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Managing Director, Group Head of Financial Crime Risk</title> </officer> <officer rank="8" since="10/01/2013"> <firstName>Peter</firstName> <mI>W.</mI> <lastName>Boyles</lastName> <age>62 </age> <title startYear="2013" startMonth="10" startDay="01" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Group Managing Director; Chief Executive of Global Private Banking</title> </officer> <officer rank="9" since="08/01/2015"> <firstName>Patrick</firstName> <mI>J.</mI> <lastName>Burke</lastName> <age>56 </age> <title startYear="2015" startMonth="08" startDay="01" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Group Managing Director; President and Chief Executive of HSBC USA</title> </officer> <officer rank="10" since="08/01/2015"> <firstName>Pierre</firstName> <mI></mI> <lastName>Goad</lastName> <age>56 </age> <title startYear="2016" startMonth="" startDay="" iD1="MDR" abbr1="Mgng.Dir." iD2="" abbr2="">Group Managing Director, Group Head of Employee Insight and Communications</title> </officer> </officers> <Ratios PriceCurrency="HKD" ReportingCurrency="USD" ExchangeRate="7.84640" LatestAvailableDate="2017-12-31"> <Group ID="Price and Volume"> <Ratio FieldName="NPRICE" Type="N">75.05000</Ratio> <Ratio FieldName="NHIG" Type="N">86.00000</Ratio> <Ratio FieldName="NLOW" Type="N">71.45000</Ratio> <Ratio FieldName="PDATE" Type="D">2018-07- 25T00:00:00</Ratio> <Ratio FieldName="VOL10DAVG" Type="N">12.50806</Ratio> <Ratio FieldName="EV" Type="N">2466752.00000</Ratio> </Group> <Group ID="Income Statement"> <Ratio FieldName="MKTCAP" Type="N">1505191.00000</Ratio> <Ratio FieldName="AREV" Type="N">321663.20000</Ratio> <Ratio FieldName="AEBITD" Type="N">177752.30000</Ratio> <Ratio FieldName="ANIAC" Type="N">86082.85000</Ratio> </Group> <Group ID="Per share data"> <Ratio FieldName="AEPSXCLXOR" Type="N">4.28869</Ratio> <Ratio FieldName="AREVPS" Type="N">27.04842</Ratio> <Ratio FieldName="ABVPS" Type="N">74.66691</Ratio> <Ratio FieldName="ACSHPS" Type="N">108.96660</Ratio> <Ratio FieldName="ACFSHR" Type="N">5.83985</Ratio> <Ratio FieldName="ADIVSHR" Type="N">4.01226</Ratio> </Group> <Group ID="Other Ratios"> <Ratio FieldName="AGROSMGN" Type="N">-99999.99000</Ratio> <Ratio FieldName="AROEPCT" Type="N">6.72498</Ratio> <Ratio FieldName="APR2REV" Type="N">2.77242</Ratio> <Ratio FieldName="APEEXCLXOR" Type="N">17.49954</Ratio> <Ratio FieldName="APRICE2BK" Type="N">1.13825</Ratio> <Ratio FieldName="Employees" Type="N">228899</Ratio> </Group> </Ratios> <ForecastData ConsensusType="Mean" CurFiscalYear="2018" CurFiscalYearEndMonth="12" CurInterimEndCalYear="2018" CurInterimEndMonth="3" EarningsBasis="PRX"> <Ratio FieldName="ConsRecom" Type="N"> <Value PeriodType="CURR">1.9167</Value> </Ratio> <Ratio FieldName="TargetPrice" Type="N"> <Value PeriodType="CURR">86.00753</Value> </Ratio> <Ratio FieldName="ProjLTGrowthRate" Type="N"> <Value PeriodType="CURR">6.9100</Value> </Ratio> <Ratio FieldName="ProjPE" Type="N"> <Value PeriodType="CURR">13.07573</Value> </Ratio> <Ratio FieldName="ProjSales" Type="N"> <Value PeriodType="CURR">433073.04033</Value> </Ratio> <Ratio FieldName="ProjSalesQ" Type="N"> <Value PeriodType="CURR">276091.27680</Value> </Ratio> <Ratio FieldName="ProjEPS" Type="N"> <Value PeriodType="CURR">5.73964</Value> </Ratio> <Ratio FieldName="ProjEPSQ" Type="N"> <Value PeriodType="CURR">1.64774</Value> </Ratio> <Ratio FieldName="ProjProfit" Type="N"> <Value PeriodType="CURR">168752.58051</Value> </Ratio> <Ratio FieldName="ProjDPS" Type="N"> <Value PeriodType="CURR">4.03148</Value> </Ratio> </ForecastData> </ReportSnapshot>''' import lxml.etree soup = lxml.etree.fromstring(data) for item in soup.xpath('//IssueID'): print(item.attrib['Type'], ':', item.text) Result: Name : Ordinary Shares Ticker : 5 CUSIP : G4634U169 ISIN : GB0005405286 RIC : 0005.HK SEDOL : 6158163 DisplayRIC : 0005.HK InstrumentPI : 312270 QuotePI : 1049324
{ "pile_set_name": "StackExchange" }
Q: \llap (or \rlap) at the beginning of an indented paragraph If I use a \llap{text} command at the beginning of an indented paragraph, the text is not indented and is put on the line above the paragraph. \documentclass{article} \begin{document} \parindent=2cm \llap{x}Hello H\llap{x}ello \end{document} Using the code above, I get the x above and far too the left, relative to the H in the first case, but I get the correct result in the second case (the x is just to the left of the e). How can I get the x just to the left of the H? I tried putting a vphantom{X} just before the \llap to force the paragraph to start, but that didn't change the result at all. A: \llap is not a LaTeX box command and does not start a paragraph. \documentclass{article} \begin{document} \parindent=2cm \makebox[0pt][r]{x}Hello H\makebox[0pt][r]{x}ello \end{document} A: You can also use \indent\llap{x}Hello
{ "pile_set_name": "StackExchange" }
Q: Keeping authentication state between Firebase - WebApp (.NET Core MVC) I am creating an ASP.NET Core MVC app, where the authentication provider will be FireBase. My Web App is hosted in Azure and, once user signs in, it sends an HTTPS request to my firebase endpoint, which looks like https://myFirebaseApp.cloudfunctions.net/signup with username and password, and it will create a user as below; https://firebase.google.com/docs/auth/web/start?authuser=0 firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // ... }); My intention is to get a kind of session token in the response and save it in a cookie. And everytime user navigates to another page, I will need to validate that cookie/token to keep authentication persistent. What would be the way to achieve this? Or is there any better practice to keep this integration? A: I found out I can use custom tokens for this. What I need to use is createCustomToken and signInWithCustomToken methods. https://firebase.google.com/docs/auth/admin/create-custom-tokens Create Token: createCustomToken(request, response) { let uid = request.query.uid; if (!uid) { response.send("query.uid is required."); return; } let additionalClaims = { myExtraField: 1 }; this.admin .auth() .createCustomToken(uid, additionalClaims) .then(function(customToken) { // Send token back to client response.send(customToken); }) .catch(function(error) { response.send(error); }); } Sign-in: signInWithCustomToken(request, response) { const id_token = request.query.id_token; if (!id_token) { response.send("query.id_token is required."); return; } // Sign in with signInWithCustomToken. this.authService .signInWithCustomToken(id_token) .then(result => { response.send(result); }) .catch(error => { response.send(error); }); }
{ "pile_set_name": "StackExchange" }
Q: Identify these Warhammer creatures In a recent trailer for Total War: Warhammer, we see these creatures of Chaos for a brief moment. I don't recognize them. Can anyone tell me who or what they are? A: I believe these handsome fellows are Gorebeasts.
{ "pile_set_name": "StackExchange" }
Q: C# and SQLGeometry: Combining Database Rows and WPF I'm pretty sure I want to use the SqlGeometry datatype to store a bunch of polygons in a database. Does the SqlGeometry type inter-operate into C# and WPF. Can you just directly cast an SqlGeometry to a Shape or Path? Secondly, Is it possible to store more than 1 polygon in a single SqlGeometry column? A: This link shows how to view SqlGeometry visually in C#: http://www.codeproject.com/KB/database/sqlgeometry.aspx This link shows how to manipulate SqlGeometry data types in C#: http://www.nickharris.net/tag/geometry-data-type/ Regarding multiple polygons per SqlGemotry column, I don't think you can do this per: http://barendgehrels.blogspot.com/2011_04_01_archive.html which converts multi-geometry to a list of SqlGeometry.
{ "pile_set_name": "StackExchange" }
Q: Navigation through json (phyton) I'm trying to navigation through a json file but cannot parse properly the 'headliner' node. Here is my JSON file : { "resultsPage":{ "results":{ "calendarEntry":[ { "event":{ "id":38862824, "artistName":"Raphael", }, "performance":[ { "id":73632729, "headlinerName":"Top-Secret", } } ], "venue":{ "id":4285819, "displayName":"Sacré" } } } } Here is what I my trying to do : for item in data ["resultsPage"]["results"]["calendarEntry"]: artistname = item["event"]["artistName"] headliner = item["performance"]["headlinerName"] I don't understand why it's working for the 'artistName' but it's not working for 'headlinerName'. Thanks for your help and your explanation. A: Notice your performance key: "performance":[ { "id":73632729, "headlinerName":"Top-Secret", } } ], The json you posted is malformed. Assuming the structure is like: "performance":[ { "id":73632729, "headlinerName":"Top-Secret", } ], You can do: for i in item: i["headlinerName"] or as @UltraInstinct suggested: item["performance"][0]["headlinerName"]
{ "pile_set_name": "StackExchange" }
Q: Ways to implement recipricals on Verilog I want to implement a reciprical block on Verilog that will later be synthesized on an FPGA. The input should be a signed 32 bit wordlength with a 16 bit fraction length. The output should have the same format. Example input : x ---> output ---> 1/x I have solved the problem using the inbuilt IP core divider. I'm wondering if there is an elegant/altenative way of solving this by for example by bit shifting or 2's complement with some xor grinds. I have used the IP core to implement the inverse as it says in the manual but for some reason that i don't really understand the result is wrong and it needs to be shifted to the left by 1. For example; Reciprical of 1 gives 0.5 . Reciprical of 2 gives 1. Below is a section from the manual and my testbench code Test bench module reciprical_tb; // Inputs reg clk; reg [1:0] dividend; reg [31:0] divisor; // Outputs wire rfd; wire [1:0] quotient; wire [31:0] fractional; // Instantiate the Unit Under Test (UUT) reciprical uut ( .rfd(rfd), .clk(clk), .dividend(dividend), .quotient(quotient), .divisor(divisor), .fractional(fractional) ); // clock always begin #5 clk = ~clk; end initial begin // Initialize Inputs clk = 0; dividend = 2'b1; // 1 divisor = 2**16;; // = 1 when fraction length is 16bit // Wait 100 ns for global reset to finish #100; // Add stimulus here :: Inverse of 2 should give 0.5 //$display("inv(%g) => %g || inv = %b",$itor(divisor)*2.0**-16, $itor(fractional)*2.0**-16, fractional); //gives zero $monitor("inv(%d) => q = %d || inv = %b", divisor>>>16,fractional>>>16, fractional); //gives a wrong answer by a factor of 2 // Using the monitor i get inv(1) = 0.5 instead of 1. #100; end endmodule Manual section (page 4): ... The divider can be used to implement the reciprocal of X; that is the 1/X function. To do this, the dividend bit width is set to 2 and fractional mode is selected. The dividend input is then tied to 01 for both unsigned or signed operation, and the X value is provided via the divisor input. Ip Core used A: Trying to debug part of the question: can you try : // Wait 10 clock cycles repeat (10) begin @(posedge clk); end // Add stimulus here :: Inverse of 2 should give 0.5 $display("dsiplay inv(%g) => %g || inv = %b",$itor(divisor)*2.0**-16, $itor(fractional)*2.0**-16, fractional); //gives zero $monitor("inv(%d) => q = %d || inv = %b", divisor>>>16,fractional>>>16, fractional); //gives a wrong answer by a factor of 2 // Using the monitor i get inv(1) = 0.5 instead of 1. // Wait 10 clock cycles repeat (10) begin @(posedge clk); end $display("dsiplay inv(%g) => %g || inv = %b",$itor(divisor)*2.0**-16, $itor(fractional)*2.0**-16, fractional); //End simulation $finish(); As monitor is only issued once, it might be after 200ns that it is actually firing and outputting the updated value.
{ "pile_set_name": "StackExchange" }
Q: The set of compact open subsets of a compact set is a $\sigma$-algebra? Let X be a compact set such that its compact open subsets form a basis for the topology. I ask if they form a $\sigma$-algebra. Let's denote this set by $\tau_c(X)$. The first property is easy: 1)$U\in\tau_c(X)\Longrightarrow X\setminus U\in\tau_c(X)$ 2) $\{U_i\}_{i\in\mathbb{N}}\subset\tau_c(X)\Longrightarrow\bigcup_{i\in\mathbb{N}}{U_i}\in\tau_c(X)$. For the second property it is clear that the union is open. Therefore, my question reduces to ask if this set is compact. If the answer is yes, I think it is key the fact that $X$ is compact. A: A counterexample is $X=\{1,1/2,1/3,1/4,\dots\}\cup\{0\}$ as a subspace of $\mathbb{R}$: every singleton except $\{0\}$ is open, so $\{0\}$ is a countable intersection of compact open sets but is not open. In fact, virtually any example is a counterexample: it is possible to show that the compact open sets are a $\sigma$-algebra iff $X$ is finite (or iff the $T_0$ quotient of $X$ is finite, if you don't require $X$ to be Hausdorff).
{ "pile_set_name": "StackExchange" }
Q: check internet connection in background service every 30 min Hello I want to make an app that will check internet connection in background every 30mins and if so it will send some really small json data to server. Don't know if doing right but now I have: package com.example.lenovotp.sender; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; import java.util.Calendar; public class MyClass extends IntentService{ private static final String TAG = "com.example.lenovotp.sender"; private AlarmManager alarmMgr; private PendingIntent alarmIntent; Calendar calendar = Calendar.getInstance(); public MyClass(){ super(""); } @Override protected void onHandleIntent(Intent intent) { AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); intent = new Intent(this, MyClass.class); PendingIntent alarmIntent = PendingIntent.getService(this, 0, intent, 0); alarmMgr.set(AlarmManager.RTC_WAKEUP, 1000 * 30, alarmIntent); ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); //boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; if(isConnected!=false){ Toast.makeText(this, "Network is avail!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Network is NOT avail!", Toast.LENGTH_LONG).show(); } } } And in manifest I have in last postition in is <?xml version="1.0" encoding="utf-8"?> <!-- Permissions --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.WAKE_LOCK"/> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyClass"/> </application> And in MainActivity package com.example.lenovotp.sender; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this,MyClass.class); startService(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } So now I don't know how to: make it work even app is not running or destroyed by user. it check connectivity every 30mins and if so it sends some data to server. Thanks in advance. UPDATED A: A few things: Subclass IntentService instead of Service. Services run on the main (UI) thread, but an IntentService will do its work in a background thread (in onHandleIntent()), and it automatically stops itself after finishing its work. In your service, use AlarmManager to schedule your next "wakeup" in 30 minutes. You can find numerous examples how to use AlarmManager all over the web. You may need a way to schedule the first "wakeup" of your service after the device boots. For this you'll need a BroadcastReceiver in your manifest that is registered to receive the ACTION_BOOT_COMPLETED broadcast. This requires you to have the RECEIVE_BOOT_COMPLETED permission. Examples of this are all over the web as well.
{ "pile_set_name": "StackExchange" }
Q: Search using REPLACE in a SELECT with PDO and .MDB ACCESS, with PHP I'm trying to write a mysql query that will match names from a table and the name in the database can contain dots or no dots. So, for example I would like my query string fast to match all of these: fast, f.ast, f.a.s.t etc. I use PHP, with PDO connecting to a .MDB database. I tried what I found here, with no success (I get error): SELECT * FROM table WHERE replace(col_name, '.', '') LIKE "%fast%" I think PDO for MDB databases is missing some functions :( Any solution? A: Thanks to Doug, I solved with: $variable = implode("[.]", str_split($variable)) . "[.]"; and: SELECT * FROM table WHERE col_name LIKE "%" . $variable ."%";
{ "pile_set_name": "StackExchange" }
Q: Where can I find Vagrant packages? Vagrant is a tool to build and manage virtual machines for developers. It has a getting started on Ubuntu guide that contains iffy-looking suggestions like $ sudo ln -s /usr/bin/ruby1.8 /usr/bin/ruby # wtf??? or installing RubyGems from source rather than from Ubuntu packages, and then using gem install to install vagrant itself. I'm not feeling comfortable just following those instructions. Is there perhaps a PPA? Are there, perhaps, alternative tools that are packaged for Ubuntu? A: Nowadays you can download self-contained .deb files from http://www.vagrantup.com/downloads.html Not as good as a PPA, but at least you can introspect what files get installed where and remove the package cleanly. A: 12.04 Vagrant 1.0.1 is now included in universe in 12.04 and you can install this via the Software Center.
{ "pile_set_name": "StackExchange" }
Q: Remove CiviCRM and Drupal links / banner on profile form we have setup an online profile form that new members to our charity can complete. The information then pulls directly into CiviCRM. When accessing the profile / form online there are drupal and CiviCRM headers / footers and links on there that we would prefer to remove: Is anybody aware of a way to do this? Many thanks ............................................................. Thanks for your help guys it has been extremely useful and and I have now removed the links / logo's in the footer. Unfortunately however I am still struggling to remove the logo and the "Home" link from the header, as per below: I have tried unticking the logo option under www.yoursite.com/admin/appearance however this did not seem to make a difference (I am happy for it to be removed from public and private / internal view so any option to get rid of it is fine :)). It would also be great if we can remove the "Home" link. We have our pulbic theme as CiviCRM Seven if that is any help at all. Finally is there a way to change the background colour of the public profile / site - Currently it is just blank / white so it would be great to add the colour of our main website theme into there. Thanks again for all your great help, Terry ..................................... As per the image below the logo option has been unticked but the logo and home link are still present. A: To remove the Drupal footer (This is a block called - Powered by Drupal) – www.yoursite.com/admin/structure/block/manage/system/powered-by/configure Under region settings, set all to - None To remove empowered by CiviCRM – www.yoursite.com/civicrm/admin/setting/misc?reset=1 Set Display "empowered by CiviCRM" to No For the header, that’s the logo, which can be changed/removed from the CiviCRM public theme – www.yoursite.com/admin/appearance A: Certain things can be turned off from UI but others needs to be hidden by css Since you want to hide this option on public facing forms than you can switch the theme from using CiviCRM Seven to use your default one by navigating to Appearance(/admin/appearance). Scroll down and change the 'CiviCRM Public theme' right at the bottom of the page to use your default theme. (If you have CiviCRM theme module enabled) If not 1 than Hide Logo from header - You will need to add below css in CiviCRM seven theme styling file to hide the logo > body.page-civicrm #branding { background-image: none !important; } empowered by CiviCRM - This can be disabled by navigating to CiviCRM >> Administrator >> System Settings >> Misc (Undelete, PDFs, Limits, Logging, Captcha, etc.). Change the option for 'Display "empowered by CiviCRM"' to and save the form. Powered By Drupal - Is a Drupal block which can be disabled by navigating to Structure >> Blocks. Scroll down and find 'Powered by Drupal' and change the corresponding drop down option to none and save. HTH Pradeep
{ "pile_set_name": "StackExchange" }
Q: Do I have to use my realtor on a For Sale by Owner home I found a For Sale by Owner (FSBO) home that I love through a family friend. The seller has sold two of their homes before with no broker help from them or the buyer. They don't want pay any amount to a broker. I contacted the homeowner well before I signed a "buyers agreement". I was in back in forth contact and even saw the home before I hired a realtor. (Long story but the seller was not sure if they wanted to sell or wait till after the new year to sell) My buyers agreement is not very long so this is the only paragraph that pertains to buying fees... "BROKER'S FEE. The Buyer shall pay the Broker compensation in the amount of ("Broker's Fee") described above, whether through the services of the Broker, or otherwise. Any compensation paid to the Broker by  the Seller or a listing company shall be credited against the compensation due under this Agreement. The Broker may retain any additional compensation offered by the seller's representative, even if this causes the compensation paid to the Broker to exceed the fees specified above. In no case shall the compensation be less than the fees specified above." Also states I can cancel at anytime but do not want the broker to come back and want that 3% at a later date. (The realtor has no idea I have been looking at this FSBO and did not find it for me) Paying the 3% fee to my realtor is out of the question since this home will stretch my budget anyway. What are my options here? Any advice? Thanks. A: Without seeing the entire agreement it is impossible to say. Most buyers agent agreements have a clause that they need to be paid in the event that you buy any house in some time period after you hire them, because...well, because they want their money. (Although also to prevent buyers doing deals behind their backs). If yours genuinely doesn't then you may be OK. But if it does then yes, they will ask for their money Your best bet is to ask your agent. Unless you were contemplating something underhand they will find out anyway. Alternatively get a lawyer or another agent to look at the contract. If the agent really did nothing to help you find the property, and you saw it before you hired them, they may waive the fee. But they probably feel they should be compensated for the work they did helping you look for properties, even if you didn't find one through them. EDIT: In comments you say that your agreement is cancellable and you only have to pay if the property has been presented to you by the realtor. That sounds like you will OK, but nobody can be sure without reading the whole contract. You also say "I love my realtor", which forces me to repeat what I said above: ask your realtor this question. They will know the answer.
{ "pile_set_name": "StackExchange" }
Q: MSSQL how to properly Lock rows and insert? I want to insert two rows in 2 different tables but want to roll back the transaction if some pre conditions on the second table are met. Does it work In .NET if i simply start a transaction scope and execute a sql query to check data on the second table before executing the insert statements? If so, what is the isolation level to use? I don't want it lock the whole tables as there are going to be many inserts. UNIQUE constraint is not an option because what i want to do is guarantee not more than 2 rows in the 2nd table to have the same value (FK to a PK column of table 1) Thanks A: Yes you can execute a sql query to check data on the second table before executing the insert statements. Fyi the default is Serializable. From MSDN: The lowest isolation level, ReadUncommitted, allows many transactions to operate on a data store simultaneously and provides no protection against data corruption due to interruptive transactions. The highest isolation level, Serializable, provides a high degree of protection against interruptive transactions, but requires that each transaction complete before any other transactions are allowed to operate on the data. The isolation level of a transaction is determined when the transaction is created. By default, the System.Transactions infrastructure creates Serializable transactions. You can determine the isolation level of an existing transaction using the IsolationLevel property of a transaction. Given your requirement, I do not think you want to use Serializable since it is the least friendly for high volume multi user systems because they cause the most amount of blocking. You need to decide on the amount of protection that is required. At a minimum, you should look into READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ. The following answer goes over Isolation Levels in detail. From that, you can decide what level of protection is sufficient for your requirement. Transaction isolation levels relation with locks on table
{ "pile_set_name": "StackExchange" }
Q: JLink (flash load)/MDR32F1QI в Linux Недавно занялся программированием Российского микроконтроллера MDR32F1QI. Проблем со сборкой не говоря уже про сам контроллер не возникло. Однако, вот уже месяц как прошиваю контроллер из Windows c помошью Keil'a или програмки из поставки отладочной платы, а отлаживаю в Linux/Eclipse/JLink V8. Поскажите пожалуйста что мне написать в makefile'e для прошивки моего соотечественника (как угодно, хоть бы и вне makefile'a отдельной утилитой). Пробовал вот такую строку: openocd -f target/1986ve1t.cfg -c init; reset halt; flash write_image erase $(RESULT).bin 0x00000000; reset run; shutdown В ответ получаю следующее: Open On-Chip Debugger 0.9.0 (2015-09-02-10:42) Licensed under GNU GPL v2 For bug reports, read http://openocd.org/doc/doxygen/bugs.html Error: Debug adapter does not support any transports? Check config file order. Error: unable to select a session transport. Can't continue. shutdown command invoked reset: unknown terminal type halt Terminal type? Что за "terminal type" и что не нравится openocd? Имя файла конфигурации openocd (1986ве1т.cfg) изменено (русские буквы в названиях файлов понятны не всем вспомогательным утилитам) A: unknown terminal type halt выдаёт команда linux reset (см. man reset, ну не находит она терминала с именем halt). Точки с запятой в командной строке разделяют команды shell, поэтому так получилось. По-видимому всё после -c следует заключить в апострофы: openocd -f target/1986ve1t.cfg -c 'init; reset halt; flash write_image erase $(RESULT).bin 0x00000000; reset run; shutdown'
{ "pile_set_name": "StackExchange" }
Q: Evaluating $\int \sqrt{x}\ln(2x)\:\mathrm{d}x$ I am learning to an exam and stumbled upon this integral. $$\int \sqrt{x}\ln(2x)\:\mathrm{d}x$$ the result should be $\frac{2}{3}\sqrt{x^{3}}\left(\ln(2x)-\frac{2}{3}\right)+C$, but I am still unable to get there… Every help will be appreciated. A: Hint Integrate by parts with $u=\log(2x)$ and $v'=\sqrt x ~dx$. So $u'=\frac{1}{x}~dx$ and $v=\frac{2 x^{3/2}}{3}$. I am sure that you can take from here. A: I think I'd start this by substituting $x=y^2$ $$\int 2y^2\ln2y^2dy$$ Now use properties of logarithms. $$\int2y^2\ln2dy+\int4y^2\ln ydy$$ $$u=\ln y,du=\frac{dy}y$$ $$dv=4y^2dy,v=\frac43y^3$$ $$\frac23y^3\ln2+\frac43y^3\ln y-\int\frac43y^2dy=$$ $$\frac23y^3\ln2+\frac23y^3\ln y^2-\frac49y^3+C=$$ $$\frac23y^3\ln2y^2-\frac49y^3+C$$ Just a little rearranging from here and substituting back for $x$ should get you the right form.
{ "pile_set_name": "StackExchange" }
Q: MySQL query to count user orders by type I have this 3 tables: users, orders and order_item. When a user can have a order, and the order item can be event only, membership only or both, and so 2 line will be written to the order_items users tables id | user_id | name | phone ---|-----------|-------|------ 1 | 123456789 | Jon | 555-55555 2 | 123456780 | Alice | 555-6666 orders tables id | user_id | user_uid | user_info ---|---------|-----------|---------- 1 | 1 | 123456789 | bla 2 | 2 | 123456780 | foo 3 | 2 | 123456780 | foo order_items table id | order_id | order_type | price --- | -------- | ---------- | ------ 1 | 1 | membership | 70 2 | 1 | event | 200 3 | 2 | event | 300 4 | 3 | membership | 70 The relationship is like this, order_items.order_id -> orders.id orders.user_id -> users.id orders.user_uid -> users.user_id I'm looking for a query which will produce this type of output, user_id | name | count_membership | count_events | total_orders -------- | ------ | ------------------ | -------------- | -------------- 123456789 | Jon | 1 | 1 | 1 123456780 | Alice | 1 | 1 | 2 I like to count the total orders a user have, and count how many of each of item he have. in the end I like to filter out all users where count_membership = 0 Thanks in advance, A: You can get the expected result set by using some conditional aggregation select u.user_id, u.name, sum(oi.membership_count) membership_count, sum(oi.event_count) event_count, count(o.id) total_orders from users u join orders o on u.id = o.user_id join ( select order_id, sum(order_type = 'membership') membership_count, sum(order_type = 'event') event_count from order_items group by order_id ) oi on o.id = oi.order_id group by u.user_id,u.name Demo
{ "pile_set_name": "StackExchange" }
Q: Which coder should I use to code a long property using NSCoder? I have an object I must encode using encodewithcoder but it's a 'long' number and I'm not sure if I must encode it like a simple int, a int32 or a int64. Apple's documentation doesn't seems to be useful for me to figure out since it never refers to 'long' type. Which coder is the proper one?. Thank you A: For iOS, a long is 32-bits, same as an int. long long gives you 64-bits. long someVar = 42l; [someEncoder encodeInt32:someVar forKey:@"someKey"];
{ "pile_set_name": "StackExchange" }
Q: algorithm to find the total number of ways to reach the last layer from the initial one of a directed graph I want an algorithm to find the total number of ways to reach the last layer from the initial one of a directed graph whose last and first layers contain only one node .Please suggest which algorithm should i use . A: If there is cycle on the path from the first node to the last one, the number of paths is infinitely large. Otherwise, there are no cycles, so a part of the graph we are interested in is acyclic(there a can be a cycle somewhere in the graph, but if does not lie on the path between the first and last node, it does not matter). That's why can use dynamic programming to count the number of paths: The base case: f(start node) = 1. Transitions: f(node) = sum f(neighbor) for all neighbors of the node. We can compute this value correctly because there is no cycle. The answer is f(last node). We can either use topological sort explicitly or write a recursive function with memoization(in both cases, the time and space complexity is linear).
{ "pile_set_name": "StackExchange" }
Q: How to call a function after running winform application I am built same win Form that opens some website with webBrowser after this i need to run runMyfunction,but this doesn't happens. Then i run runMyfunction, all stops and when i debug it it stays on Application.Run(new Form1()); What i am missing here? This my code : namespace UmbWin { static class Program { [STAThread] static void Main() { //I tried this also //Form1 myForm = new Form1(); //myForm.Show(); //myForm.runMyfunction()- doesn't do anything Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } public Form1() { InitializeComponent(); } [STAThread] private void Form1_Load(object sender, EventArgs e) { string authHeader = "User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"; webBrowser.Navigate("https://www.test.com/Default.aspx", null, null, authHeader); runMyfunction(); } public void runMyfunction() { //here where it stops and does nothing HtmlElement head = webBrowser.Document.GetElementById("123"); HtmlElement scriptEl = webBrowser.Document.CreateElement("script"); } A: That is because Application.Run will only complete once the main form of the application is closed. Application.Run runs the message loop (it checks for clicks and other Windows events. Read up on how Windows / Win32 works if you don't know what this all means). It is meant to run forever. Your runMyfunction will only run once after the Navigate call. That's all. If you want to run it after every navigate, subscribe to the DocumentCompleted event.
{ "pile_set_name": "StackExchange" }
Q: The homotopy category of the category of enriched categories We know that if $\mathcal C$ is a combinatorial monoidal model category such that all objects are cofibrant and the class of weak equivalences is stable under filtered colimits, then $\mathsf{Cat}_{\mathcal C}$, the category of all (small) $\mathcal C$-enriched categories, has the categorical model structure. My question is: Is the homotopy category of $\mathsf{Cat}_{\mathcal C}$, with respect to the categorical model structure, the category of all (small) $\operatorname{Ho}\mathcal C$-enriched categories, $\mathsf{Cat}_{\operatorname{Ho}\mathcal C}$? In other words, does every $\operatorname{Ho}\mathcal C$-enriched category arises from a $\mathcal C$-enriched category? (I am asking this question for the following reason. We know that $(\infty,1)$-categories are schematically categories enriched over the category of homotopy types, which is equivalent to $\operatorname{Ho}\mathsf{SSet}$. If the above question is not true for $\mathcal C=\mathsf{SSet}$, then there exists a $\operatorname{Ho}\mathsf{SSet}$-enriched category that does not arise from a simplicial category. This seems weird, since the theory of simplicial categories is a well-accepted model for $(\infty,1)$-categories. Therefore I expect the answer to the above question to be ''Yes'', at least in the case where $\mathcal C=\mathsf{SSet}$. But I am not able to give a proof, nor can I find any references to this question.) A: A recipe for a counterexample: Let $(X,e:\Delta^0\to X,m:X\times X\to X)$ be monoid object in the homotopy category of spaces $h\mathcal{S}$ (that is, an H-monoid). Note that this is a property of the triple. Then we can form an $h\mathcal{S}$-enriched category $\mathbf{B}X$ with set of objects $\{\ast\}$ and such that $\mathbf{B}X(\ast,\ast)=X,$ with composition given by $$m:X\times X \to X.$$ and unit given by $e:\Delta^0 \to X$ the basepoint of $X$. In general, an H-monoid structure $(X,e,m)$ only specifies a canonical $A_2$-algebra structure on $X$ with the added stipulation that there exists an $A_3$-structure extending the $A_2$-structure, and there exist many examples (none of which I know!) of $A_2$-structures admitting (possibly many) extensions to an $A_3$ structure, none of which extend to an $A_\infty$-structure. Unfortunately, even having asked some experts, it's not so easy to come up with an example of such a space. But it is a theorem that every $A_\infty$-space is equivalent to an honest monoid in spaces. So it suffices to find any H-monoid $(X,e,m)$ in spaces that doesn't admit a lift to an $A_\infty$-monoid, then take $\mathbf{B}X$. This gives an example of an $h\mathcal{S}$-enriched category that cannot lift to an honest $\mathcal{S}$-enriched category, because if it did, it would necessarily specify an $A_\infty$-structure on $X$ lifting $(X,e,m)$. Edit: Kevin Carlson's comment below gives an example of such spaces from Stasheff and Adams and a source, so check it out! A: Summarizing a discussion in the comments on Harry's answer, we can consider the case $\mathcal C=\mathrm{Gpd}$, with the canonical model structure: weak equivalences are just the equivalences of groupoids, cofibrations are functors injective on objects, and fibrations are isofibrations. A $\mathcal C$-enriched category with one object is then precisely a strictly monoidal groupoid. In contrast, a $\mathrm{Ho}(\mathcal C)$-enriched category with one object is essentially the same thing as an $A_3$-monoidal groupoid-we get a tensor product, which is certainly associative up to non-specified isomorphism, but there is no reason why the associators should satisfy the pentagon identity, and indeed they need not. For a counterexample, consider the $A_3$-monoidal groupoid $G$ freely generated by a single object $x$. For simplicity, let's also make it strictly unital. Then the objects of $G$ are given by rooted binary trees, corresponding to parenthesizations of finite strings of $x$'es. The morphisms are freely generated by the associator isomorphism between the two rooted binary trees of three leaves, together with the functoriality of the tensor product $\otimes:G\times G\to G$ which fuses two trees by adding a new root to their disjoint union. It is in fact possible to describe the morphisms in $G$ without reference to the tensor product: they are sequences of elementary moves, where an elementary move out of a binary tree $T$ is given by taking a node $N$ which is the left child of its parent $P$ and replacing $P$'s right child with $N$, $P$'s left child with $N$'s left child, $N$'s left child with its right child, and $N$'s right child with $P$'s right child. Under this description, one can see that the two different paths from $((xx)x)x$ to $x(x(xx))$ around the pentagon are not equal in $G$. (For comparison, the free strictly unital $A_4$-monoidal groupoid on $x$ has exactly one morphism between two binary trees whenever there exists any such sequence of elementary moves transforming one into the other.) Thus $G$ gives an $A_3$-monoidal groupoid which does not arise from an $A_4$-monoidal one, equivalently, not from a strictly monoidal one. EDIT: As Harry notes, this is not quite a counterexample to your question, as it's not clear that it's impossible to make a different choice of the associators that would extend to $A_4$. It seems unlikely, but also that it would be complicated to make an elementary argument against it. Here is a proposed easier example, coming from $\mathcal C=\mathrm{Cat}$ instead of $\mathrm{Gpd}$, again with the canonical model structure. We let $C$ be the free $A_3$-monoidal category generated by a co-pointed object. So as compared to $G$ from above, $C$ contains a map $p:x\to I$ contracting a leaf which freely generates $C$ from $G$ under $\otimes$ and naturality with respect to the elementary moves. I'll refer to any tensor product of $p$'s and identities as a projection. Call the canonical associators, given by elementary moves, $\alpha$; I claim there is no alternative choice $\beta$ of associators for an $A_3$-structure on $C$, so that $C$'s underlying $\mathrm{Ho}(\mathrm{Cat})$-enriched category arises from no monoidal category. To show that $C$ admits no $A_4$-monoidal structure, note that $\beta_{x,x,x}:(xx)x\to x(xx)$ is uniquely determined as it was in $G$-we've added no new morphisms between isomorphic trees. Furthermore, while morphisms between trees with different numbers of leaves cannot be uniquely written as strings of elementary moves and projections, the only relation on them is naturality of projections with respect to elementary moves. The induced equivalence relation respects lengths of strings of elementary moves and projections, so that any morphism of $C$ has a well defined length given by the length of any representing string of elementary moves and projections. Then to show for instance that $\beta_{xx,x,x}=\alpha_{xx,x,x}$, we can consider the equality $$(px)(xx)\circ \beta_{xx,x,x}=\beta_{x,x,x}\circ ((px)x)x:((xx)x)x\to x(xx).$$ This implies that $\beta_{xx,x,x}$ must be an elementary move, by computing lengths. And there is a unique elementary move $((xx)x)x\to (xx)(xx)$, namely $\alpha_{xx,x,x}$. Similarly one shows all the associators between four-leaf trees are the canonical ones, so that the pentagon cannot commute. If I haven't missed anything in this example, it seems as if its nerve should give rise to an $A_3$-but-not-$A_4$ space. I can't tell if it can be made to give such a groupoid, though.
{ "pile_set_name": "StackExchange" }
Q: I want to copy my present working directory location into abc.text file by replacing some sentence I want to copy my present working directory location into abc.text file by replacing some sentence. For example, 4th line of abc.text is "my name is narender" and i want replace pwd path instead of "my name is narender". please help A: Using sed for in-place replacement. $ sed -i "s|replace me|$PWD|g" text.txt (remember that characters in the $variable will interfere with the sed expression). sed option: -i[suffix]Edit files in place (makes backup if SUFFIX supplied). bash variables: $PWDThe current working directory as set by the cd command. Further reading: Is it possible to escape regex metacharacters reliably with sed
{ "pile_set_name": "StackExchange" }
Q: How to write a React Stateless Functional Component in Typescript? I have this: import React, { useReducer } from 'react'; import { Item, List } from '../Types'; type Props = { items: List; }; const TodoList: React.SFC<Props> = ({ items, children }) => { return items.map((item: Item) => <div key={item.id}>{item.id}</div>); }; export default TodoList; I keep getting: Type '({ items, children }: PropsWithChildren) => Element[]' is not assignable to type 'FunctionComponent'. Type 'Element[]' is missing the following properties from type 'ReactElement ReactElement Component)> | null) | (new (props: any) => Component)>': type, props, key A: The issue is that you are trying to return an array of elements in your JSX. In React, you can only return a single parent element which then needs to wrap the rest of your elements. So try changing return items.map((item: Item) => <div key={item.id}>{item.id}</div>); to return ( <div> {items.map((item: Item) => <div key={item.id}>{item.id}</div>)} </div> ) If you would prefer not to have the extra div, you can also wrap your list items with a Fragment. In that case, you would do: return ( <React.Fragment> {items.map((item: Item) => <div key={item.id}>{item.id}</div>)} </React.Fragment> )
{ "pile_set_name": "StackExchange" }
Q: What can Pygame do in terms of graphics that wxPython can't? I want to develop a very simple 2D game in Python. Pygame is the most popular library for game development in Python, but I'm already quite familiar with wxPython and feel comfortable using it. I've even written a Tetris clone in it, and it was pretty smooth. I wonder, what does Pygame offer in terms of graphics (leaving sound aside, for a moment) that wxPython can't do ? Is it somehow simpler/faster to do graphics in Pygame than in wxPython ? Is it even more cross-platform ? It looks like I'm missing something here, but I don't know what. A: Well, in theory there is nothing you can do with Pygame that you can't with wxPython. The point is not what but how. In my opinion, it's easier to write a game with PyGame becasue: It's faster. Pygame is based on SDL which is a C library specifically designed for games, it has been developed with speed in mind. When you develop games, you need speed. Is a game library, not a general purpose canvas, It has classes and functions useful for sprites, transformations, input handling, drawing, collision detection. It also implements algorithms and techniques often used in games like dirty rectangles, page flipping, etc. There are thousands of games and examples made with it. It will be easier for you to discover how to do any trick. There are a lot of libraries with effects and utilities you could reuse. You want an isometric game, there is a library, you want a physics engine, there is a library, you what some cool visual effect, there is a library. PyWeek. :) This is to make the development of your game even funnier! For some very simple games like Tetris, the difference won't be too much, but if you want to develop a fairly complex game, believe me, you will want something like PyGame. A: wxPython is based on wxWidgets which is a GUI-oriented toolkit. It has the advantage of using the styles and decorations provided by the system it runs on and thus it is very easy to write portable applications that integrate nicely into the look and feel of whatever you're running. You want a checkbox? Use wxCheckBox and wxPython will handle looks and interaction. pyGame, on the other hand, is oriented towards game development and thus brings you closer to the hardware in ways wxPython doesn't (and doesn't need to, since it calls the OS for drawing most of its controls). pyGame has lots of game related stuff like collision detection, fine-grained control of surfaces and layers or flipping display buffers at a time of your choosing. That said, graphics-wise you can probably always find a way to do what you want with both toolkits. However, when speed counts or you wish to implement graphically more taxing game ideas than Tetris, you're probably better off with pyGame. If you want to use lots of GUI elements and don't need the fancy graphics and sound functions, you're better off with wxPython. Portability is not an issue. Both are available for the big three (Linux, OSX, Windows). It's more a question of what kind of special capabilities you need, really.
{ "pile_set_name": "StackExchange" }
Q: Advanced Active Record order by using regex I am trying to query my Order model for all records but I want them ordered in a very specific way. Database is a PostgreSQL database. I want all records that start with NY first, NYN next, then all remaining records follow. I think I'm trying to do something like this: Order.all.order('order_number /^NY/, /^NYN/') An example of data: NY-1111111 NYN-1234567 P-000000 P0000000 SS0232131 NYN16151202 The order I want is: NY-1111111 NYN16151202 NYN-1234567 P0000000 P-000000 SS0232131 A: Here's one way you might do this in SQL: SELECT * FROM orders ORDER BY CASE WHEN order_number LIKE 'NYN%' THEN 1 WHEN order_number LIKE 'NY%' THEN 0 ELSE 2 END, order_number; This can be translated pretty directly to an ActiveRecord query: Order.order(" CASE WHEN order_number LIKE 'NYN%' THEN 1 WHEN order_number LIKE 'NY%' THEN 0 ELSE 2 END, order_number ") Here's another possibility using PostgreSQL's POSIX regular expressions. I'm not sure how it compares to the above in performance: Order.order(" CASE SUBSTRING(order_number FROM '^NYN?') WHEN 'NY' THEN 0 WHEN 'NYN' THEN 1 ELSE 2 END, order_number ")
{ "pile_set_name": "StackExchange" }
Q: Uniform Circular LBP face recognition implementation I am trying to implement a basic face recognition system using Uniform Circular LBP (8 Points in 1 unit radius neighborhood). I am taking an image, re-sizing it to 200 x 200 pixels and then splitting the image in 8x8 little images. I then compute the histogram for each little image and get a list of histograms. To compare 2 images, I compute chi-squared distance between the corresponding histograms and generate a score. Here's my Uniform LBP implementation: import numpy as np import math uniform = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 58, 6: 5, 7: 6, 8: 7, 9: 58, 10: 58, 11: 58, 12: 8, 13: 58, 14: 9, 15: 10, 16: 11, 17: 58, 18: 58, 19: 58, 20: 58, 21: 58, 22: 58, 23: 58, 24: 12, 25: 58, 26: 58, 27: 58, 28: 13, 29: 58, 30: 14, 31: 15, 32: 16, 33: 58, 34: 58, 35: 58, 36: 58, 37: 58, 38: 58, 39: 58, 40: 58, 41: 58, 42: 58, 43: 58, 44: 58, 45: 58, 46: 58, 47: 58, 48: 17, 49: 58, 50: 58, 51: 58, 52: 58, 53: 58, 54: 58, 55: 58, 56: 18, 57: 58, 58: 58, 59: 58, 60: 19, 61: 58, 62: 20, 63: 21, 64: 22, 65: 58, 66: 58, 67: 58, 68: 58, 69: 58, 70: 58, 71: 58, 72: 58, 73: 58, 74: 58, 75: 58, 76: 58, 77: 58, 78: 58, 79: 58, 80: 58, 81: 58, 82: 58, 83: 58, 84: 58, 85: 58, 86: 58, 87: 58, 88: 58, 89: 58, 90: 58, 91: 58, 92: 58, 93: 58, 94: 58, 95: 58, 96: 23, 97: 58, 98: 58, 99: 58, 100: 58, 101: 58, 102: 58, 103: 58, 104: 58, 105: 58, 106: 58, 107: 58, 108: 58, 109: 58, 110: 58, 111: 58, 112: 24, 113: 58, 114: 58, 115: 58, 116: 58, 117: 58, 118: 58, 119: 58, 120: 25, 121: 58, 122: 58, 123: 58, 124: 26, 125: 58, 126: 27, 127: 28, 128: 29, 129: 30, 130: 58, 131: 31, 132: 58, 133: 58, 134: 58, 135: 32, 136: 58, 137: 58, 138: 58, 139: 58, 140: 58, 141: 58, 142: 58, 143: 33, 144: 58, 145: 58, 146: 58, 147: 58, 148: 58, 149: 58, 150: 58, 151: 58, 152: 58, 153: 58, 154: 58, 155: 58, 156: 58, 157: 58, 158: 58, 159: 34, 160: 58, 161: 58, 162: 58, 163: 58, 164: 58, 165: 58, 166: 58, 167: 58, 168: 58, 169: 58, 170: 58, 171: 58, 172: 58, 173: 58, 174: 58, 175: 58, 176: 58, 177: 58, 178: 58, 179: 58, 180: 58, 181: 58, 182: 58, 183: 58, 184: 58, 185: 58, 186: 58, 187: 58, 188: 58, 189: 58, 190: 58, 191: 35, 192: 36, 193: 37, 194: 58, 195: 38, 196: 58, 197: 58, 198: 58, 199: 39, 200: 58, 201: 58, 202: 58, 203: 58, 204: 58, 205: 58, 206: 58, 207: 40, 208: 58, 209: 58, 210: 58, 211: 58, 212: 58, 213: 58, 214: 58, 215: 58, 216: 58, 217: 58, 218: 58, 219: 58, 220: 58, 221: 58, 222: 58, 223: 41, 224: 42, 225: 43, 226: 58, 227: 44, 228: 58, 229: 58, 230: 58, 231: 45, 232: 58, 233: 58, 234: 58, 235: 58, 236: 58, 237: 58, 238: 58, 239: 46, 240: 47, 241: 48, 242: 58, 243: 49, 244: 58, 245: 58, 246: 58, 247: 50, 248: 51, 249: 52, 250: 58, 251: 53, 252: 54, 253: 55, 254: 56, 255: 57} def bilinear_interpolation(i, j, y, x, img): fy, fx = int(y), int(x) cy, cx = math.ceil(y), math.ceil(x) # calculate the fractional parts ty = y - fy tx = x - fx w1 = (1 - tx) * (1 - ty) w2 = tx * (1 - ty) w3 = (1 - tx) * ty w4 = tx * ty return w1 * img[i + fy, j + fx] + w2 * img[i + fy, j + cx] + \ w3 * img[i + cy, j + fx] + w4 * img[i + cy, j + cx] def thresholded(center, pixels): out = [] for a in pixels: if a > center: out.append(1) else: out.append(0) return out def uniform_circular(img, P, R): ysize, xsize = img.shape transformed_img = np.zeros((ysize - 2 * R,xsize - 2 * R), dtype=np.uint8) for y in range(R, len(img) - R): for x in range(R, len(img[0]) - R): center = img[y,x] pixels = [] for point in range(0, P): r = R * math.cos(2 * math.pi * point / P) c = R * math.sin(2 * math.pi * point / P) pixels.append(bilinear_interpolation(y, x, r, c, img)) values = thresholded(center, pixels) res = 0 for a in range(0, P): res += values[a] << a transformed_img.itemset((y - R,x - R), uniform[res]) transformed_img = transformed_img[R:-R,R:-R] return transformed_img I did an experiment on AT&T database taking 2 gallery images and 8 probe images per subject. The ROC for the experiment came out to be: In the above ROC, x axis denotes the false accept rate and the y axis denotes the genuine accept rate. The accuracy seems to be poor according to Uniform LBP standards. I am sure there is something wrong with my implementation. It would great if someone could help me with it. Thanks for reading. EDIT: I think I made a mistake in the above code. I am going clockwise while the paper on LBP suggest that I should go anticlockwise while assigning weights. The line: c = R * math.sin(2 * math.pi * point / P) should be c = -R * math.sin(2 * math.pi * point / P). Results after the edit are even worse. This suggests something is way wrong with my code. I guess the way I am choosing the coordinates for interpolation is messed up. Edit: next I tried to replicate @bytefish's code here and used the uniform hashmap to make the implementation Uniform Circular LBP. def uniform_circular(img, P, R): ysize, xsize = img.shape transformed_img = np.zeros((ysize - 2 * R,xsize - 2 * R), dtype=np.uint8) for point in range(0, P): x = R * math.cos(2 * math.pi * point / P) y = -R * math.sin(2 * math.pi * point / P) fy, fx = int(y), int(x) cy, cx = math.ceil(y), math.ceil(x) # calculate the fractional parts ty = y - fy tx = x - fx w1 = (1 - tx) * (1 - ty) w2 = tx * (1 - ty) w3 = (1 - tx) * ty w4 = tx * ty for i in range(R, ysize - R): for j in range(R, xsize - R): t = w1 * img[i + fy, j + fx] + w2 * img[i + fy, j + cx] + \ w3 * img[i + cy, j + fx] + w4 * img[i + cy, j + cx] center = img[i,j] pixels = [] res = 0 transformed_img[i - R,j - R] += (t > center) << point for i in range(R, ysize - R): for j in range(R, xsize - R): transformed_img[i - R,j - R] = uniform[transformed_img[i - R,j - R]] Here's the ROC for the same: I tried to implement the same code in C++. Here is the code: #include <stdio.h> #include <stdlib.h> #include <opencv2/opencv.hpp> using namespace cv; int* uniform_circular_LBP_histogram(Mat& src) { int i, j; int radius = 1; int neighbours = 8; Size size = src.size(); int *hist_array = (int *)calloc(59,sizeof(int)); int uniform[] = {0,1,2,3,4,58,5,6,7,58,58,58,8,58,9,10,11,58,58,58,58,58,58,58,12,58,58,58,13,58,14,15,16,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,17,58,58,58,58,58,58,58,18,58,58,58,19,58,20,21,22,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,23,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,24,58,58,58,58,58,58,58,25,58,58,58,26,58,27,28,29,30,58,31,58,58,58,32,58,58,58,58,58,58,58,33,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,34,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,35,36,37,58,38,58,58,58,39,58,58,58,58,58,58,58,40,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,41,42,43,58,44,58,58,58,45,58,58,58,58,58,58,58,46,47,48,58,49,58,58,58,50,51,52,58,53,54,55,56,57}; Mat dst = Mat::zeros(size.height - 2 * radius, size.width - 2 * radius, CV_8UC1); for (int n = 0; n < neighbours; n++) { float x = static_cast<float>(radius) * cos(2.0 * M_PI * n / static_cast<float>(neighbours)); float y = static_cast<float>(radius) * -sin(2.0 * M_PI * n / static_cast<float>(neighbours)); int fx = static_cast<int>(floor(x)); int fy = static_cast<int>(floor(y)); int cx = static_cast<int>(ceil(x)); int cy = static_cast<int>(ceil(x)); float ty = y - fy; float tx = y - fx; float w1 = (1 - tx) * (1 - ty); float w2 = tx * (1 - ty); float w3 = (1 - tx) * ty; float w4 = 1 - w1 - w2 - w3; for (i = 0; i < 59; i++) { hist_array[i] = 0; } for (i = radius; i < size.height - radius; i++) { for (j = radius; j < size.width - radius; j++) { float t = w1 * src.at<uchar>(i + fy, j + fx) + \ w2 * src.at<uchar>(i + fy, j + cx) + \ w3 * src.at<uchar>(i + cy, j + fx) + \ w4 * src.at<uchar>(i + cy, j + cx); dst.at<uchar>(i - radius, j - radius) += ((t > src.at<uchar>(i,j)) && \ (abs(t - src.at<uchar>(i,j)) > std::numeric_limits<float>::epsilon())) << n; } } } for (i = radius; i < size.height - radius; i++) { for (j = radius; j < size.width - radius; j++) { int val = uniform[dst.at<uchar>(i - radius, j - radius)]; dst.at<uchar>(i - radius, j - radius) = val; hist_array[val] += 1; } } return hist_array; } int main( int argc, char** argv ) { Mat src; int i,j; src = imread( argv[1], 0 ); if( argc != 2 || !src.data ) { printf( "No image data \n" ); return -1; } const int width = 200; const int height = 200; Size size = src.size(); Size new_size = Size(); new_size.height = 200; new_size.width = 200; Mat resized_src; resize(src, resized_src, new_size, 0, 0, INTER_CUBIC); int count = 1; for (i = 0; i <= width - 8; i += 25) { for (j = 0; j <= height - 8; j += 25) { Mat new_mat = resized_src.rowRange(i, i + 25).colRange(j, j + 25); int *hist = uniform_circular_LBP_histogram(new_mat); int z; for (z = 0; z < 58; z++) { std::cout << hist[z] << ","; } std::cout << hist[z] << "\n"; count += 1; } } return 0; } ROC for the same: I also did a rank based experiment. And got this CMC curve. Some details about the CMC curve: X axis represents ranks. (1-10) and Y axis represents the accuracy (0-1). So, I got a 80%+ Rank1 accuracy. A: I don't know about python but most probably your code is broken. My advice is, follow these 2 links, and try to port one of the C++ codes to python. First link also contains some information about LBP. http://www.bytefish.de/blog/local_binary_patterns/ https://github.com/berak/uniform-lbp And one other thing I can say, you said you are resizing images into 200x200. Why are you doing that? As far as I know AT&T images are smaller than that, your are just making images bigger but I don't think it is going to help you, moreover it may have a negative effect in performance.
{ "pile_set_name": "StackExchange" }
Q: Getting XML / HTML test results for android gradle junit test run I'm having a hard time finding xml / html test results after running my tests through gradle either with ./gradlew test or ./gradlew testDebug. When I run either of those I wind up with an html file that shows 0 tests and no xml file at all. According to the android docs XML test results should be in path_to_your_project/module_name/build/test-results/ but the test-results folder only has .bin files in it (results.bin, etc). I also tried searching with find app/build -type f -name "*.xml" but only found Android related XML files (manifest, merge files, etc). Output from ./gradlew --version ------------------------------------------------------------ Gradle 5.1.1 ------------------------------------------------------------ Build time: 2019-01-10 23:05:02 UTC Revision: 3c9abb645fb83932c44e8610642393ad62116807 Kotlin DSL: 1.1.1 Kotlin: 1.3.11 Groovy: 2.5.4 Ant: Apache Ant(TM) version 1.9.13 compiled on July 10 2018 JVM: 1.8.0_212 (Oracle Corporation 25.212-b03) OS: Linux 4.15.0-50-generic amd64 I want to get test results to publish to jenkins. I have the same issue if I run on my local MBP as well. I have not modified any of the gradle test configurations but the link above seems to suggest I shouldn't need to. I also tried specifying my test directory with android { ... sourceSets { androidTest { java.srcDirs = ['src/test/java'] } } } A: Turns out I was missing this from my /app/build.gradle android { ... testOptions { unitTests.all { useJUnitPlatform() } } } This guide helped me figure that out
{ "pile_set_name": "StackExchange" }
Q: Project Euler problem 67 not quite correct I have the following Python code, which I wrote for the sister problem 18. It works perfectly for problem 18, but is slightly out for problem 67. I can't for the life of me figure out why. triangle = [ [59], [73, 41], [52, 40, 9], [26, 53, 6, 34], [10, 51, 87, 86, 81], [61, 95, 66, 57, 25, 68], ... ] def max_adjacent(row,col): return max(triangle[row][col]+triangle[(row+1)][col], triangle[row][col]+triangle[(row+1)][(col+1)]) if __name__ == '__main__': row = len(triangle)-2 while row >= 0: triangle[row] = [max_adjacent(row,triangle[row].index(i)) for i in triangle[row]] row -= 1 print(triangle[0][0]) The algorithm is to start on the last-but-one row, and replace each number in this row with itself plus the largest adjacent number on the row below. (e.g., in the triangle partly defined above, 10 in the last but one row would be replaced with 105.) It simply loops this until it's at row 0 at the top of the triangle, and prints out the first element of this row, which is now the maximum sum. This gives the answer of 7220, which I know to be close but wrong. I wonder why it works for problem 18 though? Can anyone see what I'm assuming or doing wrong? A: The problem might be that you're using the index function. If you have a number twice in a row, index will always give you the index of the number's first occurrence. I guess Problem 18 has no duplicates within one row, the current problem has.
{ "pile_set_name": "StackExchange" }
Q: Can I use the phrase, “open and shut” for other subjects than legal cases? There was the following passage in New York Times (April 28) under the title, “In Baltimore, we’re all Freddie Gray.”: “We’ve watched as Mayor Stephanie Rawlings-Blake, in conjunction with Police Commissioner Anthony W. Batts, spent over a week investigating what appears to be an open-and-shut case. I’d like to think that if I broke a person’s neck for no reason, I’d be charged in minutes. But the system — even when it’s run by a black mayor and a majority of the City Council is black — protects the police, no matter how blatant and brutal they are. As I am unfamiliar with the expression,“open and shut,” I searched the meaning on Google, and found the following definition by the Free Dictionary among several sources: Open and shut - If a legal case or problem is open and shut, the facts are very clear and it is easy to make a decision or find a solution Is the usage of idiom, “open and shut” limited to legal matters? If it came from the instantaneous action of opening and shutting something like a box or drawer, why can’t we use it on anything, questions (e.g. simple calculation) or problems that are manifest or easy to solve other than legal cases? A: An expression generally , but not exclusively, used referring to legal matters : Open-and-shut case: a legal case or other matter that is easy to decide or solve. (Oxford Learner's) Open-and-shut case a simple and straightforward situation without complications. (Often said of criminal cases where the evidence is convincing.) The murder trial was an open-and-shut case. The defendant was caught with the murder weapon. Bob's death was an open-and-shut case of suicide. He left a suicide note. The Free Dictionary Chevrolet presents an open-and-shut case against the van you are using. ( From LIFE 12 giu 1970) An open and shut case?: Title of an article with political content. An Open-and-Shut Case? Recent Insights into the Activation of EGF/ErbB Receptors . A scientific/medical extract.
{ "pile_set_name": "StackExchange" }
Q: How to get the gradient color from top right to bottom left corner I have trying to get the css gradient as like in the below bootstrap icon. I just want two solutions from this code. 1.)How to make gradient color as like in icon(From top right to bottom left)? 2.)Vertical alignment of text within div(Possibility without using flex property) Thanks in advance :) div{ width:100px; height:100px; background: -webkit-linear-gradient(left, #2F2727, #1a82f7); border-radius:4px; } div p{ color:white; text-align:center; text-transform:uppercase; font-weight:bold; font-size:42px; } <div> <p> b </p> </div> A: Use to top right keyword for directing gradient to move from bottom left corner to top right corner. background: linear-gradient(to top right, #2F2727, #1a82f7); Use line-height equal to height. More Information about css gradient is here. div{ width:100px; height:100px; background: linear-gradient(to top right, #2F2727, #1a82f7); border-radius:4px; } div p{ color:white; text-align:center; text-transform:uppercase; font-weight:bold; font-size:42px; line-height: 100px; } <div> <p> b </p> </div>
{ "pile_set_name": "StackExchange" }
Q: Rails server console output very noisy, can it be turned off? On some of my rails application pages I am seeing reams and reams of information echoed out to the console, messages that I am not interested in such as http messages: Started GET "/assets/jquery_ui/jquery-ui-1.8.16.custom.css?body=1" for 10.0.2.2 at 2012-03-02 15:19:59 +0000 Served asset /jquery_ui/jquery-ui-1.8.16.custom.css - 304 Not Modified (0ms) There is also lots of SQL statements that I don't normally care about. Sure, I can see how sometimes this level of information would be helpful sometimes. But I would like to run my server normally without this noise. The reason for this is because if I am debugging an issue, I like to explicitly log messages to the console, run the request and observe the output. However finding my own logs in amongst this noise is time consuming! Currently to work around this I am marking my messages with a magic string and greping the output to the console... Can anybody suggest a nicer way to reduce the console output to just my own messages? I am on rails 3.1. Thanks for any suggestions. A: You can raise the logging level in config/environments/development.rb from info to warn http://guides.rubyonrails.org/debugging_rails_applications.html#log-levels
{ "pile_set_name": "StackExchange" }
Q: Are photons eternal or do they really cease to exist? I have read this question: Are all electrons identical? Same photon or different photon? What happens when a photon "dies"? But these do not give satisfactory answers. When a photon is absorbed, we usually say that the photon ceases to exist as photon, and transforms into the energy of the absorbing electron/atom system. There is a very good description in this answer from John Rennie: Same photon or different photon? Your question is based on the assumption that a photon is a fundamental object i.e. that photons are something we can point to and say here is photon 1, here is photon 2, and so on. The trouble is that quantum field theory particles are somewhat elusive objects. This is particularly so for particles like photons that are their own antiparticles because such particles can be freely created and destroyed. At least fermions like electrons are protected by conservation of lepton number. In general energy propagating in a quantum field looks like a particle only when energy is being transferred into or out of the field i.e. when a photon is created or destroyed. Outside of these events it's hard to point to anything that looks like a photon. So basically photons are QM objects, excitation of a field, and in certain cases we say that this QM object ceases to exist. So basically there are two cases, partial energy transfer (inelastic scattering), and full transfer (absorption). When a photon is inelastically scattered, it transfers part of its energy to the other field (maybe the electron field), but we do not say that part of the photon ceased to exist. But then this partial energy that was transformed, can again be emitted as a new photon. This is part of the reasons why photon number does not have to be conserved. Only energy is conserved. So the photons are absorbed and disappear when hitting the leaves of the tree. It is energy that is absorbed and conserved and released as photons when burning. Are the photons released by trees the same generated by the sun? Energy is conserved, and eternal. It gets transformed, propagates. Photons carry energy and are the very quanta of light. If energy is eternal, then we could say that photons are too existing eternally, sometimes they get absorbed fully or partially, stored in other fields (like the electron field), then re-emitted. Question: Are photons eternal or do they really cease to exist? A: No, in modern physics we don't think so. Quantum field theory allows the creation and annihilation of particles (e.g. in pair production) so the number of a given particle, e.g. the number of photons, doesn't have to be conserved. Energy does have to be conserved, but it can be transferred to other particles, so photons can be absorbed. We can say that the photon ceases to exist because the electromagnetic field ceases to be excited.
{ "pile_set_name": "StackExchange" }