INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Unresolved reference error while calling add method in Kotlin Set interface If I use a _Set_ interface reference and I try to call _add_ method I get an unresolved reference error: fun main(args : Array<String>) { val set = HashSet<Integer>() set.add(Integer(1)) //OK val seti : Set<Integer> = HashSet<Integer>() seti.add(Integer(2)) //FAILING: Unresolved reference to add** } I don't understand that behaivour. Java _Set_ interface has an _add_ method and I expected Kotlin one to be an extended version and not to had less methods. PD1: I get the same error in Idea IDE or building with gradle. PD2: Using kotlin 1.0.0-beta-4584
Kotlin seperates Java's `Set` interface into two interfaces: `Set` and `MutableSet`. The latter interface declares mutating methods such as the `add` method you're looking for. Generally, interfaces such as `MutableSet` extend the `Set` interface, and implementations like `HashSet` implement the `MutableSet` interface. The `Set` interface can then be used to pass around a read-only instance, to help avoid common bugs from happening.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "kotlin" }
How to write this format in string builder in c# my xml file property like this: <Attributes> public function attr($attr, $value) { $this->attributes[$attr] = $value; return $this; } </Attributes> i get from c#![enter image description here]( How to write this function from image function ajaxSettings($value){ return $this -> ajaxSettings = $value; }
To use `StringBuilder`'s `AppendFormat`.aspx), you use the standard string formatting notation.aspx#Starting) to insert one or more values in your string: var sb = new StringBuilder(); var world = "World"; sb.AppendFormat("Hello {0}", world); var helloWorld = sb.ToString(); // returns "Hello World"
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "c#, xml" }
JavaScript Application Storage Best Practices This question is more of a theoretical one, than a programming one. I am currently in the process of writing a single page javascript application with Knockout.js. I choose Knockout because I love the way it handles DOM updates, but it does require you to write your own REST backend for data storage and loading. My application is an enterprise application, where the server and client will be installed on it's own server instance, and not shared with any other users. It does not require authentication, and only will only need to save and load JavaScript objects. My original thought was to use a node.js backend with Mongo for storage, but this seems a little overkill for me. Would it be considered a bad practice to save the raw json as a flat file, and save/load it as needed? The only problem I see is if multiple users were using the application and try to save data at the same time. Is there an easy way to handle a merge of JSON data?
If there are concurrent access to your application that can modify this data I would definitely advise to keep it on the server side. It depends on your application, but merging the JSON will most likely become a nightmare. I believe it will be better to manage concurrent access from the backend. Mongo DB is a good option, but take a look at CouchDB (which provides REST interface) and Redis as well. On the other hand, if concurrency was not an issue, you may want to check HTML5 local storage, which basically lets you store key/value pairs on the client side. It's a great alternative to cookies since it is not sent on each request and allows you to store more data in a cleaner way.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, knockout.js, storage" }
Flex/actionscript 3 equivalents for __FILE__ and __LINE__ I'm quite new to flex/actionscript and I was wondering if there is an equivalent for php's (and other languages) **FILE** and **LINE** identifiers? Basicly I want to do some custom error logging and would like to something like: var mymessage:String = 'Oops, a hiccup occured at ' + __FILE__ + ', line: ' + __LINE__; Where file and line would ofcourse be substituted for their values at compile time. Is this possible?
It's not directly possible, but there's a fairly usable workaround for personal testing var stackTrace:String = new Error().getStackTrace(); if (stackTrace) { var mymessage:String = "Oops, a hiccup occurred " + stackTrace.split("\n")[1]; } Adjust your abuse of `getStackTrace` to taste.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "apache flex, actionscript 3" }
MySQL: Select count of a group with the id of last record Here is my table called `logs`: id package log ==================== 0 first log0 1 first log1 2 second log2 And I want the query result to be like this: package count last_log_id =============================== first 2 1 second 1 2 So far, my searches led me to this: SELECT package, COUNT(*) FROM logs GROUP BY package This helped me getting the count of each group by package. SELECT a1.package, COUNT(*),a1.id FROM logs a1 LEFT JOIN logs a2 ON (a1.package = a2.package AND a1.id < a2.id) WHERE a2.id IS NULL GROUP BY a1.package And this helped me getting the id of the last log, but the count is wrong! package count last_log_id =============================== first 1 1 second 1 2
I think your first attempt is correct, and you may use the `MAX` function to find the latest log `id` for each package: SELECT package, COUNT(*) AS count, MAX(id) AS last_log_id FROM logs GROUP BY package;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql" }
Regex to match alphanumeric -- query rows that contain numbers in postgresql I want to write a regex that matches string that has _both_ numeric **and** alphabets. `^[a-zA-Z0-9]*$` \-- this pattern returns numeric as well as alphabets, but I want only alphanumeric. Basically I'm using postgresql to query rows that contain numericals in it.
I think multiple regex's is the easiest way: where col ~ '^[a-zA-Z0-9]*' and col ~ '[0-9]' and col ~ '[a-zA-Z]' There is probably a complicated regexp that combines this all together, but this seems like the most intuitive method.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "regex, postgresql" }
Memory handling with struct epoll_event I'm developing a server in C with the epoll library and I have a question as to how memory is handled for `struct epoll_event`. I've noticed in some online examples that, when making `epoll_ctl` calls, the `events` argument is allocated on the stack and then the pointer is passed, like so: struct epoll_event ev; ev.events = EPOLLIN; epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &ev); Now we all know what happens to `ev` when the function returns. My question is: does the epoll library make copies of these values internally or does it rely on the struct you passed to be heap allocated? Will the above example totally break my reactor implementation? If so, what is the best way of keeping track of my heap allocated `epoll_event` structs? Thanks for your time.
Everything is fine. The `epoll_ctl` function is a simple wrapper around a system call which will be entirely complete when the function returns. No further data from userspace is required. The struct is simply a way to package the arguments.
stackexchange-stackoverflow
{ "answer_score": 20, "question_score": 20, "tags": "c, linux, epoll" }
How do I get rid of the ".html" in the url of my webpages? For example, on my contact page, the url reads: websitename/contact.html. If possible, I'd like to change the website path to websitename/contact.
You need to add this on your .htaccess file #mode_rerwrite start here RewriteEngine On # does not apply to existing directores, meaning that if the folder exists on server then don't change anything and don't run the rule. RewriteCond %{REQUEST_FILENAME} !-d #Check for file in directory with .html extension RewriteCond %{REQUEST_FILENAME} !-f #Here we actually show the page that has .html extension RewriteRule ^([^\.]+)$ $1.html [NC, L]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "html, url" }
Is there a way to add tooltip to excel cell data in c# I am generating an excel sheet from multiple databases and wanted at particular column to add "Tooltip" to show, from where the data is being fetched. All I want some property or method to set Tooltip of any excel cell. At the moment I tried : objCopy.Cells[j + Convert.ToInt16(StartRow["StartRow"]), 4].Tooltip = "From First Table"; And objCopy.Cells[j + Convert.ToInt16(StartRow["StartRow"]), 4].setAttribute("title","From SpreadSheet");
No. Excel doesn't have tooltips. The only thing that comes close are comments. The `Range.AddComment` is what you need for that.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "c#, .net, excel" }
HTML5 Video player using Laravel I want to create a video player using HTML in Laravel I use below code its work fine for some video $link = 'uploads/'.$video->link; <video width="720" height="540" controls preload="auto"> <source src="{{URL::asset($link)}}" type="video/{{$video->extention }}"> </video> but probelm is in my database **link** column data is like:- ' ** _Natural animal hd video.mp4_** ' In this case its fail
$link = 'public/uploads/'.$video->link; add
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "laravel, html5 video, laravel 5.6" }
How to get motivated when drained I know many work in where they enjoy but lately after spending all day at work I get home and all my thoughts and ideas for my freelance projects all day become annoying after I am drained and exhausted. So how do you: * manage your energy with your work and freelance? * not burn yourself in your field? * balance your time with work and freelance? * Stay inspired to complete what you've been working on? I know I tend to bounce around on projects because I believe in managing my time when I get into a design block. However, is this method bad? Should I stick to one project until completion even when battling a hurtle? I have read many articles on this but nothing seems to motivate me. If it helps someone else: * How to Recharge and Get Motivated * How You Can Get Motivated To Reach Your Goals * How to Beat Designer’s Block Like a Kung Fu Master * 20 ways to beat the creative block * 5 simple ways to beat designer’s block
Besides the energy drink or taking a quick walk, I usually do one of 3 things when tired or burned out: 1. Switch to a quick easy task. Completing something small is quick and fulfilling. The productivity/accomplishment helps build momentum. 2. Take a break by reading an article or checking out a forum, write a quick post/answer (just like this one - I'm a little burned out at the moment...). 3. When all else fails, switch to a pet project that you are more excited about. By having a few projects at a time it helps give you the flexibility when you really couldn't be stuffed working on something. You need to be disciplined though not to keep pushing all the undesirable projects back though (something I do too often). On the other hand, when I've got a crunch/challenge to complete one project, usually the challenge itself is motivating enough.
stackexchange-graphicdesign
{ "answer_score": 3, "question_score": 6, "tags": "workflow, designers" }
Problem in unable to validate spinner must be click Adapter.class holder.txt_AddToCart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String product_image = brandWiseProductArrayList.get(position).getProductImgPath(); int qty = Integer.parseInt(holder.edtxt_integer_number.getText().toString()); } }); Here, When I am click this button must be asked to select `spinner` Is there any way to validate spinner or put "select something" in the first position of a spinner which is filled by `objArraylist` ProductSpinnerAdapter productSpinnerAdapter = new ProductSpinnerAdapter(context, brandWiseProductArrayList.get(position).getProductDetailsArrayList()); holder.spinner_product_details.setAdapter(productSpinnerAdapter);
Try this String product_image = brandWiseProductArrayList.get(holder.spinner.getSelectedItemPosition()).getProductImgPath(); change **holder.spinner** to respective spinner variable. Let me know if this works
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android" }
How to print multi-dimensional hash in different format I have a hash as follows: h={1=>{'a'=>3,'b'=>2,'c'=>3},2=>{'a'=>2,'b'=>1,'c'=>3},3=>{'a'=>2,'b'=>1,'c'=>3}} I want to print it as follows: inner key outer key values 'a' 1 3 'a' 2 2 'a' 3 2 Same for `b` and `c`. Please guide me.
puts "inner key outer key values" h.flat_map{|o, h| h.map{|i, v| [i, o, v]}}.sort .each{|i, o, v| puts "'#{i}' #{o} #{v}"}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "ruby, hash" }
creating 2d sprites for games? i am pretty new to developing games...i thought i would begin by making a simple 2d game.... curious what tools are commonly used to transform images to pixel sprites ? or is this done by hand, if so what tools are used ? even better, is there a marketplace where i can purchase game sprites and other game assets ?
Sprites are usually of fixed size, 8x8, 16x16, 32x32, etc., although of course some platforms may allow arbitrary sizes too. Sprites are images, I'm not sure what the transform is that you'd be asking about; you've got to load some data and pass that data to your "sprite renderer," so at some point you'll need to get the input data into the engine format, but that'll depend on the engine. Many engines can "natively" take jpegs and pngs and do the transform for you. I don't know of any marketplaces in particular, but you could post on craigslist or something, looking for an artist to create these assets.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "assets" }
Show/Hide Custom Button for Admin/Standard Users with Professional Edition I have button 'Sync Account to TRAVERSE' that syncs salesforce account to Traverse ERP. I want this button only visible for Admin Users not standard and other users. I am facing difficulty to make page layout and assign to profile. As I am using PE I am unable to do that. Is there any other way to do this in PE? Thanks!!
You can buy custom profiles and layouts a la carte, if you wanted. That's the only "secure" way to do it, as anything less can be circumvented by an advanced user (a.k.a "hacker", in the classic computer lingo sense, not the media-hyped cyber criminal sense). If you're only concerned about stopping causal users, some simple JavaScript in the custom button could discourage them. Something like: If({!$Profile.Name<>"System Administrator"}) { alert("I'm afraid I can't do that, {!$User.FirstName}."); } else { // do your magic }
stackexchange-salesforce
{ "answer_score": 2, "question_score": 3, "tags": "limits, professional edition" }
Why Android Studio can't find resource? I followed this tutorial: < And I have problem with png image: ![enter image description here](
1. chnage `tools:context="com.test.ocr.ocrtest.MainAcivity"` 2. remove / from `android:src="@drawable/test_image"`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, android studio, sdk, resources" }
Can I safely include "self-defined" HTML Tags in a HTML Website? I have seen a website that has a doctype of <!DOCTYPE html> This website uses HTML Tags that I have never seen before like `<section>`. My Question: 1.) Is this kind of "generic Doctype" recommended for a normal website? (I've never seen this this before, what are the pro and cons?) 2.) When is it valid to use such "self defined" HTML Tags? Is this valid with this doctype Declaration?
This is the doctype for HTML 5. 1. You are safe to use this Doctype as it won't break older browsers and modern browsers will understand it. 2. This is a valid tag for HTML 5. If you really want custom tags, you'd need to create a custom doctype for your document to reference, but that's discouraged.
stackexchange-webmasters
{ "answer_score": 8, "question_score": 3, "tags": "html, tags" }
Code libraries/applications in C# I am refreshing my memory on C# (first used it several years ago), and I want to look at some real world quality code (rather than the simplistic ones used in many books). My preference would be mathematical/statistics libraries written in C# as I would like to see how Matrices and PDEs (partial differential equations etc) are implemented in C#. Can anyone recommend a good quality online resource where I can view some 'industrial grade' preferably (Math/Stats) library/application written in C#?
Math .NET may be will be interesting for you.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, math, statistics, matrix" }
Is it acceptable to join a bug report to a job application? I'm writing an job application email to a smallish software company as a junior back-end developer, while researching the company I stumbled upon a front-end bug,nothing website breaking. I don't know if the manager/senior developer will take that post scriptum as a show off or as a helpful tip?
> I don't know if the manager/senior dev will take that post scriptum as a show off or as a helpful tip? I think that you should **refrain from saying so** , at least for now. Currently, you are not hired by them (although you may be in the future), so it is not your responsibility yet to evaluate their website. Mentioning such thing may come as a bit arrogant or they may not take that feedback too happily, and is clearly out of focus for the application process; these things can affect your application in a negative way. If/when you get hired, then you can mention such things without problem.
stackexchange-workplace
{ "answer_score": 5, "question_score": 1, "tags": "software industry, job search, applications" }
Easy Reflection question C# I want to supply unknown "object" and return the value of one of its members. Response is required in C#. Generically I guess I'm looking for the code to this method public static object GetObjectMemberValue (object myObject, string memberName) More specifically I'm doing this for resource strings in Silverlight and need to write this method. It resides in a common project is used against a few different Resx dictionaries, thus I don't have access to the type information. public static string GetString (object StringResources, string ResourceId) Thank you!
This will get your value... Can you give me more info in the resx part of the question? public static object GetObjectMemberValue(object myObject, string memberName) { PropertyInfo dateProperty = myObject.GetType().GetProperty(memberName); return dateProperty.GetValue(myObject, null); }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c#, .net, reflection" }
Spanning lists of the "right length" are a basis for arbitrary $R$-modules I am familiar with the statement: A spanning list of the "right length" in a finite dimensional vector space $V$ is a basis. I am wondering if this is also true for arbitrary free $R$-modules of finite rank. I am not sure because the proof that I have read on this in vector spaces does rely on a lemma that uses the hypothesis that the ring of scalars is a field. Thanks
This is true over commutative rings. See Surjective endomorphisms of finitely generated modules are isomorphisms (a spanning list for $R^n$ of length $n$ gives a surjective homomorphism $R^n\to R^n$, which then must be an isomorphism and therefore the list is a basis). It is not true for arbitrary rings. For instance, if $R$ is the ring of endomorphisms of an infinite-dimensional vector space $V$, then $R\cong R^2$ as an $R$-module (using an isomorphism $V\cong V^2$). So, $R^2$ can be generated by a single element $x$, and then for any $y\in R^2$, $(x,y)$ is a spanning list that is not a basis. In general, a ring for which this property holds is called _stably finite_. See this answer for some discussion and related conditions.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "linear algebra, abstract algebra, modules" }
Dropdown List bingding of State and City through database I have created two tables for States and City respectively. Is there any easy way of binding the state table in a dropdown list and on selecting the state I should get the respective city on the next(city) dropdown. I have Already given StateID to the City Table for reference.
You could try something like this: dropdownlistID.DataSource = table; dropdownlistID.DataValueField = "ValueColumnName"; dropdownlistID.DataTextField = "TextColumnName"; dropdownlistID.DataBind(); where `dropdowlistID` is your dropdownlist's control ID and `table` is the table of states or cities.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, asp.net, .net" }
How Go streaming read from request a.body to a newrequest‘s body Now, i do something like this with Golang: //read all bytes from body bytes, err := ioutil.ReadAll(request.Body) //set the bytes as NewReader to new request.body request, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(bytes)) but i want to streaming read from original body(io.Reader) to the new, instead of read all bytes to memory by ReadAlland then copy to NewRequest. How can i implement this? thx.
Check the `io` package if you want specialized reader - writer handling, the Pipe or Tee structs might be useful. In this case, though, `request, err := http.NewRequest(http.MethodPut, url, request.Body)` should actually just work fine.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "http, go" }
jqGridmin.js produce error in FF when doing quick switching between grids When I'm attempting to switch between filters and loading up different jqGrids in succession, I sometimes get this error in FF: i.p is undefined (line 108), which is this line: j.p.lastsort=b.inArray(j.p.lastsort,f);if(j.p.treeGrid)j.p.expColInd=b.inArray(j.p.expColInd,f)},setGridWidth:function(f,k){return this.each(function(){var i=this,h,g=0,j=i.p.cellLayout,m,a=0,q=false,t=i.p.scrollOffset,x,C=0,K=0,J=0,F;if(i.grid){if(typeof k!="boolean")k=i.p.shrinkToFit;if(!isNaN(f)){f=parseInt(f,10);i.grid.width=i.p.width=f;b("#gbox_"+i.p.id).css("width",f+"px");b("#gview_"+i.p.id).css("width",f+"px");b(i.grid.bDiv).css("width",f+"px");b(i.grid.hDiv).css("width",f+"px");i.p.pager&& Any clues on how to avoid this? It is a difficult to replicate bug cos I really have to switch quickly between the filters to sometimes get this error.
Found the problem which was a function that was called on grid complete to setGridWidth. Somehow even though the grid was 'complete', the setGridWidth couldn't get the grid to adjust .. maybe because of the delay it takes for the grid to render after ajax complete/success. A bit of background: I use the jqGrid set width function after grid complete to determine whether horizontal scrollers are needed. (A lot of customisation there...)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, jqgrid" }
Keyboard shortcut for code folding in Xcode 9 Code folding doesn't work with key binding **Shift + Alt + Cmd + <\- left** in **Xcode 9**. Is anyone having same problem with Xcode 9?
Code folding is one a long list of things that isn't implemented in the new editor yet. **UPD:** Now after release of Xcode 9 code folding works now with former shortcut ( Shift + Alt + Cmd + left arrow) **Note:** For only folding the scope you are in, press Alt + Cmd + left arrow.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 8, "tags": "keyboard shortcuts, xcode9 beta, code folding" }
Why is my Selenium selector pulling a dict? (Django/Python 3.8) I've just updated selenium in my django app on PythonAnywhere. This is my code: from selenium import webdriver def Synonym(): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") browser = webdriver.Chrome(options=chrome_options) browser.get(" test = browser.find_element_by_class_name("logo").text browser.quit() return test But it gives me an error: **AttributeError: 'dict' object has no attribute 'text'** When I grab it without the .text this is what it gives me: {'ELEMENT': '0.3567871003333163-1'} I'm using a paid account and should be able to access any site. Sidenote: is there a way to stop selenium from making /tmp/ files and folders? Thanks!
The fix for me on PythonAnywhere was to update the system image: < Answer courtesy of caseneuve!
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, django, selenium, dictionary, selector" }
map to XF86 keys in vimrc I have a chromebook that I've modified to run Arch Linux on. I have a 'search' key just under the tab key that I'd like to map as autocomplete when in `insert` mode. `xev` tells me the value of the key is `XF86Search`. However this doesn't seem to be working: #.vimrc inoremap <XF86Search> <c-n> mapmode-i$ How can I make this mapping with an XF86 key? **edit** : In fact, using AutoComplPop from this answer proved to be a better solution, but Ingo pointed me in the right direction. This question on superuser discusses remapping keys for vim and/or terminal using `xmodmap` and that's the way I would have had to go.
In insert or command-line mode, try typing the search key (maybe preceded by `<C-V>` for literal input). If nothing happens / is inserted, you cannot use that key combination directly in Vim. You would have to remap it outside to some unused key (e.g. `<F13>`) that is supported by Vim. Else, just insert the key literally into your `.vimrc` mapping definition, without the special `<...>` key notation.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "vim" }
JavaScript Sliding Billboard (No Flash) I need to create a sliding billboard ad (just like the one on this website < I would prefer to use jQuery over Flash, for reasons I'm sure most understand. I've been Googling and haven't found a solution. In the end this will be thrown into Google Ad Manager to track click throughs. Any help would be greatly appreciated! Note: This will go at the top of the site above all content.
This is easily implemented in jQuery Look here < apply a few styles, hover effect.. and 'tadaaa' no flash or UI.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, jquery, ads, slidedown, google ad manager" }
Selecting trailing empty nodes using xpath How do I select trailing empty nodes? Empty, as in no text, that is. In this example I want to ignore the first empty node, as it is not trailing, The last three nodes (under `<bar>`) have no text so I want to select them. <foo> <bar> <node>blah blah</node> <node></node> <-- Not this <node>blah blah</node> <node>blah blah</node> <node></node> <-- But this <node><node></node></node> <-- and this </bar> </foo>
If you use `/foo/bar/node[not(normalize-space()) and not(following-sibling::node[normalize-space()])]` you select the two `node` child elements that don't have any following sibling with text content. The second of those `node` elements contains a further `node` child, I am not sure whether you want to select that as well as part of the result.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "xslt, xpath" }
VBA: Debug.Print without newline? For debugging in VBA, I have several `Debug.Print` statements throughout my code. For a line-parsing block, I'd like to print the line, and output any flags **inline** with the line, without having multiple `Debug.Print sFlag & sLine` statements throughout the many if/elseif/else blocks. Is there a way, within VBA, to suppress the newline at the end of a `Debug.Print` statement?
It turns out you can easily do this by simply adding a semicolon to the end of your `Debug.Print` statement. Like so: While oExec.StdOut.AtEndOfStream = False sLine = oExec.StdOut.ReadLine If bInFileSystem Then If AnalyzeFileSystemLine(sLine) = False Then Debug.Print "[FSERR]: "; End If ElseIf bInWASCheck Then If AnalyzeWASLine(sLine) = False Then Debug.Print "[WASERR]: "; End If End If Debug.Print sLine Wend So, some sample output will be: test text things look good! [FSERR]: uh oh this file system is at 90% capacity! some more good looking text :) [WASERR]: oh no an app server is down!
stackexchange-stackoverflow
{ "answer_score": 25, "question_score": 13, "tags": "vba, debugging, newline" }
Not getting any reading from FTDI UMFT201XB USB-to-I2C module I got the FTDI UMFT201XB USB-to-I2C module in order to interface with an I2C peripheral through a USB port on my Windows 7 computer. The VCP drivers seem to install correctly, and a COM port is assigned to the module, and can be opened by a terminal emulator. However, I cannot seem to get any signal in or out of the module. That is, I see no activity when I send data through the port, or receive any data when I connect an I2C device to it (this was debugged using a scope). I have also verified that the RESET isn't on. I found very little helpful information out there on how to get this module to work, so if anyone has experience with it, or with similar FTDI modules, my question is: what are the steps that I need to take in order to get the module to communicate?
The FT201X chip used on this module implements I2C slave mode only -- by default it does not operate as an I2C master. In other words, it is meant to _be_ an I2C peripheral, not communicate with one. In the datasheet, it does state that you can reconfigure the SCL and SDA pins as GPIO, which I suppose would allow you to bit-bang an I2C master implementation in software on the host, but it hardly seems like it would be worth the trouble.
stackexchange-electronics
{ "answer_score": 2, "question_score": 2, "tags": "usb, i2c, ftdi, windows" }
Completely regular-Topology Prove that every metric space is a Tychonoff space. Can somebody please help me to show this space satisfies the completely regular axiom and the $T_1$ axiom.
According to Wikipedia, "$X$ is a Tychonoff space, ... if it is both completely regular and Hausdorff." Every metric space is Hausdorff (but perhaps you might want to show that). And, again according to Wikipedia, "$X$ is a completely regular space if given any closed set $F$ and any point $x$ that does not belong to $F$, then there is a continuous function $f$ from $X$ to the real line $\mathbb R$ such that $f(x)$ is $0$ and, for every $y$ in $F$, $f(y)$ is $1$." Let $F \subset X$ be closed. Let $x_0 \in F^c $. Since $F^c$ is open there is $\varepsilon > 0$ such that $B(x_0, \varepsilon) \subset F^c$. Define $$ f(x) = \begin{cases} \frac{d(x,x_0)}{\varepsilon} & x \in B(x_0, \varepsilon) \\\ 1 & x \in B(x_0, \varepsilon)^c \end{cases}$$ Then $f(x_0) = 0$ and $f\mid_F = 1$. Now show that $f$ is continuous.
stackexchange-math
{ "answer_score": 5, "question_score": 4, "tags": "general topology" }
Reference documentation for cgroups (control groups) settings I'm looking for some reference documentation to explain what each of the settings are, for each control group. For example, there's `cpuset.cpus`, I think setting this to `0` means use all CPUs, setting it to `1` limits you to `1` core. And `cpuset.shares`, how is that configured exactly? Surely there's a reference doc that simply explains each of the settings somewhere right? Anyone have a link?
A big thanks to Red Hat, I finally tracked down the reference documentation I was looking for in their documentation. I expect that there's no difference between Red Hat and other distros on this point. Subsystems and Tunable Parameters | Red Hat Customer Portal
stackexchange-unix
{ "answer_score": 3, "question_score": 4, "tags": "linux, documentation, cgroups, lxc" }
Randomly delete rows with condition R (aka rdeleteIf) I have data frame x: Button TrackNo NextTime 54 G155 2011-04-29 19:20:04 50 H54 2011-04-29 19:25:41 54 G157 2011-04-29 19:47:58 I need to delete say 30% (uniformly) of rows which have `button==54` (i.e.). How am I to do it? I know how to delete with condition, say `a <- x[x[,1]==54,]` And I know how to delete randomly, say `i <- runif(1,length(x)); a <- x[,i]` But how to do it at the same time?
@shadow already answered in the comments with a one liner, but here's a work flow of how you can approach these things in the future. Once you understand this, you'll be writing one liners like @shadow in no time. # generate some fake data (the kind you should provide when asking questions) mydf <- data.frame(button = sample(1:5, 100, replace = TRUE), var1 = runif(100)) find.button.5 <- mydf$button == 5 # find row numbers where button == 5 perc.30 <- round(sum(find.button.5) * 0.3) # find 30% of button 5 button.5 <- which(find.button.5 == TRUE) sampled.30 <- sample(button.5, perc.30) # row numbers of 30% of button 5 mydf[-sampled.30, ] # in your final output, include all but the 30% > nrow(mydf[-sampled.30, ]) [1] 93 Notice that the rows from `sampled.30` are missing in your final output.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "r" }
python interval i've dev code for wifi scanning in python, now i trying to modify my code so it will scan wifi at specific interval, how this can be done thanks
You generally have two solutions: * schedule to run the python script which refreshes WIFI info at various interval, using crontab or similar external device. * keep the [python] program running and use **threading.timer** to schedule calls to the WIFI checking routine at desired intervals.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, intervals" }
Как написать "&" символ в React? ![For example]( Как мне написать этот символ на React?
Используй {} скобки: url={"тут твой url"}
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, reactjs, link" }
SQLite3 explain query plan (raspberry PI) My development os is Linux(raspberry pi). I installed sqlite3 and it is latest version. **explain query plan** returns value for example sqlite> explain query plan select * from test_table 0|0|0|SCAN TABLE test_table (~100000 rows) but my result is : sqlite> explain query plan select * from test_table 0|0|0|SCAN TABLE test_table `(~100000 rows)` is not shown. what is problem? Thanks
The documentation says: > Warning: The data returned by the EXPLAIN QUERY PLAN command is intended for interactive debugging only. The output format may change between SQLite releases. You are using another SQLite release, and the output format indeed changed.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sqlite, raspberry pi" }
How to convert from int to int?, in C#? I have a `int` i want to save as a `int?` Is it possible and if so how?
There's an implicit conversion: int nonNullable = 5; int? nullable = nonNullable; (This is given in section 6.1.4 of the C# specification.) The reverse operation is unsafe, of course, because the nullable value could be null. There's an explicit conversion, or you can use the `Value` property: int? nullable = new int?(5); // Just to be clear :) // These are equivalent int nonNullable1 = (int) nullable; int nonNullable2 = nullable.Value;
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 4, "tags": "c#, nullable" }
What is short litter and how is it made? A book I'm reading on creating hotbeds recommends mixing "short litter" with the fresh manure as the base of the beds. I've also seen websites recommending using grass cuttings or a good short litter as mulch. What materials are short litter in these contexts and is there any preparation required to make them into short litter?
In the context in this book, short litter is a carbonaceous composting material used to slow the heating of the manure in hotbeds. This would include shredded leaves, cut straw, wood chips, old grass clippings, etc.. It can also mean animal bedding mucked out before it it becomes very soiled, especially for chickens.
stackexchange-gardening
{ "answer_score": 3, "question_score": 5, "tags": "compost, mulch, terminology" }
How IP address is informed to linux kernel? On system boot up, dhclient gets the IP address over particular network interface, how is this information(IP address) passed to kernel?
Short answer, using `SIOCSIFADDR` ioctl. More information about user-space program which does that: Set IP address using SIOCSIFADDR ioctl
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "linux, networking, linux kernel, linux device driver" }
Handle repeated options like -v -vv -vvv idiomatically with perl Getopt I'd like to handle the verbosity level option like OpenSSH does: by multiply passing the `-v` option. `Getopt::Std` does not increment no-argument option values, but simply sets them to `1`. This means that passing `-vvv` with Getopt::Std will yield `$opt_v == 1` and I need it to be `3` in that case. `Getopt::Long` with the `v+` option-spec understands `-v -v` correctly (target variable ends up `2`), but it misunderstands `-vvv` as the option named `vvv` \-- which is not defined and causes an error. How can I get the desired behavior?
I figured out the answer after writing up the question, but before posting it -- classic. * * * The best way to handle this is to use `Getopt::Long` with `bundling`: use Getopt::Long qw(:config bundling); GetOptions ("v+" => \$verbose); This handles `-v -vv -vvv` as expected: `$verbose == 6`. * * * If for some reason you cannot use or prefer not to use `bundling`, the only other way is to define the options `vv`, `vvv` etc. up to a reasonable maximum: use Getopt::Long; GetOptions ( "v+" => \$verbose); "vv" => sub { $verbose += 2 }, "vvv" => sub { $verbose += 3 }, ); This then also handles `-v -vv -vvv` as expected: `$verbose == 6`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "perl, getopt" }
On OnepageController.php how I can check checkout method is checkout as guest I want to check checkout method of user on OnepageController.php eg if checkout as guest then value will be guest I tried the following: $this->getRequest()->getPost('method') ...but it's not working.
Mage::getSingleton('checkout/type_onepage')->getCheckoutMethod()
stackexchange-magento
{ "answer_score": 2, "question_score": 0, "tags": "magento 1.7, checkout, onepage checkout" }
Properties, Types and Python Using Properties, I figured one can easily get things mixed up. Like the code below, I'd love `id` to be of type `int` but don't know if Python can allow me do that without a try statement and catching ValueError def getter(self): return id def setter(self, id): self.id = id If I input `'boy'` instead of `1` in there, the code still run. Is there a way to eliminate this?
you can just call int on id: def setter(self, id): self.id = int(id) now passing `1` or `"1"` will work, but passing `"boy"` will raise an exception
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "python" }
Simple JOpenID string declaration I am new to programming and JOpenID, what is a simple code example? I have heard that it is similar to Java, even though I do not know Java. My programmer friends recommended JOpenID and they say you need to learn declarations first.
I would recommend learning Java first, but a simple code example for a String declaration would be this: private static final String ATTR_MAC = "string1"; private static final String ATTR_ALIAS = "string2";
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "jopenid" }
How to make the application for all version in iPhone I am beginner in iPhone. I want to make the iPhone app that compatible for all iPhone versions like 3 and above. Please help me What to set in the project to make it compatible to all version. Thanks in advance.
You should set the deployment target in the target summary. **Edit** : Xcode 4.5.x only supports iOS 4.3 and later so you can't support iOS versions below it. **Edit 2:** If you are using and old version of Xcode this might be helpful for you. iOS 3.x support in Xcode 4 But you should think twice before writing an application that targets iOS4 and above. Targeting to old versions of iOS means that you must not use any of the API's of the next iOS versions such as ARC and auto layout. As a result your code will be harder to maintain and some features would be impossible to implement. Before going on with it, think about how many users will you satisfy by supporting iOS4. Read these thousand words from apple and then decide for yourself !enter image description here
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "iphone" }
PHP between HTML tag echo I need to have PHP between my echo between a html tag, anyone can help ? If you see my code, I want the `li` to have a PHP `if` in between it. please help. thanks. echo '<li id="dm-item1"' if($currentMenuId == '131') { echo 'class="current active"'; } '>'; I want to echo this : <li id="dm-item1"> With this in between <?php if($currentMenuId == '131') { echo 'class="current active"'; } ?>
?> <li id="dm-item1" <?php if($currentMenuId == '131') echo 'class="current active"';?> > Just close the PHP when you are bout to use HTML tags, don't print them. Print only the variable content.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, html" }
Android: Naming menu file I am new to Android SDK (not java) and I had a question or two about options menus. I look around for several tutorials, including the developer.android one. My problem is the naming of files. The menu works fine when in my res/menu folder the menu xml document is titled menu.xml. If I try to call in mainMenu.xml I get a mainMenu cannot be resolved or is not a field error. Here is the code in my main activity, @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainMenu, menu); return true; } The "mainMenu" in R.menu.mainMenu in the above code is underlined in red (error) So my question is can I name my menu file anything I want? This way seems to restrict me to one options menu per project which cannot be correct (unless I am missing something : )
You can definitely have multiple options menus: there may be a lower case restriction though. Use underscores and you should be all set? EDIT: yep, this error message occurs when you try and build: [2011-05-20 12:09:40 - BlAH BLAH BLAH] res\menu\newMenu.xml: Invalid file name: must contain only [a-z0-9_.] So there is a lower case restriction. Never knew that.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, android layout, android menu" }
How to use apache commons (or any other library not part of the jdk) from Scala Seems like this should be simple, but I'm not a java guy. I was going to try and use the apache commons ftp component (org.apache.commons.net.ftp), but I don't know how to make it accessible to my scala code. At the moment, I've just tried dropping the package into a directory, starting the scala repl from that directory, and issued: import org.apache.commons.* I'm told that apache is not a member of package org, which I assume to mean it can't find the code. This really seems like it ought to be easy, but any suggestions would be appreciated.
You need to add the jar into the class path. From REPL, that is done like so: scala -classpath some.jar If you are building a project, you might want to consider using a build tool like sbt (< which allows you to specify dependencies.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 3, "tags": "scala, apache commons net" }
how to upgrade ubuntu 10.04 LTS to ubuntu 13.04 without internet? No internet,NO cd/dvd rom, only USB. I have no idea how to upgrade the system. Any one can tell?
I THINK the only way to do it would be to get someone with Internet to follow these instructions for 13.04 and then you will have to put it into your PC, reboot to the bootloader (you might need to press ESC or F5 or something while booting to get to the Startup Menu in your PC) and then select USB. You can then select the option 'Upgrade to 13.04' to keep your files. You might want to back-up your data maybe by simply copying the files in your Home Folder to an external hard-drive and then copying them back if you need to.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "13.04, upgrade, 10.04, offline" }
intransitive usage of "vorlegen" In the minutes of an official committee, I have found the following sentence: _" Zum Zeitpunkt des letzten Komitees lagen noch keine aktuellen Werte für die Prognosen der Bank vor."_ I am surprise by this usage of _" vorlegen"_, i.e. only with a subject and without an object, because I did not know this verb could be used in such an intransitive way. I have looked in the Duden and elsewhere, but I could not find this usage. Therefore: * Is the above sentence correctly constructed in German ? * Instead, could/should we use the verb in a reflexive way, for instance _" Zum Zeitpunkt des letzten Komitees lagen **sich** noch keine aktuellen Werte für die Prognosen der Bank."_ ?
Yes, the sentence is fine. The verb there is "vorliegen", though, which is always intransitive.
stackexchange-german
{ "answer_score": 6, "question_score": 0, "tags": "sentence structure, grammaticality, verb usage" }
Fixing Python file association I'm learning python on x64 windows 7 machine. But after installing and uninstalling python 2.7 and 3.2 a few times too many (i just found out 3.x doesn't support some of the 3rd party libraries like PIL), i have lost .py file association(when i double click my python scripts, windows asks me to choose a program to open it with instead of making python interpret it). How can i fix the issue?
considering you've already set the path in environment variables: open `command prompt`: `cd` to the directory which contains `lost.py` and then type: `python lost.py` and hit enter. or using IDLE: start IDLE --> press CTRL+O --> open your file --> press F5
stackexchange-superuser
{ "answer_score": -1, "question_score": 1, "tags": "python" }
Inverting colors under OSX Mountain Lion In previous versions of OSX, you could invert the colors on the display by hitting `cmd`+`ctrl`+`option`+`8`. It appears that they have removed that functionality in Mountain Lion. Does anyone know how to get that functionality back?
The keyboard shortcut for that function is for some reason disabled by default in Mountain Lion, but you can enable it in **System Preferences>Keyboard>Keyboard shortcuts>Accessibility** !Screenshot of the Setting
stackexchange-stackoverflow
{ "answer_score": 47, "question_score": 23, "tags": "macos, osx mountain lion" }
How to launch chrome browser using selenium When am trying to launch chrome browser using selenium it throws me error. Am using this command in my code "selenium = new DefaultSelenium("localhost", 4444, "*chrome", "<
f you want to launch Google Chrome, you will have to use something else than "*chrome". Using Selenium RC in interactive mode, with something like this $ java -jar selenium-server.jar -interactive and using the getNewBrowserSession command not correctly : cmd=getNewBrowserSession I get the list of browsers is supports : 23:43:09.317 INFO - Got result: Failed to start new browser session: Browser not supported: (Did you forget to add a *?) Supported browsers include: *firefox *mock *firefoxproxy *pifirefox *chrome *iexploreproxy *iexplore *firefox3 *safariproxy *googlechrome *konqueror *firefox2 *safari *piiexplore *firefoxchrome *opera *iehta *custom on session null So, I'm guessing you should be able to launch Google Chrome using "*googlechrome" instead of "*chrome". -reference - sir pascal martin . :D
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "google chrome, selenium" }
What if Elements Being Compared in Hoare's Quicksort Are the Same? Consider an unsorted list 9,3, **5** ,3,9, with 5 being the pivot. When the elements at index 0 and index 4 are compared, their values are equal to each other, and both are greater than the pivot value. What would happen in this case? They can't be swapped, because there would still be a 9 in the 'less than' section. Is one of the 9's just moved over to the other side. And the same goes for the 3's. What happens to them?
Those elements are not compared to each other. In Hoare partition scheme, the array is scanned from the left for the first element > pivot, and then scanned from the right for the first element < pivot. That means that the first swap will be for array[0] = 9 with array [3] = 3. After that no more swaps occur. Depending on Hoare partition implementation and data pattern, the pivot element can end up as the last element of the left partition or as the first element of the right partition. Elements equal to pivot are left in place in either left or right partition, and dealt with in later recursions.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "algorithm, sorting, computer science, quicksort" }
What's the difference between request.env['REQUEST_URI'] and request.env['REQUEST_PATH']? What's the difference between request.env['REQUEST_URI'] and request.env['REQUEST_PATH'] in Rails? They always seem to contain the same value.
I believe delroth is correct about the distinction, however in almost all cases it's better to use the methods in Request instead of directly accessing the environment variables. **request.request_uri** returns the requested url including the query string and without the domain. **request.path** returns the path of the request without the query string, domain and any relative root (if your app runs from a directory other than root). See the Rails API for ActionDispatch::Request to see other helpful methods.
stackexchange-stackoverflow
{ "answer_score": 30, "question_score": 18, "tags": "ruby on rails" }
как получить по id vk имя и фамилию Получил user_id, но не знаю как по нему получить имя и фамилию пользователя request.executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { super.onComplete(response); VKApiGetDialogResponse getDialogResponse = ((VKApiGetDialogResponse)response.parsedModel); final VKList<VKApiDialog> list= getDialogResponse.items; ArrayList<String> messages = new ArrayList<>(); ArrayList<String> users = new ArrayList<>(); for (VKApiDialog msg : list){ users.add(String.valueOf(msg.message.user_id)); messages.add(msg.message.body); } listView.setAdapter(new CustomAdapter(MainActivity.this,users,messages,list)); } });
Выполняете запрос users.get, в котором передаете `id` пользователя и получаете список результатов из которого выбираете первый.
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "java, android, vkontakte api, вконтакте" }
Method from included Trait implementation not found in scope in Rust I want to use two external libraries (geo-types-0.6.0 and geo-offset-0.1.0) to perform geometric algorithms. The example below seems fine: The `Line` type is defined in the library `geo_types`. The `Offset` trait moreover is written in `geo_offset`. Including this trait should lead to the `Line` type implementing method `offset`. However I get the following error: `no method named `offset` found for struct `geo_types::line::Line<float>` in the current scope` In addition to that, the `rust-analyzer` in VS Code tells me, that the included trait `Offset` is not used. Why is that? use geo_types::{Coordinate, Line}; use geo_offset::Offset; let line = Line::new( Coordinate { x: 0.0, y: 0.0 }, Coordinate { x: 1.0, y: 8.0 }, ); let line_with_offset = line.offset(2.0)?;
The `geo-offset` crate implements the `Offset` trait for `geo::Line`, not `geo_types::Line` (src \- search for `geo::Line`). So even so `geo::Line` is just a re-export of `geo_types::Line`, the rust compiler doesn't see this deep and only knows about the `Offset` implementation for `geo::Line`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "rust, compiler errors" }
Backtracking - problem with list updates in the recurrsive call I was trying to solve **797\. All Paths From Source to Target** from `Leetcode`. I thought of using Backtracking with recursion. In the below code, the list `setOfPaths` is also getting updated when I pop from `path`. I am not sure what I am doing wrong here. class Solution(object): def allPathsSourceTarget(self, graph): path=[] setOfPaths=[] path.append(0) self.backtrack(graph,0,len(graph)-1,path,setOfPaths) return setOfPaths def backtrack(self,graph,src,dest,path,setOfPaths): if(src == dest): setOfPaths.append(path) else: for node in graph[src]: path.append(node) self.backtrack(graph,node,dest,path,setOfPaths) path.pop(len(path)-1) #BackTracking
When you try to append `path` to the `setOfPaths`, it do not really append the `path`'s data, but the reference to `path` or `path` variable itself is appended. Because `setOfPaths` did not contain the data, it contained the variable, when you modified data inside variable, you would see `setOfPaths` also be modified. To get rid of it, the simplest way is to store a copy of variable, so that you would not modified the data when you try to modify the "main" variable. This piece of code should work if(src == dest): setOfPaths.append(path[:])
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, data structures, structure, backtracking, recursive backtracking" }
How to isolate values from a list in Python? I have a few lists I'm trying to investigate.I'm stuck at some point: D = [1, 1, 1, 2, 5, 1, 1, 1, 1, 1, 3, 2, 1, 1] Let's say this is the list. I need to isolate a new list from the list D.We can say I want to filter those "1"'s; but I couldn't manage it. If I use "index" method like: D = [1, 1, 1, 2, 5, 1, 1, 1, 1, 1, 3, 2, 1, 1] E = [] for i in D: if not i == 1: E.append(D.index(i)) print(E) The output is: [3, 4, 10, 3].What I need is [3, 4, 10, 11].Since values are at D[3] and D[11] are the same, python does not allow me to get the second one.How can I solve this? Your help is highly appreciated. Thanks.
You can write this program in many ways. I will try to adapt your example with minimal changes first: D = [1, 1, 1, 2, 5, 1, 1, 1, 1, 1, 3, 2, 1, 1] E = [] for i in range(len(D)): if D[i] != 1: E.append(i) print(E) However, there is also a shorter/simpler one-line solution: D = [1, 1, 1, 2, 5, 1, 1, 1, 1, 1, 3, 2, 1, 1] E = [i for i in range(len(D)) if D[i]!=1] print(E)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, list, methods" }
How to fill error date value with 0 in python id date_original 1 20200305 2 2020305 3 2020035 4 202035 How can I convert the 'date_original' column into 'date' column in pandas dataframe? id date 1 20200305 2 20200305 3 20200305 4 20200305
For me working well all formats if used `format` for match `YYYYMMDD`, tested in pandas 1.1.3: df['date_original'] = pd.to_datetime(df['date_original'], format='%Y%m%d', errors='coerce') print (df) id date_original 0 1 2020-03-05 1 2 2020-03-05 2 3 2020-03-05 3 4 2020-03-05
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python 3.x, pandas, dataframe" }
Apache Ignite: How to cache an entry with multiple keys Is there any way to cache one entry against two keys in apache ignite? say for eg: I need to cache users, based on their user id and their username, so I can get it back in both ways. Which is the best way to achieve this?
1. Use two caches, from Id to User (`ICache<Guid, User>`) and from UserName to Id `ICache<string, Guid>` 2. Use one cache `ICache<Guid, User>`, and create an SQL index on UserName column <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, .net, ignite, gridgain" }
How to get / set jpeg exif data with objective c - mac os Currently trying to extract and manipulate the exif (or whatever meta data a Canon camera produces on an image) Is there any specific library that I can use to process this data? Note: Am not developing an ios app, mac os to be specific. Thanks!
< appears to be a common C library for exif data. (First result on Google search for 'exif c') There seems to be a few C++ libraries, but no pure Objective-C that I could find easily
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "objective c, metadata, jpeg, exif" }
Start Activity from RecycleView Adapter on click I have an issue starting a new activity from a CardView Adapter, this is the code: RVAdapter adapter = new RVAdapter(array_restaurants); recList.setAdapter(adapter); And after in the adapter. I set an OnClickListener personName.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Context context = v.getContext(); System.out.println("Context"); System.out.println(context.toString()); Intent intent = new Intent(v.getContext(), Restaurante.class); v.getContext().startActivity(intent); } }); When i print the context in the console everything looks fine, but after the aplication stop working. Why? Thank you very much.
After a lot of time I found an answer, the answer that those people submit help me to found the main problem, this was the solution In the MainActivity I added a new parameter and pass the activity to the adapter, like @Meenal Sharma and @ch3tan proposed RVAdapter adapter = new RVAdapter(restaurantes, this); And in the adaptor public Adaptador(List<Restaurant> restaurants, Context context) { this.restaurants = restaurants; this.context = context; } And creating the intent: Intent intent = new Intent(context, RestaurantActivity.class); context.startActivity(intent); That part solve an error but the main error that i had was, when I created a new activity with the Android Studio that created the new activity inheriting of ActionBarActivity, I changed ActionBarActivity for AppCompatActivity and everything worked again...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, android intent, android activity, android studio" }
Como obtener variables de entorno de windows con javascript Como podria obtener desde el lado del cliente ciertas variables de entorno de windows, como el usuario de inicio de sesion con javascript ( sin ningun framwork) que no sea con activexobject
Javascript, o mejor, el navegador, no tiene permisos para acceder a las variables de entorno/sistema. Imagínate lo que podría pasar si cualquier pagina web pudiera acceder a tus variables, cualquier ladrón podría **obtener información sensible** sobre tu ordenador. Aunque también podrías utilizar node-webkit, un "navegador" especial, pero probablemente nadie de tus visitas lo utilice. En un navegador normal, no hay manera de conseguir las variables de entorno solo con Javascript.
stackexchange-es_stackoverflow
{ "answer_score": 6, "question_score": -4, "tags": "javascript, windows" }
Silverlight control with code hightlighting? Is there a Silverlight control out there that will allow you to type in text and have it highlighted as code? For example: foreach (client in Clients) { client.Save(); } would become foreach (client in Clients) { client.Save(); } I need to write a web app to screen non-programming programmers without wasting time on them one by one. I am thinking of a Silverlight app that will ask a few simple programming questions with a time limit. After the limit is up, it will send what they have via a web service. Most of that is quite doable for me, but I would like to be able offer my candidates code highlighting. I am not up to (nor interested in) writing a Silverlight code highlighter. Any suggestions?
Actipro Software has a syntax highlighter component for Silverlight, WPF, and Winforms: <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "silverlight, controls, syntax highlighting" }
How to catch everything between two (numbered) markers, including line breaks? I'm trying to capture everything between two markers (`START[number]` and `END[number]`) where number also needs to be extracted. I need to support line breaks. For instance the following : START[1] message to capture ...END[1] must return : 1. group 1 : `1` 2. group 2 : ` message to capture ...` 3. group 3 : `1` Here is my attempt (demo): START\(\d+)\*?)END\[(\d+)\] It doesn't work as I obtain a third group made of the last character of the message to capture and I don't know why. Can someone may help me with this ? Thanks.
Use `[\s\S]` instead of `(.|\n|\r)` START\(\d+)\END\[(\d+)\] Demo To be sure to have the same number in START and END, use a backreference to group 1: (Credit to Aaron de Windt in comment) START\(\d+)\END\[(\1)\]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, regex" }
Error: Data source must be a URL for refresh | console error | javascript | Highcharts I received this error from console while creating the chart using Hightcharts. I am using vue.js framework. I don't know why this error is occurring. But it's not affecting my chart. Need to resolve this console error. ![enter image description here]( . My code is below: <column-chart :min="0" :refresh="60" height="400px" xtitle="City" :data="series" label="Value"></column-chart>
Please remove refresh attribute in your code. <column-chart :min="0" height="400px" xtitle="City" :data="series" label="Value"></column-chart> Console error will not show. If you remove the refresh option. refresh should be from your url. Not from chart.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, vue.js, highcharts" }
Find the order of $(3,1)+\langle0,2\rangle$ in $ \Bbb Z_{4}\oplus \Bbb Z_{8}/\langle0,2\rangle$ **Question** Let $\langle 0,2\rangle $ denote the sugroup of $\Bbb Z_{4}\oplus \Bbb Z_{8}$ generated by $(0,2)$. Then find the order of $(3,1)+\langle0,2\rangle$ in $\Bbb Z_{4}\oplus \Bbb Z_{8}/\langle0,2\rangle$ **MY Approach** $|(0,2)|$ in $\Bbb Z_{4}\oplus \Bbb Z_{8}$ is 4 $$|\Bbb Z_{4}\oplus \Bbb Z_{8}/\langle0,2\rangle|= 8\\\ (3,1)+\langle0,2\rangle=\\{(3,3),(3,5),(3,7),(3,1)\\} $$ i don't know the formula to calculate the order of this coset
Well, we have $$ \big((3,1)+\langle0,2\rangle\big) + \big((3,1)+\langle0,2\rangle\big) = (2,2)+\langle0,2\rangle\\\ =\\{(2,2),(2,4),(2,6),(2,0)\\}\neq (0,0) + \langle 0,2\rangle $$ so the order is not $2$. Now check whether the order is $3, 4$ and so on. It won't take long until you have your answer. > This can be made somewhat shorter if you note that the order of $(3,1)+\langle0,2\rangle$ must be a divisor of the order of $(3, 1)\in \Bbb Z_4\oplus\Bbb Z_8$, which is $8$. So the answer cannot be $3$, and you can skip that and go straight to $4$. If the order isn't $4$, then it can't be $5, 6$ or $7$, so it _must_ be $8$, and you're done.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "abstract algebra, group theory" }
CakePHP facebook logut session not destroying I am using cakephp 2.1 and using facebook plugin from < I am using facebook login helper as below $this->facebook->login(array('redirect' => 'facebook_login', 'label' => 'sign in via facebook', 'id' => 'fb-login')). and logout helper as below $this->Facebook->logout(array('redirect' => array('controller' => 'users', 'action' => 'logout'), 'label' => 'Logout')). In logout action I have written this code. $this->Auth->logout(); $this->redirect(Controller::referer()); But proble is when new user come and login, its showing old logged user data. So please help me to figure it out.
## change this below: $this->Auth->logout(); $this->redirect(Controller::referer()); **to** $this->redirect($this->Auth->logout()):
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "php, facebook, session, logout, cakephp 2.1" }
Installing Apache Struts2 on OS X I have decided to have a look at JSP technology and some of the frameworks surrounding JSP. However, I am struggling to find information regarding the installation of the JSP API, the servlet API and how to configure them all to run through Apache on OS X. If anybody could point me in the right direction I would appreciate it.
Struts2 as well as JSP api, are platform independent, so doesn't matter if you using OS X or other OS. Maybe the easiest way to get a Struts2 application (including servlet and jsp apis) working is installing maven and then execute the command line text provided from AppFuse. AppFuse's maven project will provided you with Jetty, and the JSP api will be marked as a provided dependency <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "macos, apache, jsp, struts2" }
set php variable to find current page $pages = array('Text1.php', 'Text2.php', 'Text3.php'); // $currentpage depends the page you're on $currentId = array_search($currentpage, $pages); I have php script which is accessed through an `include(Text4.php)` and the `include(Text4.php)` is stored in all the three php scripts above in the array. Now what I want to do is set up the `£currentpage` so that it should equal the page the user is currently on and match a value in `$pages` which should be the filename of the current page. My question is that in the code above, how should $currentId variable be written to perform the functionality it is suppose to acheive?
File name only: $currentPage = basename(__FILE__); __ Directory name + filename: $currentPage = __FILE__; __ Directory only: $currentPage = __DIR__;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Using ps2pdf correctly in a script? I have a script below and I am having problems. I have several folders with PostScript file in them I want to batch convert to PDFs. I have done very little scripting in linux before but I think this is close. It is not quite working how I want it though. Any suggesting? or notice a mistake I made? I want the files to stay in the same location after they have been converted. Currently this converts the files but they get all put together in one folder. I call the script like this: ./all.ps.to.pdf "/directory/to/process" #!/bin/sh STARTDIR=$1 if [ ! -d "$STARTDIR" ]; then echo No starting directory $STARTDIR exit 1 fi find $STARTDIR -name '*.ps' -print | sed -e 's/.ps$//' | xargs -l -i ps2pdf \{}.ps
> notice a mistake I made? Yessss, Sir. Your `find` command should be all in one line. Or, if you want to spread it over two lines, use `\` as the line continuation sign (which must be the very last character on the first line without any blanks following it!). That is... * either use find $STARTDIR -name '*.ps' -print | sed -e 's/.ps$//' | xargs -l -i ps2pdf \{}.ps * or use find $STARTDIR -name '*.ps' -print | sed -e 's/.ps$//' | \ xargs -l -i ps2pdf \{}.ps * or even use find $STARTDIR -name '*.ps' -print \ | sed -e 's/.ps$//' \ | xargs -l -i ps2pdf \{}.ps (whichever you think looks "nicer" to your Bash reading eyes...).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "linux, bash, scripting, ghostscript" }
Issue a Conditional Redirect in Drupal 7 I have a custom payment form that redirects to a 'Thank You' page on success. The page is just a Page type node, so someone can control the content of the page. What I wanted to do was add a little extra, and prevent the page from being seen unless they had just come from the form. I tried using 3 functions. hook_node_view, hook_node_view_alter, and hook_init. I thought the first two would allow me to check the node path or nid, and redirect if I needed to, but they did not seem to be called. Additionally, I tried mymodule_init() { global $user; krumo($user);exit; } That was not being hit, either. The rest of the module works fine, custom menu item, custom form, validate/submit/mail hooks. I am stumped. How can I check a node value when loading, take action, and furthermore, why is hook_init() not dumping/exiting?
You should not use `hook_init`, but `hook_boot` as you want to perform the check when caching is turned on. That would also be the best explanation as to why your `exit` doesn't work. That or you forgot to clear cache after implementing the hook. (All hooks are cached in D7)
stackexchange-drupal
{ "answer_score": 0, "question_score": 0, "tags": "7, hooks, nodes" }
check/uncheck tick checkboxes but ignore any disabled ones I'm using the following Jquery to check/uncheck checkboxes but some of the boxes in are disabled so I don't need to be checked. Is there a way I can tell the script to ignore disabled checkboxes? $('.uncheck').click(function () { if ($(this).is(':checked')) { $('.customers input:checkbox').removeAttr('checked'); } else { $('.customers input:checkbox').attr('checked', 'checked'); } });
Use `not()` and `:disabled` $('.customers input:checkbox').not(':disabled'); - if ($(this).is(':checked')) { $('.customers input:checkbox').not(':disabled').removeAttr('checked'); } else { $('.customers input:checkbox').not(':disabled').attr('checked', 'checked'); }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "javascript, jquery" }
How to turn off JSHint error? I have the following error for my files in tests: `Expected an assignment or function call and instead saw an expression.` It is generated from Chai libraries asserts. How can I turn it off in my `.jshintrc` file? I run a Gulp task based on it.
Here's how you can silence it inside of a `.jshintrc` file. { ... "expr": true ... } Source: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, jshint" }
What is the syntax of a pointer to a pointer? Let's say I have two structures, struct ptr1 { struct ptr2 *ptrtoptr; }; struct ptr2 { int name; }; Main function looks like this: int main() { struct ptr1 *var1; struct ptr2 *var2; (code for manipulating structure element name); return 0; } How do a manipulate data of variable `name` via pointer `var1`? Let's say both pointers are already pointed at a certain address. Is this correct? `var1->(var2->name)=(some value)` or `(var1->var2)->name=(some value)`?
> How do a manipulate data of variable name via pointer var1 ? Using : var1->ptrtoptr->name = some_value ; // or (var1->ptrtoptr)->name Neither of `var1->(var2->name)=(some value)` or `(var1->var2)->name=(some value)` make sense since `var2` is not a member of `ptr1`, which can't be accessed using `var1` * * * **Note:** Also, be cautions about the operator associativity , operator `->` has left to right associativity, therefore `var1->(ptroptr->value)` will not be same as `var1->ptrtoptr->name`
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "c, pointers" }
Infinitely stacked set suppose we have following sequence: Let $s_0$ be a set. Then let be $s_1 \in s_0$ our next set. In general $s_{n+1} \in s_n$. Assuming ZFC, I was curious about this: > Can one prove, that such sequence always ends, i.e. there will always be some $k \in \mathbb N ,$ s.t. $s_k = \emptyset$. I assume this to be false but I have been unsuccessful in constructing a sequence of sets that will go on infinetely. That also made me wondering, whether one can prove the opposite or not. For example, I think that for $s_o \in Ord$ such sequence will come to an end since all $s_i \in s_0$ and $(s_0,\in) $ is wellorded. Is this true? Thank you very much in advance. References are highly appreciated as well.
Take the set $$ A=\\{s_0,s_1,s_2,\ldots\\} $$ which exists by the axiom schema of specification (and possibly the axiom of dependent choice, depending on how the $s_i$ are established). We have, for any $s_n\in A$, that $s_{n+1}\in s_n\land s_{n+1}\in A$, contradicting the axiom of regularity. **Edit:** As pointed out by Asaf Karagila in the comments, there is a well-defined rank "function" that prescribes to any set $X$ in ZF an ordinal called it's _rank_. This rank describes how "deep" it is in exactly the sense of what chains $X=s_0\ni s_1\ni\cdots$ exist (that's not the definition, but it's how I think of it). This rank is strictly decreasing on such a chain, and thus any chain gives rise to a strictly decreasing sequence of ordinals. Such a sequence can only be finitely long, so any chain is finitely long (although any set of rank at least $\omega_0$ will have arbitrarily chains of any finite length). This way we avoid any form of choice.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "set theory" }
C++ conversion from array to pointer I am bit struggling with kinda easy task. I need to convert array to pointer. GLfloat serieLine[8][80]; GLfloat *points = &serieLine;[0][0]; this gives me just first value, but how can I get all values in the array?
If you want pointer to an array, you can do it like this: GLfloat (*points)[80] = serieLine; `points` will point to the first row of `serieLine`. If you increment `points`, it will point to the next row.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c++, pointers, conventions" }
Show ports in use on Catalyst 3570 I picked up a used C3570 and am new to IOS. I am trying to ask the switch to show which ports are in use. My searches lead to the command "show modules" but that's refused by the switch (and command line help suggests no such command) I have been unable to find the command - if there is one. Can someone offer the closest command(s) which would show which of the 24 ports are plugged in, perhaps the IP/MAC's on the other side of that port, etc?
You can use: show interface status If you want to see MAC addresses show mac address [dynamic] For a specific interface: show mac address [dynamic] interface <interface-name> For a specific vlan: show mac address [dynamic] vlan <vlan number>
stackexchange-networkengineering
{ "answer_score": 3, "question_score": 0, "tags": "cisco, cisco ios, switchport" }
To support iOS 4.3, use "assign" instead of weak, but Interface Builder uses unsafe_unretained? To support iOS 4.3 with ARC, I think the proper way is to use `assign`: @property (assign, nonatomic) UIView *view; @property (assign, nonatomic) MYNode *node; Is that correct? I also see the following in Apple's doc for Transitioning to ARC: > For declared properties, you should use assign instead of weak; for variables you should use __unsafe_unretained instead of __weak. However, if I use the current Xcode (4.4.1), changing a Single View app target to 4.3, and Ctrl-drag a UIButton to the `.h` file to create an outlet, the generated code is: @property (unsafe_unretained, nonatomic) IBOutlet UIButton *foo; Why the difference and which one should be used?
According to 4.1.1. Property declarations in the llvm documentation "assign" and "unsafe_unretained" are equivalent in a property declaration: * assign implies __unsafe_unretained ownership. * ... * unsafe_unretained implies __unsafe_unretained ownership. **ADDED:** In the clang source code < you find 00523 // 'unsafe_unretained' is alias for 'assign'. 00524 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) 00525 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "objective c, automatic ref counting, assign, unsafe unretained" }
Altium 18 - "Override library primitive" option missing? I'm busy setting up my new install of Altium 18 to match my preferred settings, namely making the default schematic font Consolas (for the purposes of mono spacing and slashed zeroes). Normally this involves going into Tools -> Preferences -> Schematic -> Defaults screen, and changing all the fonts to the desired one for each primitive. However, since Altium 18 I notice the "override library primitive" checkbox for parameters/designators/values is missing, meaning while I get Consolas as the default font for any new schematic symbols I make, any existing library symbol I use still hangs on to Times New Roman. **Old Altium:** ![Old]( **Altium 18:** ![enter image description here]( Any ideas where this checkbox went, or how to emulate the same functionality?
Aha - Altium needed updating. This was only snuck back into Altium a few releases into version 18. Added as of release 18.1.0.16385.
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "altium, software, setup" }
Use panel url for Solr result I am using Apache Solr on my website and the search form block is configured to use Apache Solr. I also use the Apache Solr panels module to panelize my page. I create a panel on search/my-search/!query, when I use it manually all works fine but when I search via the form search block, I am redirected on the default Apache Solr result page (search/site/!query). How can I change this behavior ? EDIT : Okay, I found the solution by searching a little bit more ! I just disabled the default search block form and put the "Search form (Apache Solr Panels)" in the section I wanted. I only have to restyling my input. I will put it in a separate answer tomorrow (because of my reputation, I can't answer in the next 8hrs after posting my question)
Sorry for delay, I post here my answer separately from the question : Okay, I found the solution by searching a little bit more ! I just disabled the default search block form and put the "Search form (Apache Solr Panels)" in the section I wanted. I only have to restyling my input.
stackexchange-drupal
{ "answer_score": 0, "question_score": 3, "tags": "search, panels" }
Paging Results .net and the grid concept I´ve been checking .net available paging options (telerik, others) and one recurrent situation that I found is the grid concept to refer to that functionality. By grid concept I mean, columns and rows (even including column name) giving less design customization possibilities. Does anyone know any implementation or library for .net mvc in order to deploy paging results using more fancy design implementations not attached to column display idea. brgds, sebastian
Not totally sure I follow what your trying to do..but for paging data in a grid/column type layout I recommend the jQuery Datatables plugin. Its very customizable/flexible. its allows for styling via css and handles paging, filtering, and sorting among other features. you can learn more about the plugin HERE and THIS is a great article explaining "server-side processing" with asp.net MVC using the plugin. Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, asp.net mvc 3, paging" }
Storing chocolate at home in the summer In the summer while I'm at work I'd like to set the temperature of my small apartment higher--roughly 83 degrees as per US department of energy recommendations. I'm planning on keeping it between 76-78 when I'm home. However, I don't want my chocolate to to deteriorate. Let's assume we're talking about a thin bar of Lindt milk chocolate. It's been fine so far with the apartment set at 78*F and the chocolate in a dark cabinet. I definitely don't want to put it in the refrigerator as this is too cold for it. What is the maximum temperature I can leave my apartment at when I'm not around to keep the chocolate reasonably stable? Should I use a cooler or box to keep the chocolate cooler than the rest of the house? Is there a cheaper/better/easier option I haven't thought of?
There are three different crystal types in solidified chocolate with one of them being the prefered type. This is why we temper chocolate, because it promotes crystallization of the prefered type. From what I recall, the ideal temperature for chocolate is 70°F and the first type of crystal in chocolate starts melting at around 82°F. So while not ideal, you should be fine with the room at 78°F. Keep in mind Lindt chocolate with milk is a little softer than their darker chocolate line. You can simply place the chocolate in a cooler (like a coleman) along with a pop can that has been in the fridge. The cool can should prevent the chocolate from getting too hot. Switch the can with another cold one daily and that should keep the snap sound in the chocolate along with the taste.
stackexchange-cooking
{ "answer_score": 3, "question_score": 3, "tags": "storage method, chocolate" }
Install Ubuntu on Windows 7 tablet I'm trying to install Ubuntu on a Windows 7 tablet (HP Slate 500). I wanted to install Ubuntu touch, but can't seem to find an .iso anywhere. The guide here: < does not help as it is not an Android tablet. I was going to use Unetbootin and put it on a USB and install it from there. However, I'm afraid if I download the desktop version, I won't be able to type anything in the tablet. I'm doing this for educational purposes. The tablet is really old and doesn't have anything important in it. Any help would be appreciated!
There is no Ubuntu touch for this device (that I could find). You should look at xubuntu as your CPU is weak, it comes with an on-screen keyboard, find it in `Applications > Universal Access > Onboard Settings`, so no worries there, on the log in screen you will see the accessibility icon ( a little man symbol) and can start the keyboard from there. Also any usb keyboard will work too. If your tablet is old and not important, whats wrong with just trying some distros ? If something won't work, try a different one. UPDATE: This may be of interest to any x86 tablet users. There is actually a early daily build of Ubuntu Touch 15.10 (Wily Werewolf) on ubuntu.com, can't say how well it works, it is a daily. Looking at the tablet in this question, it should meet the requierments for running Touch.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "system installation, windows 7, ubuntu touch, hp, tablet" }
Java ArrayList Index int[] alist = new int [3]; alist.add("apple"); alist.add("banana"); alist.add("orange"); Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output? output: banana
You have `ArrayList` all wrong, * You can't have an integer array and assign a string value. * You cannot do a `add()` method in an array Rather do this: List<String> alist = new ArrayList<String>(); alist.add("apple"); alist.add("banana"); alist.add("orange"); String value = alist.get(1); //returns the 2nd item from list, in this case "banana" Indexing is counted from `0` to `N-1` where `N` is `size()` of list.
stackexchange-stackoverflow
{ "answer_score": 109, "question_score": 29, "tags": "java, arraylist" }
Best way to return multiple values in echo from PHP and parsing in Javascript I'm using ajax to request data and and echoing a string containing a number of variables and trying to parse this data using javascript. `Echo eg. fullname=Joe Soap&companyname=banana&website=mywebsite.com` In my javascript, I understand I could use string functions to search and extract, but this seems a bit cumbersome. I'm assuming there is a much more elegant solution which I don't know about (I haven't been coding in PHP and javascript for very long) and I'm keen to learn the best practices. **What is the best way to achieve this?** 1. Is this the best way to echo multiple values back to my javascript? 2. What is the best way in javascript to parse the data? Thanks in advance.
You probably need json_encode <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, php" }
How can I protect integer data on NSUserDefaults from hacking? I have the paid content on my application on App Store. And I save it using the following code: paidContentCount = [[NSUserDefaults standardUserDefaults] integerForKey:@"paidContentCount"]; But it's easy to hack it. How can I protect integer data from hacking?
You can try saving your content as string with `[NSString hash]` method, and after your app is loaded, compare paid content's hashes with value from `NSUserDefaults` UPDATE: forgot that `[NSString hash]` returns NSInteger
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "ios, iphone, security, nsuserdefaults" }
Converting columns into class objects I have a class `Asset` that takes a name (should be entered with quotation marks). This will work fine: `Apple = Asset ('AAPL')` I want to turn all dataframe columns into Asset objects. Am trying the following code but does not work: for column in df.columns: column = Asset (column) I also tried the same thing with df.columns converted into a list of strings. **Edit** My goal is to create one object for each column bearing the same name as the column. In this way, the object will possess the content of the column such as price automatically. The class is defined as: class Asset: def __init__(self, name): self.name = name self.price = df[name] self.pct = self.price.pct_change()
Reassigning `columns` just means you are changing the object that the variable references, it does not imply that the original `df.columns` will be updated. I'd recommend using a list comprehension and assigning the result back: df.columns = [Asset(x) for x in df.columns] * * * Based on your edit, asset = [Asset(x) for x in df.columns] Or, asset = {x : Asset(x) for x in df.columns}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, class" }
Open the popup of the particular div When I click on the `class="team-single"` of `id="team-1"` then it should open the `.team-popup` of that particular id. But it doesn't seem to work. <div class="team-single" id="team-1"> <div class="team-popup"> <span class="close-btn">x close</span> </div> </div> <div class="team-single" id=team-2> <div class="team-popup"> <span class="close-btn">x close</span> </div> </div> This is what I am using for js jQuery(".team-single").click(function(e) { var currentID = this.id || "No ID!"; jQuery(" #currentID .team-popup").css({ display :"block", }); });
Use `find()` with `this` to get current context jQuery(".team-single").click(function(e){ jQuery(this).find(".team-popup").css({ display :"block", }); //Or // jQuery(".team-popup",this).css({ display :"block", }); }); Why your code did not work : You stored the ID in a variable, and to access this variable in a selector use: jQuery("#"+currentID+" .team-popup").
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery" }
Синтаксис jQuery Как сделать чтобы код заработал? $(".saveAll").attr("action", .append("" + i + "")); в элементе с классом saveAll, в атрибут action, в конец добавляем значение переменной. Этот код в цикле, так что нужно что бы именно добавляло в конец атрибута. Спасибо
`.append(..)` — вызов метода `append` "из ниоткуда". Метод `append` вызывается из обьекта, например `$(` _`selector`_`).append(...)`. Важно подметить, что данный метод работает из внутренним содержимым блока, тоесть добавляет текст к `innerHTML`, а не к какому-либо из атрибутов. Так как вам нужно работать не со внутренним содержимым, а именно с атрибутом `action`, нужно узнавать его текущее значение и уже к нему добавлять нужную строчку. Исходя из того, что обьект не один, при добавлении атрибута нужно работать именно з текущим обьектом, тоесть выбирать обьекты по селектору `$('.saveAll')` не можно, нужно работать с обьектом `$(this)`. Именно из-за этого, нужно еще использовать метод `.each()`. $('.saveAll').each(function(){ $(this).attr('action',$(this).attr('action')+i); })
stackexchange-ru_stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "jquery, javascript, синтаксис" }
Pointer not getting updated after sending to another function I was trying to make a simple Linked List program, also when I'm trying to pop the first element from the list , it's not popping and it still remains the first element in the list, please help me resolve this error. Here are the required files and the main code. Thanks. stack.c stack.h char pop(stack *s){ if(s == NULL){ isEmpty(s); return -1; } char x=s->value; s=(s->next); return x; }
The error is at the following line in your `getsize` function: `while( (temp->next) != NULL){` Here `temp` is a pointer which is initialized with the value of the other pointer `s`. (temp and s point to the same address). However you have not allocated any memory to `s` before passing it to `getsize`. So accessing `next` member results in seg fault. **Solution** : Before giving the user the choice to manipulate your `stack`, initialize sufficient memory. There is a `create` function in stack.c that allocates memory to your stack. But you are not even calling that function. So to fix your error, simply call `create` at the beginning of your program. Also, you should not include a `.c` file. You should include the header file *.h instead. (As a good practice).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c, linked list" }
WSIG Deployment BUILD FAILED I would like to use wsig : I followed the guide . So in step of deployement: 1. Prepare the WSIG web application content in the webModule directory. This step can be performed by means of the build target of the ANT build file included in the WSIG distribution. When I launch the command ANT like this : c:\JADE-all-4.5.0\add-ons\wsig>ant build.xml it's displays this error : buildfile: C:\Users\acer\Downloads\JADE-all-4.5.0\add-ons\wsig\build.xml BUILD FAILED Target "build.xml" does not exist in the project "wsig". I checked the folder wsig , build.xml file exists in wsig folder.
Try this instead. >ant -f build.xml If you need to specify a target in the build.xml file then put that on the end. For example - ant -f build.xml mytarget See here for more information.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "web services, ant, pug" }
How to prove this regularized matrix is invertible? So I'm taking Andrew Ng's course on machine learning (great course, only comment is that its lacking a lot of math) and we came across the analytical solution to a model using Normal equations with the regularization penalty. Andrew claims that it is possible to prove that the matrix below, inside the parentheses, is always invertible but I'm stuck wondering how to do it. $$\theta = (X^TX + \lambda [M])^{-1} X^Ty$$ where $M$ is an $(n+1)(n+1)$ matrix and $\lambda$ is the regularization parameter $$M = \begin{bmatrix} 0 & 0 & 0 \\\ 0 & 1 & 0\\\ 0 & 0 & 1 \end{bmatrix}$$
$X^TX$ is either PD or PSD.* If it's PD, it's already invertible. If it's PSD, its smallest eigenvalue is $0$. For any $\lambda>0$, you're making the smallest eigenvalue inside the parentheses positive. *Consider $(Xa)^2$; we can write $||Xa||^2_2\ge0\implies a^TX^TXa\ge 0$. The LHS is nonnegative, so the RHS must also be. And the RHS is immediately the definition of PSD; $a\neq 0$. As whuber points out, $(X^TX)_{1,1}$ must be positive for this to work. This will be true whenever the first column of $X$ is not a 0 vector. (We can verify that easily: the 1,1 entry is the inner product of the first column of X with itself, which must be nonnegative for real values because it is formed as the sum of squares and squares of reals are nonnegative.)
stackexchange-stats
{ "answer_score": 7, "question_score": 7, "tags": "regularization" }
My windows 7 downloads files with appended lines I have a windows 7 on my old laptop which don't support newer OS so i keep that as a test machine for various codes. Most of the times I use `wget` for transferring files from my new laptop to the old one and most of the time when I open the file it has appended lines. I mean, all the lines are just in one line. Not only `wget` but I have made a `vba` code to download files and it still has them in just one line. How to solve this?
If you're downloading text files from Linux, most likely your problem is the Linux end-of-line which is badly recognized on Windows. Windows uses "Carriage-Return Line-Feed" (`\r\n`) as the line ending. Linux/Unix and MacOS use just Line-Feed (`\n`). To convert Linux line endings to Windows, you could use the Unix2Dos utility.
stackexchange-superuser
{ "answer_score": 3, "question_score": 0, "tags": "windows, windows 7, command line, wget, file download" }
How to avoid "wants to open" dialog triggered by openURL in iOS 9.0 I use openURL to open **app B** from **App A** , and I get this alert dialog " **App A** wants to open **App B** ", with two buttons, "Open" and "Cancel". If I press "Cancel", **app B** won't open and dialog will appear again. If I press "Open", **app B** will open and dialog won't appear again. I would like to somehow to make it not appear to begin with. I am wondering if there is a key I should add to **app A** 's info.plist in order to skip the dialog step when doing openURL to **app B**. Any ideas? **Update:** After checking, I could not come up with a solution for my problem. It looks like this dialog will appear regardless. I hope Apple will add the option to handle it automatically as if both apps are mine, logically, there should not be any dialog to confirm switching between them...
After checking for hours, I could not come up with a solution for my problem. It looks like this dialog will appear regardless anything... I hope Apple will add the option to handle it in the app's info.plist as if both apps are mine, logically, there should not be any dialog to confirm switching between them...
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 15, "tags": "ios, objective c, xcode, ios9" }
can hudson show code coverage with a maven2 project So the question is: is there a way to have the cobertura test coverage graph be shown on the front page of a project, similar to the test trend graph, with a maven2 project? refs: cobertura graph in hudson How to generate Cobertura Code Coverage Report using Maven from Hudson If not, is this a bug I should report to them, do you think? Thanks! -r
The Hudson Cobertura plugin should allow a build to be configured with the path to a Cobertura report (in XML format), from which Hudson can then pull the coverage report and render it. The build will still need to run Cobertura itself, either as part of a full **site** generation, or using **cobertura:cobertura**. From memory, look towards the bottom of the project's configuration page (under Post-Build actions); the setting is labelled something like "Publish Cobertura report".
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "maven 2, hudson" }
How do I find min and max of index when using group by in pandas? I use `time` as index in a Pandas DataFrame. time | id | value ---|---|--- 2021 05 01 00:00:00 | JG8oYBAA | 123 2021 05 01 01:00:00 | JG8oYBAA | 431 2021 05 01 01:00:00 | pM8SWMrM | 213 I can run `df.groupby('id')['value'].min()` to find min value for each id: id | value ---|--- JG8oYBAA | 123 pM8SWMrM | 213 But when trying this with the index `df.groupby('id').index.min()` ... I get: `AttributeError: 'DataFrameGroupBy' object has no attribute 'index'`
Try to reset the index before performing groupby. df.reset_index().groupby('id').agg({'value': min, 'time (index)': min})
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, pandas" }
If a list is empty will it throw an exception while applying.contains of a formatted date List<String> Lst = List; Calendar today = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd/MM/yy"); if(null == Lst){ Lst = new ArrayList<String>(); } if(!Lst .contains(df.format(today.getTime()))) { System.out.println("..."); } will this throw an exception if Lst is empty?
Your code won´t throw an exception if you call contains on an empty List. The only time you will receive an exception is in case the list was not initialised (NullPointerException). Anyways the code in your snippet won´t compile if you have no "List" - List instance available the rest of your code because of the first line.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -5, "tags": "java, list" }
Open images from Windows store application I have created a windows store application and I want the user to open Documents, Excel files and picture from the app. I want the files to open in their default application. i.e. Docs in word and pictures in windows picture viewer. I have used the following code: FileOpenPicker openPicker = new FileOpenPicker(); openPicker.FileTypeFilter.Add(".Doc"); openPicker.FileTypeFilter.Add(".Docx"); openPicker.FileTypeFilter.Add(".png"); openPicker.FileTypeFilter.Add(".jpg"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file!=null) { await Windows.System.Launcher.LaunchFileAsync(file); } When I run this and browse to a word document the file opens up fine using word, great. But if I browse to an image file, it doesn't do anything. I don't get any errors. Any ideas what I need to do? Thanks
One other thing you can do is to force app picker if default program could not be launched like following: if (file != null) { var options = new Windows.System.LauncherOptions(); options.DisplayApplicationPicker = true; bool success = await Windows.System.Launcher.LaunchFileAsync(file, options); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "xaml, windows runtime, windows store apps, winrt xaml" }