id
stringlengths
3
6
prompt
stringlengths
100
55.1k
response_j
stringlengths
30
18.4k
346444
I want to display an object if the condition is false for which I was doing something like this in my stateful component return statement. ``` { !this.state.searchCoin ? {displayCrypto} : null } ``` For this, it is throwing the following error > > Objects are not valid as a React Child > > > My display crypto looks something like this (called in render) ``` let displayCrypto = CryptoData.map(el => { return (<CoinCard no={i++} key={el["short"]} coinShortName = {el["short"]} coinName = {el["long"]} coinPrice = {el["price"].toFixed(2)} marketCap = {(el["mktcap"]/1000000000).toFixed(4)} percentChange = {el["perc"].toFixed(2)} vwapData={el["vwapData"].toFixed(2)} /> ``` **[Question:]** How can we I use itinerary expression to display on object if the condition is false? Ps: If you are downvoting this question then please leave a comment as well so that I can improve my question as well.
First of all number your rows, so get the first and fourth per `M_PACK_REF`. Then compare. ``` with numbered as ( select m_pack_ref, m_nb, m_xpfwspt, row_number() over (partition by m_pack_ref order by m_nb) as rn from gather ) select * from (select * from numbered where rn = 1) first join (select * from numbered where rn = 4) fourth on fourth.m_pack_ref = first.m_pack_ref and fourth.m_xpfwspt <> first.m_xpfwspt; ```
346591
So I have a PHP array "$shared" with values [0, 1, 2] (I'm just using this as an example). I want to insert and retrieve this array from my MySQL database, but its not working. Currently I'm using this code to insert it: ``` mysqli_query($dbhandle, "INSERT INTO table (arraytest) VALUES ('$shared')"); ``` And after the above code the value in 'table' in column 'arraytest' is 'Array' instead of [0, 1, 2] or however an array should look like in a MySQL database. After inserting the array into my database, I want to retrieve it, and am currently using this code: ``` $id='2'; $result = mysqli_query($dbhandle, "SELECT arraytest FROM table"); while ($row = mysqli_fetch_array($result)) { $shared=$row{'arraytest'}; if(in_array($id, $shared)){ echo 'Value is in the array. Success!'; } } ``` I did some researching online, and have not found a way to do this specifically. I want to insert a PHP array() into one cell in the table in the database, and then I want to retrieve that array from the database and check if a certain value is in the array which I previously inserted into the database. P.S. I am not trying to retrieve an entire column of values from the database as an array. This is what i have found on google when i search for an answer, and it is not what i want to do.
I have to question why you would want to do this, but the simplest answer is to serialize the array. ``` "INSERT INTO table (arraytest) VALUES ('" . serialize($shared) . "')" ``` Then you can use `unserialize` when you retrieve it from the database --- You should properly parameterize your queries to prevent injection or errors.
347315
I want to write a bash script : ``` schedsim.sh [-h] [-c x] -i pathfile ``` Where : • -h: print the current username. • -c x : get an option-argument x and print out (x + 1). If no argument was found, print the default value is 1. • -i pathfile: print the size of pathfile. The pathfile is a required argument. If no argument was found, print out an error message. This is what I've done so far : ``` x="" path="" while getopts ":hc:i:" Option do case $Option in h) echo -e "$USER\n" ;; c) x=$optarg+1 ;; i) path=$(wc -c <"$optarg") ;; esac done if [ -z "$x"] then echo -e "$x\n" else echo 1 fi if [ -z "$path"] then echo $path else echo "Error Message" exit 1 fi ``` How to finish the option-argument,required-argument part and the error message part?
A rewrite: ``` while getopts ":hc:i:" Option; do case $Option in h) echo "$USER" ;; c) x=$(($OPTARG + 1)) ;; i) if [[ -f $OPTARG ]]; then size=$(wc -c <"$OPTARG") else echo "error: no such file: $OPTARG" exit 1 fi ;; esac done if [[ -z $x ]]; then echo "you used -c: the result is $x" fi if [[ -z $size ]]; then echo "you used -i: the file size is $size" fi ``` Notes: * `OPTARG` must be in upper case. * you need `$((...))` for bash arithmetic * check that the file exists before using it * use a sensible filename (`path` does not represent the size of a file) * there *must* be a space before `]` * `echo -e "value\n"` is too much work: you just want `echo "value"` unless you want to process escape sequences in the value: ``` $ var="foo\tbar\rbaz" $ echo "$var" foo\tbar\rbaz $ echo -e "$var\n" baz bar $ ``` --- Update: responding to comments: simplified and more complete option handling; expanded error handling. ``` #!/bin/bash declare -A given=([c]=false [i]=false) x=0 path="" while getopts ":hc:i:" Option; do case $Option in h) echo "$USER" ;; c) x=$OPTARG given[c]=true ;; i) path=$OPTARG given[i]=true ;; :) echo "error: missing argument for option -$OPTARG" exit 1 ;; *) echo "error: unknown option: -$OPTARG" exit 1 ;; esac done # handle $x if [[ ! $x =~ ^[+-]?[[:digit:]]+$ ]]; then echo "error: your argument to -c is not an integer" exit 1 fi if ! ${given[c]}; then printf "using the default value: " fi echo $(( 10#$x + 1 )) # handle $path if ! ${given[i]}; then echo "error: missing mandatory option: -i path" exit 1 fi if ! [[ -f "$path" ]]; then echo "error: no such file: $path" exit 1 fi echo "size of '$path' is $(stat -c %s "$path")" ```
347857
I like the way Xfce works on top of Linux Mint 14 Nadia (Quantal) - but I also like LXDE that I want to have in parallel. Mint 14 has no LXDE "version" now, and that is too bad. I heard that installing multiple DE is not a problem. But ... problems may occur. After installing LXDE (and I am not sure this is the real cause of that), when I log in Xfce (which is the main "flavour" of my Linux Mint installation) all windows are missing the upper frame and buttons, and are stuck to the upper border of the screen. Alt-Tab would not work. Reinstalling Xfwm4 didn't help. LXDE behaves just fine - the Xfce session is useless. But all was perfect in Xfce until I installed LXDE and made 2 or 3 logout/login between the two DEs. Before doing something radical like reinstalling the system - any ideas?
The cause of this may be in a way related to LXDE but not directly: it is the Xfce's session manager that seems to be the real problem, and switching between different DE sessions might have triggered this. For some reason `xfwm4` does not start or does not work properly at the start of an Xfce session. Browsing the internet I found that for this and [other issues](https://unix.stackexchange.com/q/64775/32012) people recommend clearing session cache and setting **not** to save automatically the session at logout (source [here](http://forum.xfce.org/viewtopic.php?id=6042)). So, in Menu/Settings/Session and Startup: * under Session tab:"Clear saved sessions" * under General tab: uncheck "Automatically save session on logout"
348007
I'm creating a map editor for a little game project that I'm doing. Considering that the map editor isn't going to be intense, I simply used java 2d, which I hate. Anyways, here is my map.java, tile.java, and my TileList.java code. FIXED, I modified my TileList.java code (set function) to this: Alright, I fixed it: I simply changed the set(Tile tile) function! ``` public void set(Tile tile) { for(int i = 0; i < this.tileList.length; i++) { int x = this.tileList[i].getX(); int y = this.tileList[i].getY(); if((x == tile.getX()) && (y == tile.getY())) { System.out.println("Changing tile: (" + x + "," + y + ")" + " with (" + tile.getX() + "," + tile.getY() + ")"); this.tileList[i].setImage(tile.getImage()); } } } ``` Image showing error: <http://i.imgur.com/eosPt.png> map.java: ``` package org.naive.gui.impl; import org.naive.util.TileList; import javax.swing.JPanel; import java.util.HashMap; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Color; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.Rectangle; import java.util.Iterator; import java.util.LinkedList; /** * Copyright 2011 Fellixombc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Map extends JPanel implements MouseListener { private final int tileSize; private final int mapSize; private final int size; private TileList tileSet; private Tile currentTile = null; /* Creates the Map, e.g, Panel * @param int Desired size (in tiles) of the map */ public Map(int size, int tileSize) { this.tileSize = tileSize / 2; this.size = size; this.mapSize = (this.tileSize)*(size/2); this.tileSet = new TileList(size/2 * size/2); properties(); } /* Initlize the properties for the JPanel */ public void properties() { this.setPreferredSize(new Dimension(mapSize, mapSize)); this.addMouseListener(this); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D gfx = (Graphics2D) g; for(int i = 0; i < this.tileSet.size; i++) { Tile tile = this.tileSet.get(i); gfx.drawImage(tile.getImage(), tile.getX(), tile.getY(), null); } for(int i = 0; i <= size/2; i++) { gfx.setColor(Color.BLACK); gfx.drawLine(i * this.tileSize, 0, i * this.tileSize, this.tileSize * this.size/2); gfx.drawLine(0, i * this.tileSize, this.tileSize * this.size/2, i * this.tileSize); } } public void populate() { int i = 0; for(int x = 0; x < size/2; x++) { for(int y = 0; y < size/2; y++) { Tile tile = new Tile("grass.png"); tile.setPos(x * this.tileSize, y * this.tileSize); this.tileSet.setAtIndex(i, tile); i++; } } } /* Sets a new tile * @param tile The *new* tile to be set */ public void setTile(Tile tile) { if(this.currentTile != null) { tile.setPos(this.currentTile.getX(), this.currentTile.getY()); this.tileSet.set(tile); this.currentTile = tile; } this.repaint(); } /* Gets the tile closest* to the mouse click * @param int The x-axis location of the mouse click * @param2 int The y-axis location of the mouse click */ public void getTile(int x, int y) { for(int i = 0; i < this.tileSet.size; i++) { Tile tile = this.tileSet.get(i); int minX = tile.getX(); int minY = tile.getY(); int maxX = minX + this.tileSize; int maxY = minY + this.tileSize; if((x >= minX) && (x < maxX) && (y >= minY) && (y < maxY)) { this.currentTile = tile; System.out.println("Tile at: " + "(" + this.currentTile.getX() + "," + this.currentTile.getY() + ")"); } } } public void setTileSet(TileList tileSet) { this.tileSet = tileSet; } /* Gets the TileList, e.g, the tiles of the 'map' * @return hashmap Returns the list of tiles */ public TileList getTileSet() { return this.tileSet; } public int getMapSize() { return this.size; } public int getTileSize() { return this.tileSize * 2; } /* Gets where the mouse clicked on the canvas * @param mouseevent Where the mouse event occurred */ public void mouseClicked(MouseEvent e) { this.getTile(e.getX(), e.getY()); } /* Useless.. */ public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } ``` Tile.java ``` package org.naive.gui.impl; import javax.swing.ImageIcon; /** * Copyright 2011 Fellixombc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Tile extends ImageIcon { private int x = 0; private int y = 0; private final String sprite; public Tile(String sprite) { super("data/sprite/" + sprite); this.sprite = sprite; } public String getSprite() { return this.sprite; } public void setPos(int x, int y) { this.x = x; this.y = y; } public int getX() { return this.x; } public int getY() { return this.y; } } ``` TileList.java package org.naive.util; ``` import org.naive.gui.impl.Tile; import java.util.Iterator; /** * Copyright 2011 Fellixombc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TileList { public int size; private Tile[] tileList; public TileList(int size) { this.size = size; this.tileList = new Tile[size]; } public void setAtIndex(int index, Tile tile) { this.tileList[index] = tile; } public void set(Tile tile) { for(int i = 0; i < this.tileList.length; i++) { int x = this.tileList[i].getX(); int y = this.tileList[i].getY(); if((x == tile.getX()) && (y == tile.getY())) { System.out.println("Changing tile: (" + x + "," + y + ")" + " with (" + tile.getX() + "," + tile.getY() + ")"); this.tileList[i] = tile; } } } public Tile get(int index) { return this.tileList[index]; } } ```
Can you search for the element using the search bar at the top of the firebug window?
348013
Let's say I'm running a mill deck. I have some kind of infinite mill combo ready and available (e.g. [Semblance Anvil](http://gatherer.wizards.com/Pages/Search/Default.aspx?name=%2b%5bSemblance%20Anvil%5d) imprinting a creature, [Myr Retriever](http://gatherer.wizards.com/Pages/Search/Default.aspx?name=%2b%5bMyr%20Retriever%5d) and [Grinding Station](http://gatherer.wizards.com/Pages/Search/Default.aspx?name=%2b%5bGrinding%20Station%5d) - this lets me sacrifice Myr Retriever to Grinding Station, retrieve another Myr Retriever, mill opponent for 3 cards, and cast a new Myr Retriever for free). However my opponent has two copies of [Emrakul, the Aeons Torn](http://gatherer.wizards.com/Pages/Search/Default.aspx?name=%2b%5bEmrakul%2c%20the%20Aeons%20Torn%5d) in his deck. Since Emrakul shuffles back in to the deck each time it's put into the graveyard, this means I can't actually mill him out. However, through repeated use of the mill combo I can in principle 1) figure out every card in his deck, and then 2) mill him until the last three cards in his deck are Emrakul, Emrakul, and [irrelevant card] (I assume here the number of cards in opponent's deck before I start the mill combo is divisible by three). This means opponent must hard cast Emrakul to win, and I already know (e.g. via [Thoughtseize](http://gatherer.wizards.com/Pages/Search/Default.aspx?name=%2b%5bThoughtseize%5d)) that he doesn't have the resources to do this. So I win anyway by milling in three turns. This kill will take a long time to execute, for obvious reasons, because each time I mill an Emrakul it gets shuffled back into opponent's deck. I'll need the deck to be stacked in exactly such a way that the two Emrakuls + an irrelevant card are at the bottom of the deck. This will happen eventually, just probably not for a very long time. Question: can I actually execute this kill in paper, or will standoff rules kick in first?
You are not allowed to execute this entire combo, either using a shortcut or playing it out explicitly. You cannot execute this combo with a shortcut because of the way shortcuts are defined in rule 720.2a of the [Taking Shortcuts](https://mtg.gamepedia.com/Shortcut) rules section: > > At any point in the game, the player with priority may suggest a shortcut by describing a sequence of game choices, for all players, that may be legally taken based on the current game state and the predictable results of the sequence of choices. This sequence may be a non-repetitive series of choices, a loop that repeats a specified number of times, multiple loops, or nested loops, and may even cross multiple turns. **It can't include conditional actions, where the outcome of a game event determines the next action a player takes.** The ending point of this sequence must be a place where a player has priority, though it need not be the player proposing the shortcut. > > > In the combo you describe, you determine whether to continue or stop based on which cards, and how many, are still in the deck. That in turn depends on when exactly the Emrakuls got milled and their abilities triggered, which means that your actions would fundamentally depend on those game events, making this an invalid shortcut. You can see a ruling [here](http://magicjudge.tumblr.com/post/95707496529/if-i-have-assembled-a-combo-that-allows-me-to-scry) about a different combo that also involves an indeterminate amount of shuffling. You also cannot execute this combo without using a shortcut. A fundamentally identical combo exists in the deck Four Horsemen, which involves milling its own library including Emrakul in order to eventually end up with a particular sequence of cards in the graveyard and the library. [Previous rulings](https://blogs.magicjudges.org/telliott/2012/11/02/horsemyths/) have established that this combo is slow play and it should not be played in tournaments. The basic reason for this is that the combo can take unbounded time to complete, and every time you shuffle Emrakul in you are starting all over without making any meaningful progress.
348088
From UK-relevant results: 1. <http://careers.stackoverflow.com/jobs/8762/network-rail-graduate-programme-network-rail?campaign=List> 2. <http://careers.stackoverflow.com/jobs/9324/begin-a-career-in-consulting-now-accenture-uk?campaign=List> 3. <http://careers.stackoverflow.com/jobs/10410/immediate-graduate-opportunities-in-consulting-accenture-uk?campaign=List> Now, there are currently two pages of results for the UK, so I suppose 3/37 job results being total garbage isn't a massive issue as yet, but I have a request to make: Please, please, please can we not turn StackOverflow careers (or let become by inaction) any other recruitment site. This would be a horrendous waste of what StackOverflow has going for it. Reasons these job adverts suck in the context of a programming job board: 1. They're straight out of campus recruiting 101. I can't speak for other countries, but in the UK campus recruiting roughly consists of the marketing department going overboard and handing out things like "Work for company X! Live the dream!" and stuff from those posts like "working for us doesn't involve *desks* or *pointy haired bosses*, it's more like being on holiday. Like a journey. You will literally wake up every morning and crave being in your office. Your office is like an oasis of calm and yet full of passionate and exciting innovation, with the brightest minds!. I know you're getting that warm fuzzy feeling now. Don't worry we haven't told you what you'll be doing yet, sssh, all will be well."\* Whilst I don't doubt that some companies have created an amazing culture, this is a secondary concern. I'm more concerned with whether this job is likely to be a correct fit for my technical skills and/or offer me the ability to learn what I'm missing. 2. Lack of specifics. No tags, no Joel test thing, no nothing. 3. How to apply is a link to their graduate web pages. Spam spam spam. Sure, they used a person and a thesaurus rather than a [Markov Chain](http://en.wikipedia.org/wiki/Markov_chain#Markov_text_generators) to write it, but it is still spam. So, I shall make a few feature requests: 1. The search box is quite useful because it allows me to search within a specific tag, but why can't we do what stackoverflow does already and highlight in Glorious Orange (the future is bright with these jobs...) results matching tags we're interested in as per our profiles on either SO or careers. 2. Make that the default, allow users to disable it and allow searching on more detailed criteria. 3. Sort search results that way, so that stuff I want to see floats upwards. 4. Push downwards, hide and/or fade out anything that isn't tagged with a specific technology. So if you're using no tags, you get less visibility. 5. Push downwards, hide and/or fade out anything that hasn't bothered to complete the Joel test. 6. Make it all optional for searchers. 7. Make employers aware of the implications of these through their posting system with useful things like "you should add a tag to make your advert more relevant" and "please complete the Joel Test" with the appropriate pre-post warning of "you haven't complied. Please be aware some searchers will filter you out as a result." 8. Consider a rating system which is automatic. So employers who have a history of posting good job adverts that complete the Joel test and add tags etc get a slightly increased bonus, i.e. their results turn up higher, or they have to pay one unit of currency less, or whatever. In any case, give them a reward for investing time and effort in their recruitment. 9. Consider [doing this](https://meta.stackexchange.com/questions/80254/new-careers-feature-passive-candidate-search-feedback-wanted/80274#80274) or something like it, too. Again, give good employers/recruiting agencies their due for their effort and reward them with more system access, or a free Unicorn or something. 10. Allow users to ignore tags and employers. 11. In the UK at least I believe it is law to state "such and such is acting as a recruiting agency for this post". Can we have a box that allows companies to declare this and allow users to filter it out? I realise that's quite a lot of feature requests and I suppose the StackExchange network is more a priority for the newly formed StackExchange Inc but I think this is something you could also make great. And here's a good reason to do it: there's a **meta.unicornsrock.stackexchange.com** isn't there? So what if there was a **careers.unicornsrock.stackexchange.com** where relevant once the q&a site reaches a critical mass in the public stage? \*Clearly I should have gone into marketing. **tl;dr version:** Please can we provide some measures to encourage good recruiting on Careers?
Wow... Great post! You bring up lots of good points. Rather then responding to them one by one, I'll respond in broader strokes. I agree that tags and the Joel test make for better postings, yet I'd be hesitant to build a sorting algorithm out of them. Users should be able to determine what they want to look at rather than us determining that for them. But perhaps giving people the option to filter untagged / un-Joel-tested postings out is a good option. The same applies to graduate level postings. While they do not necessarily advertise a specific position, they will be useful to a subset of our user base. Again, maybe an option to allow users to filter them out would be of benefit. Ditto for recruiting agencies. And suddenly we have four more check boxes to fit in the search interface. While this is not necessarily a bad thing (in fact, I think it's a great idea to give users more control over what results they'll see), there's also something to be said for simplicity. We're going to have to think on this for a bit (same goes for other search modifiers you suggest). We've been throwing around the idea of applying some sort of rating system to job posts to aid advertisers in writing better postings for a while now, but haven't quite decided how we want to do this (and all sorts of other things like careers 2.0 kept coming in the way). It's still on the list of things we want to implement though. Thanks again for all suggestions, please keep them coming. And thanks for bearing with us while we work on deciding which ones to implement (and when).
348380
I did not find any way to set the access tier of a blob when I upload it, I know I can set a blob's access tier after I uploaded it, but I just want to know if I can upload the blob and set it's access tier in only one step. And if there is any golang API to do that? I googled it but I got nothing helpful till now. Here is what I did now, I mean upload it and then set it's access tier. ``` // Here's how to upload a blob. blobURL := containerURL.NewBlockBlobURL(fileName) ctx := context.Background() _, err = azblob.UploadBufferToBlockBlob(ctx, data, blobURL, azblob.UploadToBlockBlobOptions{}) handleErrors(err) //set tier _, err = blobURL.SetTier(ctx, azblob.AccessTierCool, azblob.LeaseAccessConditions{}) handleErrors(err) ``` But I want to upload a blob and set it's tier in one step, not two steps as I do now.
The short answer is No. According to the offical REST API reference, the blob operation you want is that to do via two REST APIs [`Put Blob`](https://learn.microsoft.com/en-us/rest/api/storageservices/put-blob) and [`Set Blob Tier`](https://learn.microsoft.com/en-us/rest/api/storageservices/set-blob-tier). Actually, all SDK APIs for different languages are implemented by wrapping the related REST APIs. Except for Page Blob, you can set the header `x-ms-access-tier` in your operation request to do your want, as below. [![enter image description here](https://i.stack.imgur.com/ycHwK.png)](https://i.stack.imgur.com/ycHwK.png) For Block Blob, the operations in two steps are necessary, and can not be merged.
348634
It seems impossible or very complicated to keep the original elements in webdriver of selenium after moving another page via a link generated by javascript. How can I do this? I'm trying to do web scraping for a particular web page using the following components: * Ubuntu 18.04.1 LTS * Python 3.6.1 * Selenium (Python package) 3.141.0 * Google Chrome 71.0.3578.98 * ChromeDriver 2.45.615279 The web page includes links which "href" is javascript function like the following: ``` <a href="javascript:funcName(10, 24, 100)"></a> ``` The definition of the function is something like this. ``` var funcName = function(arg1, arg2, arg3) { var url = 'XXXXXXXX' // dynamically generated using arguments var form = $('<form>', { name: 'formName', action: url, method: 'post' }); // Some procedure to enhance the form element with input arguments. form.submit() } ``` The above post request redirects me to another page which I'd like to scrape. The thing is the original web page includes many links and I'd like to scrape redirected pages one by one. However, it seems impossible to get the redirected page's url without actually clicking the link (<a>) as it's redirected by dynamically generated post request. On the other hand, if I click it and move to the redirected page, the elements I used for the original web page cannot be used anymore, so, after coming back to the original page, I need to get the next link from the beginning. This feels very redundant. Python code example ``` for a in driver.find_elements_by_css_selector(.some-class-name): a.click() # this redirects me to another page print(driver.current_url) # this shows the redirected page driver.back() print(driver.current_url). # this shows the original page # After coming back to the original page and when doing looping process, Python returns StaleElementReferenceException # because a is attached to the original page before redirected. ``` **What I did to keep the original page's elements but did not work:** 1.Copy a element (or driver) object ``` from copy import deepcopy for a in driver.find_elements_by_css_selector(.some-class-name): a2 = deepcopy(a) a2.click() # this redirects me to another page print(driver.current_url) # Expected result is that this remains the original web page, but didn't ``` I tried deepcopy for driver itself, but didn't work either. Returned error is ``` TypeError: can't pickle _thread.lock objects ``` 2.Open a redirected page in a new tab ``` from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys for a in driver.find_elements_by_css_selector(.some-class-name): action = ActionChains(driver) # Expected result is the following open the redirected page in a new tab, and CONTROL + TAB changes between tabs action.key_down(Keys.CONTROL).click(a).key_down(Keys.CONTROL).perform() driver.send_keys(Keys.CONTROL + Keys.TAB) ``` However, this didn't open a new tab, just move to the redirected page in the same tab. If there is no simple way, I will do this by creating a list or dictionary object to store which links I've already scraped, and every time after scraping redirected page, I'll parse the original page over again and skip the link that has already been checked. But I don't want to do because it's very redundant.
Even you return the same page, but selenium don't know it's the same page, selenium will treat it as an new page. The `links` found before the for loop is not belong to the new page. You need to find the links again on the new page and assign them to the same variable `links` inside for loop. Using index to iterate to next link. ``` links = driver.find_elements_by_css_selector(.some-class-name) for i in range(0, len(links)): links[i].click() # this redirects me to another page print(driver.current_url) # this shows the redirected page driver.back() print(driver.current_url). # Important: find the links again on the page back from redirected page # to resolve the StaleElementReferenceException. links = driver.find_elements_by_css_selector(.some-class-name) ```
348722
Using a Jetty web server, started from maven, which includes iBatis, Spring, Jersey, a little of this and a little of that, I get logging output with a host of formats. Some are from maven: ``` [INFO] [war:war] [INFO] Exploding webapp... ``` Some are from Jetty: ``` 2009-03-25 21:01:27.781::INFO: jetty-6.1.15 2009-03-25 21:01:28.218:/example:INFO: Initializing Spring root WebApplicationContext ``` Some are from Spring: ``` INFO ContextLoader - Root WebApplicationContext: initialization started (189) INFO XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml] (323) ``` Some are from Jersey: ``` Mar 25, 2009 9:01:29 PM com.sun.jersey.spi.spring.container.SpringComponentProviderFactory register ``` still others are from my code: ``` INFO ExampleApp - [User@14ef239 ...stuff] (69) ``` I expect they're all using standard logging packages (log4j, commons-logging, java-logging...) - Is it possible, and what is the easiest way to configure all of them to use the same format? - Is there any benefit to leaving them in varying formats?
This is possible using the logback library and its bridges. It basically consists to remove any log4j commons or alike jars from the classpath, stick logback jar file and bridges jars for log4j and alike. Spring, jersey and maven will use the bridge factories to instantiate loggers which in turn will use logbak producing unified logging. Check <http://logback.qos.ch/> and <http://www.slf4j.org/legacy.html> The key are the bridges which link other log utilities with a single global logger.
348963
I see lots of current accounts have switching bonuses - is there generally any limit to how soon after opening a new account you can switch and get these? More specifically: say I opened a current account like [this FirstDirect one](http://www1.firstdirect.com/1/2/banking/current-account?fd_msc=PCS0000003&WT.mc_id=FSDT_Aggregators_fdCurrentAccountsAggsQ32016_CUR_Textlink_DR_MSM_CurrentAccountLisiting%2525A3100-MSE_100_AG2383&mtp=agg) with a free £100 for using the Current Account Switch Service within 3 months, is there anything to stop me opening another account from another bank first (e.g. a basic current account with no credit checks), paying some money in then 'switching' within the 3 month period? I can't see anything against it in the T&C's, but I could have easily missed it. Context: I'm a UK student on placement year looking to open an account for my housemates and I to pay our rent and bills from, in my name only. £100 would be a sweet deal for us but I don't really want to get in trouble for it. I already have a student current account that I want to keep separate so would not be interested in closing it. Assume I'll pass credit checks etc.
No, to follow up on your example First Direct won't care (and I suspect won't even know) how long you held the account you are switching to them so if you don't want to switch your main current account to them you can just open a new one and switch that. To get the bonus you just need to make sure you meet the requirements imposed which in First Direct's case seem to simply be: 1. have not held a First Direct account before 2. pay in at least £1000 within 3 months of opening the account Once the First Direct bonus is paid, which they say should be within 28 days of you meeting the criteria, it is yours to keep. You are then free to close the First Direct account or transfer it on to another bank (and potentially claim another switching bonus).
349941
In my React native app I am using "react-navigation": "^3.11.0". I have top level bottomTabNavigator ```js const TabNavigator = createBottomTabNavigator({ Main: { screen: balanceStack, navigationOptions: { tabBarLabel: I18n.t("balanceTabLabel"), tabBarIcon: ({ tintColor}: {tintColor: string}) => ( <Icon name="home" style={{color: tintColor}} /> ) } }, ServicesStack: { screen: servicesStack, navigationOptions: { tabBarLabel: I18n.t("servicesTabLabel"), tabBarIcon: ({ tintColor}: {tintColor: string}) => ( <Icon name="list-box" style={{color: tintColor}} /> ) } }, }, { tabBarOptions: { activeTintColor: WHITE_COLOR, inactiveTintColor: WHITE_COLOR, style: { backgroundColor: PRIMARY_COLOR, } }, backBehavior: 'history', swipeEnabled: true, }); ``` And stack navigators for each tab: ```js const balanceStack = createStackNavigator({ Balance: { screen: MainScreen, }, FullBalance: { screen: FullBalanceScreen, }, Payment: { screen: PaymentScreen, }, ServiceView: { screen: ViewServiceScreen, }, }, { initialRouteName: 'Balance', headerMode: 'none', }); const servicesStack = createStackNavigator({ AllServices: { screen: AllServicesScreen, }, ServiceView: { screen: ViewServiceScreen, }, ServiceOptionAction: { screen: ServiceOptionsActionScreen, } }, { initialRouteName: 'AllServices', headerMode: 'none', }); ``` I want that my navigation for all tabs will be common, not divided per stack. For example when I navigate Balance->FullBalanceScreen->AllServices(by clicking Services tab)->ServiceView If I click back button (call goBack()) one time I will back to AllServices. But if I click back second time, I don't navigate to FullBalanceScreen, because it's in another stack. How can I do this?
``` private JLabel gameArea; ``` A JLabel does NOT have a method runGame(). Your code should be: ``` private GameArea gameArea; ``` Then you will be able to use `gameArea.runGame()`. But the real question is why are you even doing this? You can just invoke `setText(...)` on the label to change the text. There is no need to create a custom class with a custom method.
350381
**Request description:**. I want disable jaeger client remoteReporter, I don't nee send to agent, Because istio would make it. **Tried:**. Add `quarkus.jaeger.sender-factory` prop in my application.properties but I not has lucky, and can't find when use this prop in source code. **env infomation:** java version: 1.8. quarkus version: 1.13.2.Final **example project**. [GitLab link](https://gitlab.com/luciferstut/opentracing-quickstart)
It seems like `io.jaegertracing.internal.senders.SenderResolver` which determines the Sender to use is pretty broken, which is why `quarkus.jaeger.sender-factory` isn't being taken into account. One way to achieve what you want is to add a service loader file, i.e. add a file named `resources/META-INF/services/io.jaegertracing.spi.SenderFactory` that contains this single line: `io.jaegertracing.internal.senders.NoopSenderFactory`
351559
I'm using *`virtualenv`* and I need to install "psycopg2". I have done the following: ``` pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160 ``` And I have the following messages: ``` Downloading/unpacking http://pypi.python.org/packages/source/p/psycopg2/psycopg2 -2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160 Downloading psycopg2-2.4.tar.gz (607Kb): 607Kb downloaded Running setup.py egg_info for package from http://pypi.python.org/packages/sou rce/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160 Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info\psycopg2.egg-info writing pip-egg-info\psycopg2.egg-info\PKG-INFO writing top-level names to pip-egg-info\psycopg2.egg-info\top_level.txt writing dependency_links to pip-egg-info\psycopg2.egg-info\dependency_links.txt writing manifest file 'pip-egg-info\psycopg2.egg-info\SOURCES.txt' warning: manifest_maker: standard file '-c' not found Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- Command python setup.py egg_info failed with error code 1 Storing complete log in C:\Documents and Settings\anlopes\Application Data\pip\p ip.log ``` My question, I only need to do this to get the psycopg2 working? ``` python setup.py build_ext --pg-config /path/to/pg_config build ... ```
If you using Mac OS, you should install PostgreSQL from source. After installation is finished, you need to add this path using: ``` export PATH=/local/pgsql/bin:$PATH ``` or you can append the path like this: ``` export PATH=.../:usr/local/pgsql/bin ``` in your `.profile` file or `.zshrc` file. This maybe vary by operating system. You can follow the installation process from <http://www.thegeekstuff.com/2009/04/linux-postgresql-install-and-configure-from-source/>
351610
I've posted this question in the MS forums, but the only response (create a macro and extrapolate from the VBA code) didn't help. The only vague hint I got was to use TickLabelPosition -- which apparently is something only useful if you're using VB, and I'm using C# What I'm trying to do SHOULD be the most simple and common thing in the world: I just want to move the X Axes label to the bottom of the chart. How hard could that be? Well, I'll admit I'm not overly experienced in either C# or the Excel interop, but currently it seems impossible. I am writing a C# program (VS2010) to create Excel spreadsheets from imported data. I have no problem actually creating the spread sheet with all the correct data and ranges. What I CANNOT figure out is how to move the label for the X Axis. It's got to be something simple that I'm missing, but the thing always appears right at the zero line and since my values go negative, that means it's right in the middle of the chart. Now I can get the thing to where I want it to be if I use a template, but I don't want to do that. Here is a code snippit: ``` const string topLeft = "A9"; const string bottomRight = "B18"; const string graphTitle = "Graph Title"; const string xAxis = "Time"; const string yAxis = "Value"; string chartTabName; var range = workSheet.get_Range(topLeft, bottomRight); // Add chart. var charts = workSheet.ChartObjects() as Microsoft.Office.Interop.Excel.ChartObjects; var chartObject = charts.Add(20, 20, 750, 500) as Microsoft.Office.Interop.Excel.ChartObject; var chart = chartObject.Chart; // Set chart range. chart.SetSourceData(range); chart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlXYScatterSmooth; ``` // chart.ApplyChartTemplate(@"Chart1.crtx"); (<- template) ``` chart.ChartWizard(Source: range, Title: graphTitle, CategoryTitle: xAxis, ValueTitle: yAxis); ``` Using this puts the Horizontal Value axis in the middle of the chart, since the x axis goes negative. Now I can move this MANUALLY, or by using a chart template (as I did), but that's not the best plan. The best plan would be to move it programmatically, but I can't find a way to do it. I can find a way to move the LEGEND (chart.Legend) but not the Value. Thanks for any help.
ALthough it's completely undocumented, this command will work: chart.Axes(2).CrossesAt = chart.Axes(2).MinimumScale;
351764
Simply prefixes a # to the field name I am using Laravel Breeze, which by default sets the `password` and `remember_token` fields to hidden. ``` class User extends Authenticatable { use HasFactory, Notifiable; protected $fillable = [ 'username', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; protected $casts = [ 'email_verified_at' => 'datetime', ]; } ``` However if I fetch a User instance running `User::inRandomerOrder()->first()` inside Tinker I am still able to see these supposed hidden fields. ``` App\Models\User {#4440 id: 14, username: "verdie10", email: "jerrold.ziemann@example.org", email_verified_at: "2021-08-31 11:19:47", #password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", #remember_token: "F87k6RPxgi", created_at: "2021-08-31 11:19:47", updated_at: "2021-08-31 11:19:47", }, ```
That's because these fields are only hidden when you convert your model to array or JSON. From the documentation: > > Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. > > > The whole documentation about this topic is available here: <https://laravel.com/docs/8.x/eloquent-serialization#hiding-attributes-from-json> The goal is to remove them from your API responses. However, you might still use them when you are working with your models in controllers, services... that's why you see them. You can check it works by doing: ```php $user = User::first(); $user->toArray(); // hidden attributes not included $user->toJson(); // hidden attributes not included ```
351955
MAJOR EDIT: Reframing question as this might be easier to solve... I am trying to generate JSON microdata using PHP code in Wordpress. I'm currently using the foreach() method to cycle through a list of posts on a page, put their thumbnail, title and link data into an array, and I'll later encode that array into JSON microdata. However, the array I've assembled using foreach() doesn't output the data how I want. I've spent hours trying to get this section of data to output correctly, but to no avail. -- What I want to achieve (using print\_r() to view and test my PHP code) - e.g. Instead of index numbers like `[0]`. `[1]` etc., I want each array to output `[associatedMedia]` instead as below: ``` Array ( [associatedMedia] => Array ( [image] => http://www.website.com/thumbnail.jpg [name] => post title [url] => http://www.website.com/the-post ) [associatedMedia] => Array ( [image] => http://www.website.com/second-thumbnail.jpg [name] => second post title [url] => http://www.website.com/the-second-post ) // And so on... ) ``` My current result: ``` Array ( [0] => Array ( [image] => http://www.website.com/first-thumbnail.jpg [name] => first post title [url] => http://www.website.com/the-post-one ) [1] => Array ( [image] => http://www.website.com/second-thumbnail.jpg [name] => second post title [url] => http://www.website.com/the-post-two ) [2] => Array ( [image] => http://www.website.com/third-thumbnail.jpg [name] => third post title [url] => http://www.website.com/the-post-three ) // And so on... ) ``` My foreach method: ``` // other PHP code global $post; global $wp_query; $category = $wp_query->get_queried_object(); $args = array( 'category' => $category->cat_ID ); $posts = get_posts( $args ); $post_details = array(); $i = 0; foreach( $posts as $post ) { setup_postdata($post); $thumb_url = wp_get_attachment_image_src( get_post_thumbnail_id(),'thumbnail' ); $post_thumbnails['image'] = $thumb_url[0]; $post_titles['name'] = get_the_title(); $post_links['url'] = get_permalink(); $post_details[$i]['image'] = $post_thumbnails['image']; $post_details[$i]['name'] = $post_titles['name']; $post_details[$i]['url'] = $post_links['url']; $i++; }; wp_reset_postdata(); print_r($post_details); ``` I'm only beginning to get into more advanced programming, and I'm sure my code above will look crude. So any help or tips on how I can shorten it would be appreciated. EDIT: More `$post` related code added
Use this ``` $array_details['associatedMedia'][$i] = $post_details[$i]; ``` instead of ``` $array_details['associatedMedia'] = $post_details[$i]; ``` **Update :** Keys of array elements should be unique. Use any of the below format to get the desired results. ``` foreach( $posts as $post ) { .... $array_details['associatedMedia'][$i] = $post_details[$i]; i++; } ``` Results : ``` Array ( ['associatedMedia'] => Array( [0] => Array( [image] => http://www.website.com/first-thumbnail.jpg [name] => first post title [url] => http://www.website.com/the-post-one ) [1] => Array( [image] => http://www.website.com/second-thumbnail.jpg [name] => second post title [url] => http://www.website.com/the-post-two ) [2] => Array( [image] => http://www.website.com/third-thumbnail.jpg [name] => third post title [url] => http://www.website.com/the-post-three ) // And so on... ) ) ``` OR ``` foreach( $posts as $post ) { .... $array_details[$i]['associatedMedia']= $post_details[$i]; i++; } ``` Results : ``` Array ( [0] => Array( ['associatedMedia'] => Array( [image] => http://www.website.com/first-thumbnail.jpg [name] => first post title [url] => http://www.website.com/the-post-one ) ) [1] => Array( ['associatedMedia'] => Array( [image] => http://www.website.com/second-thumbnail.jpg [name] => second post title [url] => http://www.website.com/the-post-two ) ) [2] => Array( ['associatedMedia'] => Array( [image] => http://www.website.com/third-thumbnail.jpg [name] => third post title [url] => http://www.website.com/the-post-three ) ) // And so on... ) ```
352524
First of all I'm playing with Retrofit for the first time in Kotlin Android. **So the Logic i want is like this:** 1. I want send a **username** to the Rest API. 2. Then check if it is exists or not. 3. if it exists I want to make a Toast message saying **true** if it does not exist **False**. So, I have this JSON in this URL:`https://jsonplaceholder.typicode.com/users`: ``` [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz" }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv" }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "Nathan@yesenia.net" } ] ``` So let me walk through the content of my code using Retrofit **Model.class** ``` class FakeUserModel { @Expose @SerializedName("username") val username: String = "" } ``` **Retrofit Api Client** class ``` object FakeUserApiClient { var BASE_URL:String="https://jsonplaceholder.typicode.com/" val getFakeUserClient: ApiInterface get() { val gson = GsonBuilder() .setLenient() .create() val interceptor = HttpLoggingInterceptor() interceptor.setLevel(HttpLoggingInterceptor.Level.BODY) val client = OkHttpClient.Builder() .addInterceptor(interceptor) .build() val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create(gson)) .build() return retrofit.create(ApiInterface::class.java) } } ``` And this ApiInterface to demonstrate the fucntion to you are using to send data to the server: **Api Interface** ``` interface ApiInterface { @FormUrlEncoded @POST("users") fun check( @Field("username") username:String ): Call<FakeUserModel> } ``` So finally, in the Activity I want to receive the response telling me if it exists or not... **Activity class** ``` checkButton.setOnClickListener { val username = userName.text.toString().trim() FakeUserApiClient.getFakeUserClient.check(username) .enqueue(object : Callback<FakeUserModel>{ override fun onFailure(call: retrofit2.Call<FakeUserModel>, t: Throwable) { Toast.makeText(applicationContext, t.message, Toast.LENGTH_LONG).show() } override fun onResponse( call: retrofit2.Call<FakeUserModel>, response: Response<FakeUserModel> ) { if (response != null) { Toast.makeText(applicationContext, "true", Toast.LENGTH_LONG).show() }else{ Toast.makeText(applicationContext, "false", Toast.LENGTH_LONG).show() } } }) } ``` When I execute the app it always saying `true`, even if the username I have passed is not on the JSON... So, guys is there a problem in my code? What did I missed? Is there a better way to do it? Thanks!
Change this ApiInterface ``` interface ApiInterface { @GET("users") fun check( @Query("username") username: String ): Call<FakeUserModel> } ``` When username is present you will get response like below Url - <https://jsonplaceholder.typicode.com/users?username=Bret> ``` [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ] ``` When user name is not Present you will get empty response Url - <https://jsonplaceholder.typicode.com/users?username=Bre> ``` [] ```
352889
Why I can not access my variable `p` in `mull` class's `iterate` method? ``` public class mull { public static void main(String[] args) throws InterruptedException { final JPanel p = createAndShowGUI(); Timer timer = new Timer(1000, new MyTimerActionListener()); timer.start(); try { Thread.sleep(10000); } catch (InterruptedException e) { } timer.stop(); public static void iterate(){ for (int i = 0; i < 55; i++){ // "p cannot be resolved" p.moveSquare(i*10, i*10); p.setParamsRing(i*5, i*7, 200, 200); } } } class MyPanel extends JPanel { .... } ``` Why does Eclipse force me to use this: ``` ((MyPanel) p).setParamsRing(i*5, i*7, 200, 200); ``` instead of: ``` p.setParamsRing(i*5, i*7, 200, 200); ``` ?
Declare `p` as a static field to the class: ``` private static JPanel p; ```
353292
i want dynamically create ascx files, to partial render them. but as i know, ot show them , i at least need dummy method: ``` public ActionResult test() { return PartialView(); } ``` how can i create this method for each new ascx file? upd: i need factory?
you might find the following questions to be of use: [What are some good resources for learning about Artificial Neural Networks?](https://stackoverflow.com/questions/478947/what-are-some-good-resources-for-learning-about-neural-networks) [Open-source .NET neural network library?](https://stackoverflow.com/questions/1549811/open-source-net-neural-network-library) [Looking for a Good Reference on Neural Networks](https://stackoverflow.com/questions/604078/looking-for-a-good-reference-on-neural-networks) also you can find two examples of a neural network in this article which also has source code availible: <http://www.codeproject.com/KB/recipes/aforge_neuro.aspx> if these are not helpful then please make your question more specific
353583
I am trying to make a program that sends a message after a user makes a choice, but after the choice is made then it just closes cmd. Here's the program. ``` @echo off title Get A Life cd C: :menu cls echo I take no responsibility for your actions. Beyond this point it is you that has the power to kill yourself. If you press ‘x’ then your PC will be formatted. Do not cry if you loose your data or anything. pause echo Pick your option: echo 1. Die slowly echo 2. Instant Death echo 3. Stay Away From This One echo 4. Die this way (For Wimps!) echo 5. Easy way out set input=nothing set /p input=Choice: if %input%=1 then msg * Your computer will now sutdown else GOTO END if %input%=2 then msg * Your hard drive will now be formatted else GOTO END if %input%=3 then msg * FINE! JUST PICK THE MIDDLE ONE! else GOTO end if %input%=4 then msg * Can you guess what happens next? else GOTO END if %input%=5 then START %documents%/%Personal Projects%/Cool trick.bat :END ```
well i tried a few ways to see the possibilities on how to inputs through different objects and i explored it in 4 different ways ``` public String input1() { System.out.println("enter the input"); Scanner sc=new Scanner(System.in); String s1=sc.nextLine(); return s1; } public String input2()throws IOError { Console c=System.console(); String s2=null; s2=c.readLine("enter the value"); return s2; } public String input3() { System.out.println("enter the input"); String s3=javax.swing.JOptionPane.showInputDialog("enter the text"); return s3; } public String input4()throws Exception { System.out.println("enter the input"); InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); String s4=br.readLine(); return s4; } ``` if i come across anymore i'll be sure to list it down here
353672
I am currently struggling with a mathematical problem and can't seem to get it solved. I have a bunch of rotated rectangular polygons (solution should also work for non-rectangular polygons) in different shapefiles. I want to (automatically) find the lower left corner of each of the polygons using python (arcpy). First I tried to simply use the extent, but since they are rotated, the extent will bring false results. So how do I approach this? I googled for hours and the only thing I could come up with, is to somehow calculate the center of the polygon or somehow temporairly rotate it to 180 degrees and then use xmin and ymin. Here are a few pictures which may help to distract the attention from my bad english (sorry for that btw) [![enter image description here](https://i.stack.imgur.com/4sq03.jpg)](https://i.stack.imgur.com/4sq03.jpg) [![enter image description here](https://i.stack.imgur.com/e6SU3.jpg)](https://i.stack.imgur.com/e6SU3.jpg) I had no problems exporting the coordinates of the polygons by using the feature vertices to points tool. So far I extracted them once in a list of tupels and once in two different lists (one for x-coords and one for y-coords) so here are a few coordinates to make it easier to test: **tupel-format:** ``` tupelList=[[1792398.680577231, 4782539.85121522], [1792173.0363913027, 4780368.293228334], [1788935.7990357098, 4780713.732859781], [1789162.9530321995, 4782885.332685629], [1792398.680577231, 4782539.85121522]] ``` **x-list/y-list format:** ``` xList= [1792398.680577231, 1792173.0363913027, 1788935.7990357098, 1789162.9530321995, 1792398.680577231] yList=[4782539.85121522, 4780368.293228334, 4780713.732859781, 4782885.332685629, 4782539.85121522] ``` I am currently using ArcGIS 10.3.1 width ally extensions and an advanced license. Version of Python is 2.7.something
Here's a very simple approach that offloads all the processing into the [Sort](http://desktop.arcgis.com/en/desktop/latest/tools/data-management-toolbox/sort.htm#GUID-26359B3D-A0C8-4666-B99B-40C8B4D91449) GP tool. Since you have access to an Advanced license, sorting by shape and starting at the lower left corner gives quick results. ```py import os, arcpy arcpy.env.overwriteOutput = True inFC = r'<path>' outFC = r'<path>' # create output FC to hold points and field to link OID spatref = arcpy.Describe(inFC).spatialReference arcpy.CreateFeatureclass_management(*os.path.split(outFC), geometry_type="POINT", spatial_reference=spatref) arcpy.AddField_management(outFC, "ID", "LONG") with arcpy.da.SearchCursor(inFC, ["OID@", "SHAPE@"]) as sCursor: with arcpy.da.InsertCursor(outFC, ["ID", "SHAPE@"]) as iCursor: for oid, poly in sCursor: # using Geometry objects is very quick and also has the added # benefit of returning lists of geometries # Since we are sorting the vertices by LL, the first one is the answer verts = arcpy.FeatureVerticesToPoints_management(poly, arcpy.Geometry()) sort = arcpy.Sort_management(verts, arcpy.Geometry(), [["SHAPE", "ASCENDING"]], "LL")[0] iCursor.insertRow([oid, sort]) ``` [![enter image description here](https://i.stack.imgur.com/sL6Vk.png)](https://i.stack.imgur.com/sL6Vk.png) From the explanation on [spatial sorting](http://desktop.arcgis.com/en/desktop/latest/tools/data-management-toolbox/how-sort-works.htm), we see that N/S takes precedence over E/W: > > Note that U gets priority over R. R is taken into considerations only > when some features are at the same horizontal level. > > >
354252
I have a strange problem with mysql count. When I execute ``` SELECT a.inc AS inc, a.cls AS cls, a.ord AS ord, a.fam AS fam, a.subfam AS subfam, a.gen AS gen, aspec AS spec, asubspec AS subspec FROM a WHERE (ainc = 11) ``` I obtain: ![](https://farm9.staticflickr.com/8034/7946322494_c696399c1c.jpg) and that's ok, because I have 2 records. When I execute ``` SELECT COUNT(DISTINCT a.inc) AS inc, COUNT(DISTINCT a.cls) AS cls, COUNT(DISTINCT a.ord) AS ord, COUNT(DISTINCT a.fam) AS fam, COUNT(DISTINCT asubfam) AS subfam, COUNT(DISTINCT a.gen) AS gen, COUNT(DISTINCT a.spec) AS spec, COUNT(DISTINCT a.subspec) AS subspec FROM a WHERE (a.inc = 11) GROUP BY a.inc ``` I obtain ![](https://farm9.staticflickr.com/8319/7946322558_0886cbf733.jpg) and that's odd because as you see `gen, spec and subspec` have 0 value on one row. I know that `count distinct` doesn't count zero values. I want to count all value != 0 and after count distinct I want to get ``` `1 | 2 | 2 | 2 | 2 | 1 | 1 | 1 |` ``` I also try: ``` SELECT COUNT(DISTINCT a.inc) AS inc, SUM(if(a.cls <> 0, 1, 0)) AS cls, SUM(if(a.ord <> 0, 1, 0)) AS ord, SUM(if(a.fam <> 0, 1, 0)) AS fam, SUM(if(a.subfam <> 0, 1, 0)) AS subfam, SUM(if(a.gen <> 0, 1, 0)) AS gen, SUM(if(a.spec <> 0, 1, 0)) AS spec, SUM(if(a.subspec <> 0, 1, 0)) AS subspec FROM a GROUP BY a.inc ``` and ``` SELECT COUNT(DISTINCT a.inc) AS inc, SUM(DISTINCT if(a.cls <> 0, 1, 0)) AS cls, SUM(DISTINCT if(a.ord <> 0, 1, 0)) AS ord, SUM(DISTINCT if(a.fam <> 0, 1, 0)) AS fam, SUM(DISTINCT if(a.subfam <> 0, 1, 0)) AS subfam, SUM(DISTINCT if(a.gen <> 0, 1, 0)) AS gen, SUM(DISTINCT if(a.spec <> 0, 1, 0)) AS spec, SUM(DISTINCT if(a.subspec <> 0, 1, 0)) AS subspec FROM a GROUP BY a.inc ``` but it's not working because in first approach doesn't make distinct and sum all duplicate values greater than 0; and in second case it give just 1 and 0 . So, can someone help me with that? Thank you in advance. Leo
> > I know that count distinct doesn't count zero values. > > > I don't know where you got that idea, but it is not correct. Perhaps you are thinking of NULL values? One way to get the results you desire is to treat the 0s as NULL in your distinct count. Try something like this (I also removed the group by, which was not helping): ``` SELECT COUNT(DISTINCT case when a.inc = 0 then null else a.inc end) AS inc, COUNT(DISTINCT case when a.cls = 0 then null else a.cls end) AS cls, COUNT(DISTINCT case when a.ord = 0 then null else a.ord end) AS ord, COUNT(DISTINCT case when a.fam = 0 then null else a.fam end) AS fam, COUNT(DISTINCT case when a.subfam = 0 then null else a.subfam end) AS subfam, COUNT(DISTINCT case when a.gen = 0 then null else a.gen end) AS gen, COUNT(DISTINCT case when a.spec = 0 then null else a.spec end) AS spec, COUNT(DISTINCT case when a.subspec = 0 then null else a.subspec end) AS subspec FROM a WHERE (a.inc = 11) ```
354314
I am putting together a build system for my Qt app using a qmake .pro file that uses the 'subdirs' template. This works fine, and allows me to specify the order that each target is built, so dependencies work nicely. However, I have now added a tool to the project that generates a version number (containing the build date, SVN revision, etc,) that is used by the main app - I can build this version tool first but when it is built I want to execute it before any more targets are built (it generates a header file containing the version number that the main app includes.) For example, my simple qmake file looks like something this: ``` TEMPLATE = subdirs CONFIG += ordered SUBDIRS = version \ lib \ tests \ mainapp ``` When 'version' is built I want to execute it (passing some arguments on the command-line) before 'lib' is built. Does anyone know if this is possible? I see that qmake has a 'system' command that can execute apps, but I don't know how I could leverage this. A related question concerns my unit tests. These live in the 'test' project and use the QTest framework. I want to execute the tests exe before building 'mainapp' and if the tests fail (i.e. the tests exe doesn't return zero) I want to quit the build process. I realise that qmake is designed to generate makefiles, so I may be wishing for a little too much here but if anyone can give me some pointers it would be very welcome.
I currently use qmake to exec my unit tests automatically for two years - and it works fine. Have a look here - I made a mini-howto for that: [Qt: Automated Unit Tests with QMAKE](http://www.3dh.de/?p=97) Abridged summary: ================= --- Structure --------- ```none /myproject/ myproject.h myproject.cpp main.cpp myproject.pro /myproject/tests/ MyUnitTest.h MyUnitTest.cpp main.cpp tests.pro ``` Using QMake to automatically run unit tests on build ---------------------------------------------------- The QMake target QMAKE\_POST\_LINK will run a user defined command after linking. **tests.pri (common file)** ```none TEMPLATE = app DEPENDPATH += . ../ INCLUDEPATH += . ../ DESTDIR = ./ CONFIG += qtestlib unix:QMAKE_POST_LINK=./$$TARGET win32:QMAKE_POST_LINK=$${TARGET}.exe ``` **tests.pro (project-specific file)** ```none TARGET = MyUnitTest HEADERS += MyUnitTest.h SOURCES += MyUnitTest.cpp main.cpp include(tests.pri) ``` Running multiple unit tests in a single main() ---------------------------------------------- **main.cpp** ``` #include "MyUnitTest1.h" #include "MyUnitTest2.h" int main(int argc, char** argv) { QApplication app(argc, argv); int retval(0); retval +=QTest::qExec(&MyTest1(), argc, argv); retval +=QTest::qExec(&MyTest2(), argc, argv); return (retval ? 1 : 0); } ``` This runs your tests on each build and aborts if an error is found. Note ---- If you get linker errors such as "LNK2005: xxx already defined...", add a new .cpp file for each test class header and move some test method implementations. --- You can use exactly that mechanism to exec your versioning tool after compile/building - so your questions should be solved :-) If you have any further questions don't hesitate to ask me. PS: Here you can find more (undocumented) tricks around QMake: [Undocumented QMake](http://wiki.qtcentre.org/index.php?title=Undocumented_qmake)
354433
I have used `Lehigh University Benchmark` (LUBM) to test my application. What I know about `LUBM` is that its ontology contains 43 classes. But when I query over the classes I got 14 classes! Also, when I used Sesame workbench and check the "Types in Repository " section I got 14th classes which are: ``` AssistantProfessor AssociateProfessor Course Department Fullprofessor GraduateCourse GraduateStudent Lecturer Publication ResearchAssistant ResearchGroup TeachingAssistant UndergraduateStudent University ``` Could any one explain to me the differences between them? Edit: Problem partially solved but now How can I retrieve RDF instances from the upper level of Ontology (e.g. Employee, book, Article, Chair, college, Director, PostDoc, JournalArticle ..etc) or let's say all 43 classes because I can just retrieve instances for the lower classes (14th classes) and the following picture for retrieving the instances from ub:Department ![enter image description here](https://i.stack.imgur.com/dEANj.png)
From what you have said I don't think you are doing anything wrong with respect to using Telerik controls. However please try the following; 1. Remove all the middle 'html' in between the 2 controls and try 2. Render the page in Chrome and check the console for any rendering issues 3. Check the rendered Html to verify that the 2 controls are indeed not rendered. May be they are rendered but you don't see them in the browser for some reason I have tried rendering a page similar to yours and both methods @() and @{} did work for me and here's the code ``` @{ Html.Telerik().Window() .Name("Window1") .Content("<h1>Window1</h1>") .Draggable(true) .Render(); } <span>Here is the middle html</span> @{ Html.Telerik().TabStrip() .Name("TabStrip1") .Items(items => { items.Add().Content("<h1>Tab 1</h1>").Text("Tab 1").Visible(true); items.Add().Content("<h1>Tab 2</h1>").Text("Tab 2"); items.Add().Content("<h1>Tab 3</h1>").Text("Tab 3"); }) .Render(); } ``` Here's the @() way; ``` @( Html.Telerik().Window() .Name("Window2") .Content("<h1>Window2</h1>") .Draggable(true) ) <span>Here is the middle html</span> @( Html.Telerik().TabStrip() .Name("TabStrip2") .Items(items => { items.Add().Content("<h1>Tab 1</h1>").Text("Tab 1").Visible(true); items.Add().Content("<h1>Tab 2</h1>").Text("Tab 2"); items.Add().Content("<h1>Tab 3</h1>").Text("Tab 3"); }) ) ```
355489
A subset $X$ of $\mathbb{N}^n$ is *linear* if it is in the form: $u\_0 + \langle u\_1,...,u\_m \rangle = \{ u\_0 + t\_1 u\_1 + ... + t\_m u\_m \mid t\_1,...,t\_n \in \mathbb{N}\}$ for some $u\_0,...,u\_m \in \mathbb{N}^n$ $X$ is *semilinear* if it is the union of finitely many linear subsets. > > What are the techniques used to prove that a set is not semilinear (or is semilinear)? > > > For example I would like to know/prove if the following subset is not semilinear: $X = \{ \langle x, y\_1, y\_2, z\_1, z\_2, w \rangle \}$ in which: ($x \geq y\_1+y\_2 +z\_1+z\_2+w$) OR ($w \geq x + y\_1+y\_2 +z\_1+z\_2$) OR ($x+y\_1 = y\_2+z\_1 +z\_2+w$ AND $x\neq y\_2$ AND $y\_1 \neq w$) OR ($x + y\_1 + y\_2 + z\_1 = z\_2 +w$ AND $x \neq z\_2$ AND $z\_1 \neq w$) > > Any suggestions? > > >
$A\_n$ is normal in $S\_n$ and $S\_n / A\_n$ is the group of order 2. The kernel of the quotient map $\theta : S\_n \longrightarrow S\_n / A\_n$ is $A\_n$. So under $\theta$, $S\_n \setminus A\_n$ maps to the element of order 2 in $S\_n / A\_n$. Hence every element in $S\_n \setminus A\_n$ must have even order.
356174
This is my current `.htaccess` file: ``` RewriteEngine on # remove trailing slash RewriteRule (.*)(/|\\)$ $1 [R] # everything RewriteRule ^(.*?)$ /handler.php?url=$1 [L,QSA] ``` However, this doesn't work, it throws a `500 Internal Server Error` My previous `.htaccess` file looked like this: ``` RewriteEngine on # remove trailing slash RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*)(/|\\)$ $1 [R] # everything RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*?)$ /handler.php?url=$1 [L,QSA] ``` And it worked, except for specific files. However, now I'd like the specific files to redirect into the handler as well. Is there a way to use `RewriteRule`s without the `RewriteCond`s?
The error is saying that your project depends on google\_Play\_Service\_Lib and android studio is not able to find that dependency, but what android studio did is giving you the path where you can paste that library and then you will able to import that project. first download google\_service\_lib from <https://github.com/aporter/coursera-android/tree/master/Examples/google-play-services_lib> or <https://github.com/MobileChromeApps/google-play-services> and now paste that in E:\android\CFPEvents\cfp-android-user now again import..
356690
I'm looking at [TensorFlow implementation of ORC on CIFAR-10](https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10.py), and I noticed that after the first convnet layer, they do pooling, then normalization, but after the second layer, they do normalization, then pooling. I'm just wondering what would be the rationale behind this, and any tips on when/why we should choose to do norm before pool would be greatly appreciated. Thanks!
It should be pooling first, normalization second. The original code link in the question no longer works, but I'm assuming the normalization being referred to is batch normalization. Though, the main idea will probably apply to other normalization as well. As noted by the batch normalization authors in [the paper introducing batch normalization](https://arxiv.org/pdf/1502.03167.pdf), one of the main purposes is "normalizing layer inputs". The simplified version of the idea being: if the inputs to each layer have a nice, reliable distribution of values, the network can train more easily. Putting the normalization second allows for this to happen. As a concrete example, we can consider the activations `[0, 99, 99, 100]`. To keep things simple, a 0-1 normalization will be used. A max pooling with kernel 2 will be used. If the values are first normalized, we get `[0, 0.99, 0.99, 1]`. Then pooling gives `[0.99, 1]`. This does not provide the nice distribution of inputs to the next layer. If we instead pool first, we get `[99, 100]`. Then normalizing gives `[0, 1]`. Which means we can then control the distribution of the inputs to the next layer to be what we want them to be to best promote training.
357073
I am learning AWS CloudFormation. Now, I am trying to create a template for VPC and Subnets. I am now creating a VPC. This is my template: ``` AWSTemplateFormatVersion: '2010-09-09' Description: "Template for Networks and IAM Roles" Resources: Vpc: Type: AWS::EC2::VPC Properties: CidrBlock: '10.0.0.0/16' EnableDnsHostnames: True EnableDnsSupport: True ``` What I don't understand here is that CidrBlock. Now, I specified it as, 10.0.0.0/16. To be honest, how does it work exactly. Is setting it as 10.0.0.0/16 always going to work? What is that for? How does that IP address range work exactly? How does it help? How can I determine which value to set for it? Is there a formula to calculate it? How? I saw an existing VPC in my console. The IP address is different. Also, how can I calculate to split it to assign to subnets? I am seeking an understanding of the following template, especially Cidr for subnets. ``` AWSTemplateFormatVersion: '2010-09-09' Description: "Template for Networks and IAM Roles" Parameters: VpcCidr: Default: '10.0.0.0/16' Type: String AllowedPattern: '(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})' Resources: Vpc: Type: AWS::EC2::VPC Properties: CidrBlock: !Ref VpcCidr EnableDnsHostnames: True EnableDnsSupport: True PublicSubnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref Vpc CidrBlock: !Select [ 0, !Cidr [ !Ref VpcCidr, 12, 8 ] ] MapPublicIpOnLaunch: True AvailabilityZone: !Select - 0 - Fn::GetAZs: !Ref "AWS::Region" PublicSubnet2: Type: AWS::EC2::Subnet Properties: VpcId: !Ref Vpc CidrBlock: !Select [ 1, !Cidr [ !Ref VpcCidr, 12, 8 ] ] MapPublicIpOnLaunch: True AvailabilityZone: !Select - 0 - Fn::GetAZs: !Ref "AWS::Region" ```
There are way too many sub-questions to answer each of them individually here. Instead I can write this. CIDRs for VPC are selected from three [common ranges](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html#VPC_Sizing): * 10.0.0.0 - 10.255.255.255 (10/8 prefix) * 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) * 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) These ranges are used because they are **not-routable** over the internet. `10.0.0.0/16` - is the most commonly used CIDR used for VPC. This give you 65535 private IP addresses to work with in your VPC. You commonly **divide it** to subnets of size `/24`, each with 255 private addresses. For example: * 10.0.1.0/24 * 10.0.2.0/24 * 10.0.3.0/24 * 10.0.4.0/24 If you use the above pattern for VPC and subnets, you don't have to do any calculations or memorize any formals. Of course if you want to have more specific subnets, or subnets of different sizes, you have to learn how to calculate subnets. There are **many resources and tools** on the internet for that. Examples are: * <http://www.subnet-calculator.com/cidr.php> * <https://mxtoolbox.com/SubnetCalculator.aspx> * [IPv4, CIDR, and VPC Subnets Made Simple!](https://www.youtube.com/watch?v=z07HTSzzp3o) **Update** The template uses intristic function [Fn::Cidr](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-cidr.html). The construct: ``` !Cidr [ !Ref VpcCidr, 12, 8 ] ``` Will create a list of **12 CIDR ranges**, of size of /24 (32-8). Each subnet will have 255 addresses. The `Select` is used to chose **individual** CIDRs from the list: ``` !Select [ 0, !Cidr [ !Ref VpcCidr, 12, 8 ] ] # 10.0.0.0/24 !Select [ 1, !Cidr [ !Ref VpcCidr, 12, 8 ] ] # 10.0.1.0/24 !Select [ 2, !Cidr [ !Ref VpcCidr, 12, 8 ] ] # 10.0.2.0/24 !Select [ 11, !Cidr [ !Ref VpcCidr, 12, 8 ] ] # 10.0.11.0/24 ```
357161
Writing an application which sends 4 ints over socket, trying the following but getting 0s at receiving end... I assume this is something to do with the way I'm passing them signedness & endianness etc... ``` int _send(int sock, int c, int x, int y, int w) { int cc, xc, yc, wc; char buf[16]; int offset; struct sockaddr_in sap; char echoBuffer[1]; /* Buffer for echo string */ int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total bytes read */ offset = 0; buf[offset] = htonl(c); buf[4] = htonl(x); buf[8] = htonl(y); buf[12] = htonl(w); if (send(sock, buf, 16, 0) != 16) { printf("send() sent a different number of bytes than expected"); return(-1); } //... } ``` And this is the code at the receiving end: ``` while (listen(sock, 2) == 0) { printf("listened...\r\n"); int addrlen; struct sockaddr_in address; addrlen = sizeof(struct sockaddr_in); int channel = accept(sock, (struct sockaddr *)&address, &addrlen); if (channel<0) { perror("Accept connection"); return -1; } else { printf("accepted\r\n"); while (1) { int size = 16; char buffer[16]; recv( channel, buffer, size, 0); for (int i=0; i<=12; i+=4) { int c = ntohl(buffer[i]); printf("%d\r\n", c); } } ```
``` buf[offset] = htonl(c); buf[4] = htonl(x); buf[8] = htonl(y); buf[12] = htonl(w); ``` this is broken. you should declare array of `int`egers. Reason is that `buf[i] = x` meants put a byte at i-th cell, and if it doesn't fit then truncate. That is what is happening.
357845
I have mysql-table called products with the following structure/contents: ``` id (int), public_id (int), deleted (bool), online (bool) 1 1 0 1 2 1 0 0 3 1 1 0 4 2 0 1 5 2 0 1 ``` My question is, how to select all, currently online, not deleted products. In this example only record 5 (public\_id 2). The same public\_id means the same product (grouping) The higher the id, the newer the information (ordering). And the products need to be *not* deleted (where). And some other where statements, in this case with the online field. I need all the aspects (grouping, ordering and where), but I can't figure out how. Any suggestions? Results of explain query from Galz: ``` id select_type table type possible_keys key key_len ref rows Extra 1 PRIMARY nomis_houses ref online online 1 const 8086 Using where 2 DEPENDENT SUBQUERY nomis_houses index NULL house_id 4 NULL 9570 Using filesort ``` ps. This query did the trick, but is awfully, awfully, awfully slow: ``` select * from (select * from (select * from products order by id desc) tmp_products_1 group by public_id) tmp_products_2 where deleted = '0' AND online = '1' ```
based on Sachin's answer and your comment, maybe this can help: ``` select * from products where id in ( select max(id) as id from products where sum(deleted) = 0 group by public_id ) and online = 1 ``` **Edit by Pentium10** The query can be rewritten into ``` SELECT * FROM products p JOIN (SELECT MAX(id) AS id FROM products HAVING SUM(deleted) = 0 GROUP BY public_id) d ON d.id = p.id WHERE online = 1 ``` You need indexes on: * (id,online) * (public\_id,deleted,id)
358161
> > This is My XML Format > > > ``` <Formsxml CM="7" CW="3"> <Forms GroupName="Kingfisher" PRONME="Kingfisher" TBONUSP="6000" NACRES="45" TP="133.333333"> <Form M="1" GroupName="Kingfisher January" PRONME="Kingfisher" TBONUSP="1000" NACRES="7.50" TP="133.333333" /> <Form M="2" GroupName="Kingfisher Feb" PRONME="Kingfisher" TBONUSP="1000" NACRES="7.50" TP="133.333333" /> <Form M="5" GroupName="Kingfisher May" PRONME="Kingfisher" TBONUSP="1000" NACRES="7.50" TP="133.333333" /> <Form M="6" GroupName="Kingfisher July" TBONUSP="1000" NACRES="7.50" TP="133.333333" /> <Form W="3" GroupName="Kingfisher Week 3 Total" TBONUSP="2000" NACRES="7.50" TP="133.333333" /> </Forms> <Forms GroupName="Pigeon" PRONME="Pigeon" TBONUSP="5000" NACRES="55555.00" TP="0.018000"> <Form M="5" GroupName="Pigeon May" PRONME="Pigeon" TBONUSP="1000" NACRES="7.50" TP="133.333333" /> <Form M="6" GroupName="Pigeon July" TBONUSP="1000" NACRES="7.50" TP="133.333333" /> <Form W="1" GroupName="Pigeon Week 1 Total" TBONUSP="2000" NACRES="7.50" TP="133.333333" /> </Forms> <Forms GroupName="Sparrow" PRONME="Sparrow" TBONUSP="1000" NACRES="0.90" TP="1111.111111"> <Form M="6" GroupName="Sparrow July" TBONUSP="1000" NACRES="7.50" TP="133.333333" /> <Form W="4" GroupName="Sparrow July" TBONUSP="1000" NACRES="7.50" TP="133.333333" /> </Forms> </Formsxml> ``` > > This is My XSLT 1.0 > > > ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <table cellspacing="0" cellpadding="0" width="100%" border="1" borderColorDark="#ffffff" borderColorLight="#000000" class="smlFonts"> <tr height="20" align="center"> <td rowspan="1" width="10%"><b>Name</b></td> <td rowspan="1" width="7%"><b>Net</b></td> <td rowspan="1" width="7%"><b>Total</b></td> <td rowspan="1" width="8%"><b>Average</b></td> <xsl:apply-templates select="*/Forms"/> </tr> </table> </xsl:template> <xsl:template match="Forms"> <xsl:apply-templates select="Form"/> <tr style="color:red"> <td> <xsl:value-of select="@NAME"/> Total </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:template> <xsl:template match="Form"> <xsl:choose> <xsl:when test="@M ='1'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> January </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='2'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> Febuary </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='3'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> March </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='4'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> April </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='5'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> May </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='6'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> June </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='7'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> July </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='8'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> August </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='9'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> September </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='10'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> October </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='11'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> November </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="@M ='12'"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:when> <xsl:otherwise><tr> <td> December </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr></xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> ``` > > But i want Output Like This...Based on the Condition of CM Means if > its 7 only till June Then after Based on Week CW if its 3 Till 3rd Week i want to print > Any Help will be > Appreciated........See Image for More Details.. > > > Output i Expect... > > > ![enter image description here](https://i.stack.imgur.com/jduSR.jpg)
I'm afraid your effort of twelve `xsl:choose` instructions is totally vain and logically wrong. You can obtain the wanted result with less effort, but you need a lookup table for the months. The following transform is just a "get-started". Give it a run and you will notice that: * For each Forms group only the required rows will be printed (all months) * When a month is missing in the group, a default is used * The number of months displayed is less or equal Formsxml/@CM (as requested) You might want also complete the lookup table at the moment populated till july. --- [XSLT 1.0] ``` <xsl:stylesheet version="1.0" xmlns:empo="http://stackoverflow.com/users/253811/empo" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <empo:months> <empo:M id="1">Jan</empo:M> <empo:M id="2">Feb</empo:M> <empo:M id="3">Mar</empo:M> <empo:M id="4">Apr</empo:M> <empo:M id="5">May</empo:M> <empo:M id="6">Jun</empo:M> <empo:M id="7">Jul</empo:M> </empo:months> <xsl:template match="/"> <table cellspacing="0" cellpadding="0" width="100%" border="1" borderColorDark="#ffffff" borderColorLight="#000000" class="smlFonts"> <tr height="20" align="center"> <td rowspan="1" width="10%"><b>Name</b></td> <td rowspan="1" width="7%"><b>Net</b></td> <td rowspan="1" width="7%"><b>Total</b></td> <td rowspan="1" width="8%"><b>Average</b></td> <xsl:apply-templates select="*/Forms"/> </tr> </table> </xsl:template> <xsl:template match="Forms"> <xsl:variable name="Forms" select="."/> <xsl:for-each select="document('')/*/ empo:months/empo:M[@id &lt;= $Forms/../@CM]"> <xsl:choose> <xsl:when test="$Forms/Form[@M=current()/@id]"> <xsl:apply-templates select="$Forms/Form[@M=current()/@id]"/> </xsl:when> <xsl:otherwise> <tr> <td> <xsl:value-of select="."/> </td> <td> 0.0000 </td> <td> 0.0000 </td> <td> 0.0000 </td> </tr> </xsl:otherwise> </xsl:choose> </xsl:for-each> <tr style="color:red"> <td> <xsl:value-of select="@NAME"/> <xsl:text> Total</xsl:text> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:template> <xsl:template match="Form"> <tr> <td> <xsl:value-of select="@GroupName"/> </td> <td> <xsl:value-of select="@NACRES"/> </td> <td> <xsl:value-of select="@TBONUSP"/> </td> <td> <xsl:value-of select="@TP"/> </td> </tr> </xsl:template> </xsl:stylesheet> ```
358385
I'm a new Ruby/Rails guy. Here's one question puzzling me: Can we find the exact module lists mixin-ed for a class in Rails from the API doc? For example, if we have an instance of one subclass of ActiveRecord::Base, we can use validates method in this class such as following: ``` class Product < ActiveRecord::Base has_many :line_items validates :title, :description, :image_url, :presence => true end ``` from rails api doc we can find that validates belongs to ActiveModel::Validations::ClassMethods, so ActiveRecore::Base must have ActiveModel::Validations::ClassMethods mixin, but I didn't find anything relating to this in the api reference. Can anyone tell me if I can find this info from api doc? Thanks for all of your help in advance. I really hope my question doesn't sound too silly:)
in console : ``` ActiveRecord::Base.included_modules ```
358536
I use the current event to update the RecordSource property of a subform based on the ID of the record on the parent form. The problem arises in new records, because the ID field (which is an autonumber) is null. I test for the null ID to avoid errors, but I need to update the RecordSource as soon as the record is created, when the user types the first character. The problem is that both Dirty and BeforeInsert events are triggered **before** the record is actually created, thus before the ID is assigned. I need an event that will trigger **after** the ID autonumber is assigned. Thanks in advance for your help
There is an After Insert event that will do what you want-- it fires after the record has been inserted and therefore the ID is in existence.
358688
I have troubles to add some data to my Mysql Data base : i work with redhat jboss and wildfly 9.x server i generated my entities , so it seems like my server work fine, but when i started to add some data in my client project , it keep show me an error that is No EJB receiver available for handling . this is my Service : ``` String jndiName = "examen2018-ear/examen2018-ejb/ServiceEmployee!tn.esprit.examen2018.services.EmployeeServiceRemote"; Context context = new InitialContext(); EmployeeServiceRemote employeeServiceRemote = (EmployeeServiceRemote) context.lookup(jndiName); Employee emp1 = new Employee(); emp1.setFirstName("Mohamed"); emp1.setLastName("Boujouma"); emp1.setPassword("emp"); emp1.setEmployeeType(EmployeeType.EMP); employeeServiceRemote.ajouterEmployee(emp1); ``` My Service Link generated from wildfly: ``` java:jboss/exported/examen2018-ear/examen2018-ejb/ServiceEmployee!tn.esprit.examen2018.services.EmployeeServiceRemote ``` My implimentation for ajouterEmployee : ``` @Override public void ajouterEmployee(Employee employe) { em.persist(employe); } ```
You have a couple of issues. 1. `socket.connect` doesn't return anything. It returns `None`. You think it returns a tuple of `conn, addr`. Python tries to deconstruct whatever is returned into a tuple by iterating over it and you get the error: ``` TypeError: 'NoneType' object is not iterable ``` 2. socket.sendall accepts bytes not a `str`. Convert by ``` sock.sendall(command.encode()) ``` Here's the fixed `send.py`: ``` import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) command = "bridge test!" x, y = sock.connect(('172.168.1.2', 4000)) sock.sendall(command.encode()) ```
358923
I am having an undefined value when I tried to convert my canvas to a blob. I have this code below which works fine, but when I tried to move the console log below to the function then it gives me undefined. Here is the working code: ``` const handleSave = (params) => { let previewUrl; previewCanvasRef.current.toBlob( (blob) => { previewUrl = window.URL.createObjectURL(blob); console.log(previewUrl); }, 'image/png', 1 ); } ``` when I tried to make the console log below. then It gives me an undefiend value: ``` const handleSave = (params) => { let previewUrl; previewCanvasRef.current.toBlob( (blob) => { previewUrl = window.URL.createObjectURL(blob); }, 'image/png', 1 ); console.log(previewUrl); } ``` Here is what I've tried but error: ``` const handleSave = (params) => { let previewUrl; previewCanvasRef.current.toBlob( async (blob) => { previewUrl = window.URL.createObjectURL(blob); }, 'image/png', 1 ).then((res) => console.log(res)); } ```
Use this: ```js document.getElementById("clickCount").addEventListener("click", function() { document.getElementById("showMe").value++; }) ``` ```html <input type="number" id="showMe" value="1"> <button type="button" id="clickCount">Click Me</button> ```
358971
I have this IF clause snippet from a PHP script that is basically a small search engine: ``` if(isset($_REQUEST['search'])){ $search_term = trim($_REQUEST['search']); if(strlen($search_term) <= 0){ $website_search_dynamic -> error($website_search_dynamic->label("Please enter a search query."),true); }else if(strlen($search_term) < $GLOBALS['_SEARCH_MIN_CHARS']){ $website_search_dynamic -> error($website_search_dynamic->label("Sorry, you must enter at least %d characters in your search query",$GLOBALS['_SEARCH_MIN_CHARS']),true); } $website_search_dynamic -> search($search_term); } ``` How do I add CSS styling to the two labels? For example, I would like either error message to be displayed in a centered div. Nothing too fancy. Thanks!
``` $insert_cust=mysql_query("INSERT INTO tb_cust(cust_id,cust_name,cust_add) VALUES(NULL,'$cust_name','$cust_add')"); mysql_query($insert_cust); ``` Why did you run mysql\_query twice? As you try to run `mysql_query` again which is nonsense, you can't get a valid insert id I think. At the end you use `echo` to insert?
359325
This is my first question, so I'll try to be as detailed as possible. I'm working on implementing noise reduction algorithm in CUDA 6.5. My code is based on this Matlab implementation: <http://pastebin.com/HLVq48C1>. I'd love to use new cuFFT Device Callbacks feature, but I'm stuck on **cufftXtSetCallback**. Every time my cufftResult is **CUFFT\_NOT\_IMPLEMENTED** (14). Even example provided by nVidia fails the same way... My device callback testing code: ``` __device__ void noiseStampCallback(void *dataOut, size_t offset, cufftComplex element, void *callerInfo, void *sharedPointer) { element.x = offset; element.y = 2; ((cufftComplex*)dataOut)[offset] = element; } __device__ cufftCallbackStoreC noiseStampCallbackPtr = noiseStampCallback; ``` CUDA part of my code: ``` cufftHandle forwardFFTPlan;//RtC //find how many windows there are int batch = targetFile->getNbrOfNoiseWindows(); size_t worksize; cufftCreate(&forwardFFTPlan); cufftMakePlan1d(forwardFFTPlan, WINDOW, CUFFT_R2C, batch, &worksize); //WINDOW = 2048 //host memory, allocate float *h_wave; cufftComplex *h_complex_waveSpec; unsigned int m_num_real_elems = batch*WINDOW*2; h_wave = (float*)malloc(m_num_real_elems * sizeof(float)); h_complex_waveSpec = (cufftComplex*)malloc((m_num_real_elems/2+1)*sizeof(cufftComplex)); //init memset(h_wave, 0, sizeof(float) * m_num_real_elems); //last window won't probably be full of file data, so fill memory with 0 memset(h_complex_waveSpec, 0, sizeof(cufftComplex) * (m_num_real_elems/2+1)); targetFile->getNoiseFile(h_wave); //fill h_wave with samples from sound file //device memory, allocate, copy from host float *d_wave; cufftComplex *d_complex_waveSpec; cudaMalloc((void**)&d_wave, m_num_real_elems * sizeof(float)); cudaMalloc((void**)&d_complex_waveSpec, (m_num_real_elems/2+1) * sizeof(cufftComplex)); cudaMemcpy(d_wave, h_wave, m_num_real_elems * sizeof(float), cudaMemcpyHostToDevice); //prepare callback cufftCallbackStoreC hostNoiseStampCallbackPtr; cudaMemcpyFromSymbol(&hostNoiseStampCallbackPtr, noiseStampCallbackPtr, sizeof(hostNoiseStampCallbackPtr)); cufftResult status = cufftXtSetCallback(forwardFFTPlan, (void **)&hostNoiseStampCallbackPtr, CUFFT_CB_ST_COMPLEX, NULL); //always return status 14 - CUFFT_NOT_IMPLEMENTED //run forward plan cufftResult result = cufftExecR2C(forwardFFTPlan, d_wave, d_complex_waveSpec); //result seems to be okay without cufftXtSetCallback ``` I'm aware that I'm just a beginner in CUDA. My question is: How can I call cufftXtSetCallback properly or what is a cause of this error?
Referring to the [documentation](http://docs.nvidia.com/cuda/cufft/index.html#callback-overview): > > The callback API is available in the statically linked cuFFT library only, and only on 64 bit LINUX operating systems. Use of this API requires a current license. Free evaluation licenses are available for registered developers until 6/30/2015. To learn more please visit the [cuFFT developer page](https://developer.nvidia.com/cufft/). > > > I think you are getting the not implemented error because either you are not on a Linux 64 bit platform, or you are not explicitly linking against the CUFFT static library. The Makefile in the [cufft callback sample](http://docs.nvidia.com/cuda/cuda-samples/index.html#simple-cufft-callbacks) will give the correct method to link. Even if you fix that issue, you will likely run into a `CUFFT_LICENSE_ERROR` unless you have gotten one of the evaluation licenses. Note that there are various [device limitations as well](http://docs.nvidia.com/cuda/cufft/index.html#static-library) for linking to the cufft static library. It should be possible to build a statically linked CUFFT application that will run on cc 2.0 and greater devices.
359471
I cannot go pass the black screen and the following shows up on my screen after upgrading and rebooting with the Ubuntu update manager from 11.10 to 12.04: ``` ata_id [27]: HDIO_GET_IDENTITY failed for '/dev/sdb/': Invalid argument *stopping save kernel messages Setting up X font server socket directory /tmp/.font-unix...done. Starting X font server:xfs. Rather than invoking init scripts through /etc/init.d, use the service(8) utility, e.g. service S25 bluetooth start inid: Unkown job: S25 bluetooth Since the script you are attempting to invoke has been converted to an upstart job, you may also use the start(8) utility, e.g. start S25bluetooth *PulseAudio configured for per-user sessions Saned disabled; edit /etc/default/saned *Checking battery state... [OK] ``` After this nothing happens anymore. I even tried booting from different linux versions and also from recovery mode. I've tried repairing the packages and even updating the grub loader. \*I have Ubuntu in an external hard drive but there were never any problems with booting before the upgrade. \*Also, it seems to be something to do with invoking init scripts rather than other problems. (If u think it isn't, still do try to help me solve the problem.) Please help!
You could try booting from Grub with the option: ``` xforcevesa ``` This should boot ubuntu in failsafe graphics mode. If you have a proprietary driver you can then fix it under additional drivers. If this isn't the case, you could try reinstalling xorg and its drivers: ``` sudo apt-get remove --purge xserver-xorg sudo apt-get install xserver-xorg sudo dpkg-reconfigure xserver-xorg ```
360292
If I have the following methods: ``` public bool Equals(VehicleClaim x, VehicleClaim y) { bool isDateMatching = this.IsDateRangeMatching(x.ClaimDate, y.ClaimDate); // other properties use exact matching } private bool IsDateRangeMatching(DateTime x, DateTime y) { return x >= y.AddDays(-7) && x <= y.AddDays(7); } ``` I am comfortable overriding `GetHashcode` when the values exactly match but I really have no idea how to do it when a match is within a range like this. Can anyone help please?
I agree with Chris that > > But if you have Date1 as Oct1, Date2 as Oct6, Date3 as Oct12. Date1 == Date2, and Date2 == Date3, but Date1 != Date3 > is a strange behavior and the Equals purpose is not what you should use. > > > I don't really know if you are developping something new and if you have a database containing your vehicule claims, but I would have associated claims in the database as parent child relationship. What you have to ask yourself is: Is it possible that 2 vehicule claims within your date range can be different? Is there any other property you can use to identify a claim as unique? Maybe you could resolve your problem this way: Having a ``` List<VehicleClaim> RelatedClaims ``` property in your VehicleClaim object. Instead of Equals, use a function ``` bool IsRelated(VehicleClaim vehiculeClaim) { if(all properties except date are equals) { // since claims are sorted by date, we could compare only with the last element foreach(var c in RelatedClaims){ if (IsDateRangeMatching(this.ClaimDate, c.ClaimDate)) return true; } } return false; } ``` and add code to construct your object ``` List<VehiculeClaim> yourListWithDuplicatesSortedByDate; List<VehiculeClaim> noDuplicateList = new List<VehiculeClaim>(); foreach(var cwd in yourListWithDuplicatesSortedByDate) { var relatedFound = noDuplicateList.FirstOrDefault(e => e.IsRelated(cwd)); if (relatedFound != null) relatedFound.RelatedClaims.Add(cwd); else noDuplicateList.Add(cwd); } ``` Problem with this, your claims must be sorted by date and it could not be the most efficient way to accomplish that.
360881
I have a WPF application, which uses a custom implemented ForEachAsyncParallel method: ``` public static Task ForEachParallelAsync<T>(this IEnumerable<T> source, Func<T, Task> body, int maxDegreeOfParallelism) { return Task.WhenAll(Partitioner.Create(source).GetPartitions(maxDegreeOfParallelism).Select(partition => Task.Run(async delegate { using (partition) { while (partition.MoveNext()) { await body(partition.Current); } } }))); } ``` The issue I'm facing is when a the body contains a async statement and on executing it, it switches the thread to a new one, which is causing an `The calling thread cannot access this object because a different thread owns it`. Alternate is to use foreach loop or dispatcher ( which I do not want to) is it possible to point out the issue with the current implementaion?
Your problem can be solved by replacing the [`Task.Run`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run) with the simple `Run` implementation below: ``` static async Task Run(Func<Task> action) => await action(); ``` The `Task.Run` method executes the supplied delegate on a `ThreadPool` thread, making it illegal to access UI components inside the delegate. On the contrary the `Run` method above will execute the delegate on the current thread (most probably the UI thread). This means that the asynchronous delegates will not be invoked in parallel (making the name of the `ForEachParallelAsync` method a bit misleading). This shouldn't be a problem, because most probably your intention is not to parallelize the creation of the tasks, but instead to have multiple tasks concurrently in-flight. In other words the goal is asynchronous concurrency, not parallelism. Parallelism requires many threads, while asynchronous concurrency requires [no threads](https://blog.stephencleary.com/2013/11/there-is-no-thread.html). Honestly the `ForEachParallelAsync` implementation used by your application has flaws that are irrelevant to the `Task.Run`/`Run` discussion above, and my suggestion is to avoid it. You can find better implementations [here](https://stackoverflow.com/questions/15136542/parallel-foreach-with-asynchronous-lambda/66635760#66635760), [here](https://stackoverflow.com/questions/10806951/how-to-limit-the-amount-of-concurrent-async-i-o-operations/37569259#37569259) and [here](https://stackoverflow.com/questions/11564506/nesting-await-in-parallel-foreach/65251949#65251949), that are based on the `SemaphoreSlim` class or the TPL Dataflow library. The problem with the `ForEachParallelAsync` implementation in your question, which is probably originated from [this](https://devblogs.microsoft.com/pfxteam/implementing-a-simple-foreachasync-part-2/) blog post, is its behavior in case some of the tasks fail. On every exception one worker-task will be killed, and the process will continue with a reduced level of concurrency. If you are unlucky to have exactly `maxDegreeOfParallelism - 1` early exceptions, the last standing worker will slowly process all elements alone, until the exceptions are finally surfaced. This problem may not affect you, in case your code handles all errors and doesn't allow them to propagate.
361213
I have a `UILabel` which added in `UIView` and this view add as subview of `UIScrollView`and zooming is enabled. Working every thing fine but when I zoom in then UILabel and other properties too and this look quite odd.I also added following code for flexible size. ``` userResizableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); userResizableView.autoresizesSubviews = YES; ``` Above View is `UIView Type. And below is code of Label ``` UILabel * lbl_FormFieldName = [[UILabel alloc]initWithFrame:CGRectMake(1, 1, rect.size.width, 15)]; lbl_FormFieldName.attributedText = attrText; // lbl_FormFieldName.text = text; lbl_FormFieldName.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); lbl_FormFieldName.textColor = [UIColor blackColor]; lbl_FormFieldName.backgroundColor = [UIColor clearColor]; lbl_FormFieldName.font = customFont; lbl_FormFieldName.numberOfLines = 0; lbl_FormFieldName.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone lbl_FormFieldName.clipsToBounds = YES; lbl_FormFieldName.textAlignment = NSTextAlignmentCenter; ``` Kindly give me any suggestion how to make good. Looking for suggestion. Thanks
Using command substitution as a fake comment is both expensive (you still have to fork a shell and parse the comment) and possibly dangerous (command substitutions can be nested, and those will still be executed). A better way is to store your arguments in an array where there is no chance of inadvertent execution. ``` args=( # This is for something arg_1 # This is for something else arg_2 # This is not not for anything arg_3 ) my_func "${args[@]}" ``` If you need to remain POSIX-compliant, meaning no arrays, I suggest simply documenting the arguments prior to the call: ``` # Arg 1: this is for something # Arg 2: this is for something else # Arg 3: this is not for anything my_func \ arg_1 \ arg_2 \ arg_3 ```
361429
rpmbuild generates RPM under which directory? I checked the RPMS directory:- ``` [root@tom adil]# ls /usr/src/redhat/ BUILD RPMS SOURCES SPECS SRPMS [root@tom adil]# ls /usr/src/redhat/RPMS/ athlon i386 i486 i586 i686 noarch [root@tom adil]# ``` How to decide rpmbuild outputs in which of the above sub-directories? Is it controlled by spec file? What is the default option? I thought `uname -p` but its not the case probable `uname -i` is used. Linked to my last question [Difference between "machine hardware" and "hardware platform"](https://stackoverflow.com/questions/2565282/difference-between-machine-hardware-and-hardware-platform)
Following on from your last comment, by default the RPM will go into the subdirectory that matches the platform you're building on. You can override this by passing the --target parameter to rpmbuild, but this only applies where valid; for example, you can use --target i386 on an x86\_64 system to build a 32-bit RPM, but you can't build a 64-bit RPM on a 32-bit platform.
361513
I have web services built with ASP.NET and ASP.NET clients consuming them. When consuming the webservices, how would I to force the clients to use https? I don't want to force the whole site to use https by turning on require SSL in IIS. Can I use the IIS7 URL rewrite module to re-route http requests to https?
Since the HTML is not coming from a live URL, you need to include a `<base href=...>` tag in the HTML itself so relative links can be resolved correctly.
361651
I have list of **Processes** and i want to execute them like, **Ten processes per minute**. I tried `ExecutorService`, `ThreadPoolExecutor`, `RateLimiter` but none of them can support my case, also i tried `RxJava` but maybe i cannot figure out how ti implement it correctly. --- Example ------- I have list of `Runnable` with size **100K**, each `Runnable` have this logic: * Retrieve data from `rest api`. * Do some calculation on data. * Save the result in database. So i used `ExecutorService` with size **10** and make **Delay(5 seconds)** inside `Runnable#run()` to manage what i need **"Ten processes per minute"**, but still, it's not manageable. The main point of this logic to decrease requests on `rest api`. --- UPDATE ------ effectively what we're looking for is to have an upper limit (in time and count of operations) rather than evenly distribute the time across operations regardless of their individual throughput. i.e. if I have a list of 100 ops which will take 0.5 seconds each, and I have a rate limiter than (after distribution) determined that a single operation should take 0.8 seconds I then have a gap of 0.3 second I can use to start a new operation
If you know the name of the peer network just add the location: `peer_network = "projects/PEER_PROJECT/global/networks/PEER_NETWORK"`
361797
OK, I know a bit of C++ (very basic syntax), and I want to do physics simulation in C++, like stuff like (also the things mentioned [here](http://www.falstad.com/mathphysics.html)): * Ripples and waves over a 2-d surface * Vibrating string/membrane * Various electric/magnetic fields (as per my wish) in 2d/3d * Gas molecules simulation * Newtonian mechanics stuff (rotating objects, Newtonian gravity etc) Can anybody suggest some sources/libraries (or what that's called, something like vpython for python) so where I can learn so that I can simulate such stuff on my PC? Note that I'm NOT asking for books for doing it (though recommendations are welcome)
I think you are missing a very important and crucial step that lies exactly between the physics and simulation: the mathematical model. In order to model any physics, one has to formulate the mathematical description of the physical phenomenon. Depending on the goals of the simulation, different approximations and assumptions can be made resulting in various complexity of the systems and requiring more or less complicated numerical techniques to solve them. You mentioned several very different areas of physics that you are interesting simulating, so, I guess, your interest lies more in the numerical methods/visualization rather than in any particular field. I will take electromagnetics (EM) as an example: * the full glory of EM is covered by Maxwell's Equations * various forms of which (and approximations) can be solved in 1D, 2D, and 3D. * sometimes it is appropriate to use surface discretization (PEC - perfect electric conductor), sometimes you have to use volume discretization * different properties of materials (nonlinearity, anisotropy, etc) might need to be taken into account. What I am trying to say, is that to simulate any physics you first have to understand (to some extent) the mathematical model behind it. Next, usually, you need to solve this model using some numerical technique. Depending on the model, different techniques can be applicable and preferable. Again, I will use the ones that are commonly used for EM, but other fields will be similar: * finite-difference (finite-difference time-domain) * finite-element method (FEM) * integral-equation methods (boundary element) * physical/geometrical optics ...etc. Different libraries (including C++ ones) can be used to solve those problems: deal.ii, FEniCS... However, my advice would be to start with something simpler and use a more appropriate language/platform to begin with numerical simulation of the physical phenomenon. Say, starting solving wave-equation in 1-D using Matlab (Octave) and visualizing simple propagation. Also using numerous already available toolboxes for PDE, ODE, and particular areas of physics should be easier there. I would also suggest a book/course that has nothing to do with C++, but was my "bible" in computational science: * [MIT course on computational science and engineering (Gilbert Strang)](https://ocw.mit.edu/courses/mathematics/18-085-computational-science-and-engineering-i-fall-2008/), syllabus, video lectures, notes are available * [Gilbert Strang, "Computational Science and Engineering"](https://books.google.ca/books/about/Computational_Science_and_Engineering.html?id=GQ9pQgAACAAJ&source=kp_cover&redir_esc=y), very accessible book.
361826
After a great deal of searching and head banging, i'm asking this question. I started a new Windows Forms Application in Visual Studio 2010. Gave it a name and stored it in a location. Nothing added or edited in the same. No changes in the project properties either. [Here](http://i299.photobucket.com/albums/mm298/aabond/Capture_zpsdc5768a4.jpg) is a copy of the Solutions Explorer. I'm building the empty form and I get the following error. ``` 1>------ Build started: Project: TestProject, Configuration: Debug Win32 ------ 1>Build started 27/11/2013 1:35:27 PM. 1>InitializeBuildStatus: 1> Touching "Debug\TestProject.unsuccessfulbuild". 1>GenerateTargetFrameworkMonikerAttribute: 1>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files. 1>CoreResGen: 1> Processing resource file "Form1.resX" into "Debug\TestProject.Form1.resources". 1>LINK : fatal error LNK1104: cannot open file 'Debug\AssemblyInfo.obj' 1> 1>Build FAILED. 1> 1>Time Elapsed 00:00:01.41 ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ``` Now I have checked every damn page relevant to the error (6 hrs. of googling!!) [Here](http://msdn.microsoft.com/en-us/library/ts7eyw4s.aspx) is a list of the possible errors as suggested by MSDN. Now I'm new to MSVS 10, so I figure out that the `.obj` file is not present in the Debug Window, but `AssemblyInfo.cpp` is present. What should I do in the project settings so that the `.obj` gets compiled and the error goes away. **Update**: Still no answers!! I'm amazed how NOBODY is getting this issue. Here is what I have tried soo far and the following happens: 1. Opened new Visual C++ Windows Forms Application (no modifications!) 2. Write ABSOLUTELY NO CODE. 3. Build Project And the error occurs. **Next** 1. Opened an old solution, where the .obj files were present. 2. Made a rebuild of the solution. Same Error. I look up the solution in the windows explorer. All .obj files are gone(which should happen as a rebuild would clean the .obj files). But what remains are onlt the `.log` files. Thus, I have isolated the error that the compilation is not occuring as the linker files are not being created. As a result, the linker error `LNK1104` or `LNK1181` happen. Can somebody tell me *why* is this problem. Has anyone seen this before. Can anyone provide a solution, if possible??
You should use `display: table-cell;` for the parent element and than use `max-height` and `max-width` properties for your `img` tag.. This way you can align the images vertically as well as horizontally. [**Demo**](http://jsfiddle.net/m9VGB/) ``` div { width: 300px; height: 300px; display: table-cell; border: 1px solid #f00; text-align: center; vertical-align: middle; } div img { max-height: 100%; max-width: 100%; } ``` --- But if you are looking to align images only horizontally and not vertically, than you won't need to do much, just declare `text-align: center;` on the parent element.
362090
I have a method that limits the items in a list via LINQ. The list contains items with two boolean properties: bool\_a and bool\_b. The list contains items where bool\_a is true and bool\_b is false as well as items where both are false. My expectation is that once I have limited the list only records where bool\_a is false will remain while all items where both bool\_a and bool\_b are false will be removed. However, I'm finding that all items are being removed. It's as though the AND operator is behaving like an OR. An example follows. What am I not seeing? ``` var records = GetRecords(); var count_where_a_before = records .Where(x => x.bool_a); // 100 items var count_where_ab_before = records .Where(x => x.bool_a && x.bool_b); // 10 items records = records.Where(x => !x.bool_a && !x.bool_b); var count_where_a_after = records .Where(x => x.bool_a); // 0 items ``` As you can see from the above, I've been using counts before and after the where clause to evaluate the list.
This line ``` records = records.Where(x => !x.bool_a && !x.bool_b); ``` Results in records only having items that have !x.bool\_a so logically the next line has no x.bool\_a items. This is true because you state that all x.bool\_b are false therefore the statement is really no different to: ``` records = records.Where(x => !x.bool_a); ``` EDIT: you should just be able to use this query if you want all records where bool\_a is true and bool\_b is false: ``` records = records.Where(x => x.bool_a && !x.bool_b); ```
362112
I have a query that's giving me the results I want, but for each item with a given ID\_UNIDAD\_EXPERIMENTAL there are two rows, one with column "Alt" with a value and column "Dap" with null, and the other one with "Alt" null and "Dap" with a value. My question is: How can I group them so each element with a given ID just shows both Alt and Dap columns with values, kind of "removing" the nulls. Heres the query: ``` SELECT ENS_Medicion.id_medicion_resumen, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental, CASE WHEN UPPER(Variable_simple.nombre) = UPPER('alt') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END as alt, CASE WHEN UPPER(Variable_simple.nombre) = UPPER('dap') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END as dap FROM ENS_Medicion JOIN ENS_Variable_medicion ON ENS_Variable_medicion.id_variable_medicion = ENS_Medicion.id_variable_med JOIN Variable_simple ON Variable_simple.id_variable_simple = ENS_Variable_medicion.id_variable_simple join ENS_Variable_medicion varmed on ENS_Medicion.id_variable_med = varmed.id_variable_medicion join Variable_simple vs on varmed.id_variable_simple = vs.id_variable_simple join ENS_Medicion_resumen mr on mr.id_medicion_resumen = ENS_Medicion.id_medicion_resumen where mr.nro_medicion = 3 and mr.id_ensayo = 9227 and (UPPER(Variable_simple.nombre) = UPPER('alt') or UPPER(Variable_simple.nombre) = UPPER('dap')) GROUP BY ENS_Medicion.id_medicion_resumen, ENS_Medicion.id_unidad_exprimental, Variable_simple.nombre, valor_medido, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental ORDER BY id_unidad_exprimental ``` and here are the results: [![query results](https://i.stack.imgur.com/ioqfY.png)](https://i.stack.imgur.com/ioqfY.png) you can see that there are two rows for each "id\_unidad\_experimental" and each row has one column with a null value, the goal is to only show one row for "id\_unidad\_experimental" with the two values. Any help would be nice
Color by Value -------------- ```vb Option Explicit Sub ColorByValueTEST() Dim rg As Range: Set rg = Range("B2:B21") ColorByValue rg, 100, -1, vbGreen End Sub Sub ColorByValue( _ ByVal rg As Range, _ ByVal GreaterThanValue As Double, _ ByVal ColumnOffset As Long, _ ByVal DestinationColor As Long) If rg Is Nothing Then Exit Sub Dim srg As Range: Set srg = rg.Columns(1) If srg.Column + ColumnOffset < 1 Then Exit Sub If srg.Column + ColumnOffset > srg.Worksheet.Columns.Count Then Exit Sub Dim drg As Range Dim sCell As Range For Each sCell In srg.Cells If IsNumeric(sCell) Then If sCell.Value > GreaterThanValue Then If drg Is Nothing Then Set drg = sCell.Offset(, ColumnOffset) Else Set drg = Union(drg, sCell.Offset(, ColumnOffset)) End If End If End If Next sCell If drg Is Nothing Then Exit Sub srg.Offset(, ColumnOffset).Interior.Color = xlNone drg.Interior.Color = DestinationColor End Sub ```
362367
After following part of [***this tutorial***](http://www.androidbegin.com/tutorial/android-parse-com-image-upload-tutorial/) and the [***second answer of this question in SO***](https://stackoverflow.com/questions/9107900/how-to-upload-image-from-gallery-in-android), I managed to save a photo that I chose from my gallery to my object in [Parse](https://parse.com). ![enter image description here](https://i.stack.imgur.com/V7xGp.png) The problem is that the photo that I saved has *.PNG* extension (it was just a screenshot). When I tried to choose a normal photo from the camera folder, nothing was saved and an exception was occurred. The extension of ALL the other photos is **.jpg** *NOT .jpeg*. Because of that, i tried to put `if` statements, so that I can check the type of the photo. The result of the code that is following is that when I choose a **.JPG** photo, **the data type is `NULL`.** But, how can I manage to save the .jpg photos in my Parse Object ? --- In my Activity I have 2 buttons. when you press the first one ( `sign_in` ), there is the listener that does correctly all the checks of the other data in my page and then if all data are okay, it calls a function ( `postData()` ), in which there will be done the saving to parse via objects. The second button is about adding a photo from gallery. In my .java activity, I have this exact listener: ``` picture.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY); } }); ``` --- This is the function that it is being called from the `onClick` function of the button: ``` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //Detects request codes if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) { Uri selectedImage = data.getData(); selectedImageType =data.getType(); Toast.makeText(SignUpActivity.this, "Type: "+selectedImageType, Toast.LENGTH_SHORT).show(); try { bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage); // Convert it to byte ByteArrayOutputStream stream = new ByteArrayOutputStream(); // Compress image to lower quality scale 1 - 100 if (selectedImageType == "JPEG"){ bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); image = stream.toByteArray(); } else if (selectedImageType == "JPG" || selectedImageType == "jpg"){ bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); image = stream.toByteArray(); } else if (selectedImageType == "PNG") { bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); image = stream.toByteArray(); } else{ Toast.makeText(SignUpActivity.this, "Please pick a JPEG or PNG photo!", Toast.LENGTH_SHORT).show(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` --- And this is the function that saves the data: ``` public void postData(final String username,final String password,final String email,final String gender,final String age) { ParseObject user = new ParseObject("users"); user.put("username", username); user.put("password", password); user.put("email", email); user.put("gender", gender); user.put("age_category", age); user.put("admin", false); ParseFile file = null; if (selectedImageType == "JPEG"){ file = new ParseFile("profile_picture.jpeg", image); } else if (selectedImageType == "JPG" || selectedImageType == "jpg"){ file = new ParseFile("profile_picture.jpg", image); } else if (selectedImageType == "PNG"){ file = new ParseFile("profile_picture.png", image); } else{ // Show a simple toast message Toast.makeText(SignUpActivity.this, "Please pick a JPEG or PNG photo!", Toast.LENGTH_SHORT).show(); } // Upload the image into Parse Cloud file.saveInBackground(); user.put("photo", file); // Create the class and the columns user.saveInBackground(); // Show a simple toast message Toast.makeText(SignUpActivity.this, "Image Uploaded", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(SignUpActivity.this, LoginActivity.class); startActivity(intent); overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out); //finish(); } ```
You need to use a positive lookahead assertion. ``` ([A-Z]{3})=(.*?)(?=[A-Z]{3}=|$) ``` [DEMO](https://regex101.com/r/uI0fW4/2)
363108
I notice that Apple has what seems to be duplicate variable names: 2 properties and two ivars. Why does Apple do this? ``` //.h file @interface TypeSelectionViewController : UITableViewController { @private Recipe *recipe; NSArray *recipeTypes; } @property (nonatomic, retain) Recipe *recipe; @property (nonatomic, retain, readonly) NSArray *recipeTypes; ``` And they then update the recipe instance below. Why have two variable with the same name? Will one affect the recipe variable of the `parentViewController` since that recipe variable was set when presenting this view controller the code was in from the `parentViewController`? ``` //.m file - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // If there was a previous selection, unset the accessory view for its cell. NSManagedObject *currentType = recipe.type; if (currentType != nil) { NSInteger index = [recipeTypes indexOfObject:currentType]; NSIndexPath *selectionIndexPath = [NSIndexPath indexPathForRow:index inSection:0]; UITableViewCell *checkedCell = [tableView cellForRowAtIndexPath:selectionIndexPath]; checkedCell.accessoryType = UITableViewCellAccessoryNone; } // Set the checkmark accessory for the selected row. [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark]; // Update the type of the recipe instance recipe.type = [recipeTypes objectAtIndex:indexPath.row]; // Deselect the row. [tableView deselectRowAtIndexPath:indexPath animated:YES]; } ``` **UPDATE 1** This code is from Apple's [iPhoneCoreDataRecipes](https://developer.apple.com/library/ios/samplecode/iPhoneCoreDataRecipes/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008913) core data example: First have a look at the `RecipeViewController's` didSelect delegate method, which will present the `TypeSelectionViewController` (child) view controller. Then have a look at that viewcontroller's `didSelect` delegate method where you will find the code implementation. The reason I started looking at this is because I was interested how the parent's tableView cell got updated based on the selection in the `ChildViewController` in editing mode. To see this for yourself, do the following: 1. Run the application 2. Select the `Recipes` tab 3. Click on a recipe - Chocolate Cake. 4. Click the edit button on the top right 5. Make note of the current category - should be on desert - then click on it. 6. Then you will be taken to the child view controller 7. Click on a different category, then click back and you will notice that the category button for that recipe has magically been updated. And I don't know how that's happening. Does it have something to do with the private ivars and properties? which affects the `parentViewController`'s cell? My question i Guess is, how does selecting a category type in the child view controller's table affect the cell.text in the Parent View Controller's table? I can't see where the managedObjectcontext is saved in the child view controller for it to automatically update the parent View controller's cell text.
What you're seeing here is relatively old code, and there's not much need to do this anymore, thanks to Objective-C auto-synthesis. Nowadays, when you issue a `@property (nonatomic) NSArray *foo;`, you *implicitly* get a `@synthesize foo = _foo;` in your implementation file and an instance variable declaration in your header. You don't see this, the compiler "inserts" it automatically. `foo` is the `property` and `_foo` is the instance variable. (In your above example, the `@property` and backing instance variable are both the same name, which could get confusing very quickly. With the `foo` property, you couldn't accidentally say `self._foo`, that doesn't exist. There's `self.foo` and `_foo`. With your example `recipe` is the ivar and `self.recipe` is the property. Very easy for one to quickly confuse the two when reading code. Before the auto-synthesis, there was an intermediate step where you still needed a `@synthesize`, but you the backing instance variable was generated for you. These new features help you remove boilerplate code. **Answering Update 1** The code doing what you're wondering is in `tableView:cellForRowAtIndexPath`. There's nothing magical here. When you selected a new Category via the `TypeSelectionViewController`, the `NSManagedObject` is updated. Back in the `RecipeDetailViewController`, `cellForRowAtIndexPath` pulls the lasted information from CoreData. `text = [recipe.type valueForKey:@"name"];` You might be getting confused about what an `@property` really is. It's just syntactic sugar. A `@property` these days automatically creates accessor and mutator methods and a backing ivar. Properties themselves aren't areas to store data, it's just a quick way of generating some methods and backing ivars. Example ``` @interface MyClass { NSUInteger _foo; } @end @implementation MyClass - (NSUInteger)foo { return (_foo) } - (void)setFoo:(NSUInteger)newFoo { _foo = newFoo; } @end ``` is equivalent to: ``` @interface MyClass @property (nonatomic, assign) NSUInteger foo; @end ``` You save a lot of typing. When you get into things like `NSString` properties and different property modifiers like `strong` or `copy`, the amount of code you save (and memory management mistakes you avoid) in the mutators becomes much greater.
363660
git push heroku master was rejected. i did some digging in the log and here is what i found. i have never seen this before. this was the first thing in the log that looked like it did not go well. everything before was successful. ``` rake aborted! Invalid CSS after "*/": expected identifier, was "/*!" (in /tmp/build_2a4aaujom538/app/assets/stylesheets/application.css) ``` at the very end, the push stops and here is the reason ``` Precompiling assets failed. Push rejected, failed to compile Ruby/Rails app [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'git@heroku.com:triprecs.git' ``` any ideas on what to check/fix? thanks
It seems there is an issue with nested comments being poorly handled by the sass compiler during asset precompilation. <http://www.madflanderz.de/madblog/archives/307/heroku-rake-assetsprecompile-failed-invalid-css/> Removing nested comments in CSS (// lines within /\* \*/ blocks) should solve the issue. This may be harder with third-party CSS libraries you've included in your project. In that case an upgrade of sass-rails could help (but this is something I've never tried).
364216
I want to display an error on the same page if any field is empty. I've got this, which works but the empty error is displayed as soon as the page is loaded instead of appearing once empty fields are submitted. ``` <?php // Required field names $required = array('triangleSide1', 'triangleSide2', 'triangleSide3'); // Loop over field names, make sure each one exists and is not empty $error = false; foreach($required as $field) { if (empty($_POST[$field])) { $error = true; } } if ($error) { echo "ALL FIELDS ARE REQUIRED"; } else { echo header('Location: formSuccess.php'); } ?> ``` Any ideas? -- UPDATE // IVE TRIED ALL ANSWERS, nothing has worked so far
If you have an input you know will always be submitted with the form, such as a hidden one: ``` <input type='hidden' name='formsubmit' value='1'> ``` Then you can test for this before validating the other inputs ``` if($_POST["formsubmit"]) { // Required field names $required = array('triangleSide1', 'triangleSide2', 'triangleSide3'); // Loop over field names, make sure each one exists and is not empty $error = false; foreach($required as $field) { if (empty($_POST[$field])) { $error = true; } } if ($error) { echo "ALL FIELDS ARE REQUIRED"; } else { header('Location: formSuccess.php'); } } ``` Also you don't echo the return of header()
365101
> > **Possible Duplicate:** > > [Is close() necessary when using iterator on a Python file object](https://stackoverflow.com/questions/1832528/is-close-necessary-when-using-iterator-on-a-python-file-object) > > > ``` for line in open("processes.txt").readlines(): doSomethingWith(line) ``` Take that code for example. There's nothing to call close() on. So does it close itself automatically?
Files will close when the corresponding object is deallocated. The sample you give depends on that; there is no reference to the object, so the object will be removed and the file will be closed. Important to note is that there isn't a guarantee made as to when the object will be removed. With CPython, you have reference counting as the basis of memory management, so you would expect the file to close immediately. In, say, Jython, the garbage collector is not guaranteed to run at any particular time (or even at all), so you shouldn't count on the file being closed and should instead close the file manually or (better) use a `with` statement.
365451
After numerous failed attempts I am really hoping someone can with my problem. It theory what I am trying to do sounds easy enough but I have spent hours on it today with no success. I have tried all the possible solutions from this thread but to no avail: [Excel vba Autofill only empty cells](https://stackoverflow.com/questions/39514314/excel-vba-autofill-only-empty-cells) Also looked here : <https://www.mrexcel.com/board/threads/macro-to-copy-cell-value-down-until-next-non-blank-cell.660608/> I am looking to autofill a formula down a column(a vlookup from another sheet) but if there is already populated cells then to skip and continue the formula in the next available blank cell. For example, in rows A2:A10, row A5 has a value in it, so the formula gets into in A2, then fills to A4, then skips A5, then continues in A6 to A10. This below code works the first time you use it but then on the second run it debugs with a "Run-time error '1004' - No cells were found". I noticed it it putting the formula into the first cell (B2) and then debugging out. ``` Sub FillDownFormulaOnlyBlankCells() Dim wb As Workbook Dim ws1, ws2 As Worksheet Dim rDest As Range Set wb = ThisWorkbook Set ws1 = Sheets("Copy From") Set ws2 = Sheets("Copy To") ws2.Range("A1").Formula = "=IFERROR(IF(VLOOKUP(A2,'Copy From'!A:B,2,FALSE)=0,"""",VLOOKUP(A2,'Copy From'!A:B,2,FALSE)),"""")" Set rDest = Intersect(ActiveSheet.UsedRange, Range("B2:B300").Cells.SpecialCells(xlCellTypeBlanks)) ws2.Range("B2").Copy rDest End Sub ```
Please, try the next code: ``` Sub FillDownFormulaOnlyBlankCells() Dim wb As Workbook, ws1 As Worksheet, rngBlanc As Range Set wb = ThisWorkbook Set ws1 = wb.Sheets("Copy From") On Error Resume Next Set rngBlanc = ws1.Range("B2:B" & ws1.rows.count.End(xlUp).row).SpecialCells(xlCellTypeBlanks) On Error GoTo 0 If Not rngBlanc Is Nothing Then rngBlanc.Formula = "=IFERROR(IF(VLOOKUP(A2,'Copy From'!A:B,2,FALSE)=0,"""",VLOOKUP(A2,'Copy From'!A:B,2,FALSE)),"""")" Else MsgBox "No blanc rows exist in B:B column..." End If End Sub ``` After running it once and do not create any empty cell, **of course there will not be any blanc cells, anymore**, at a second run...
365698
Is there any flag in DataGrip that enables showing caution message of running **write** SQL queries(*UPDATE/INSERT/DELETE*). E.g. saying that Reason: it's so easy to run queries in DataGrip with `Cmd`+`Enter` and not paying attention what query you are running.
To prevent changes from being immediately committed to your DB, you can turn off "Auto-Commit" by connection/console. This can be turned off from the toolbar, as shown in the image below, or in the bottom right of the connection properties window. From the properties window there is also a checkbox for "Read Only" if you are only pulling data. [![Data Grip Auto-commit check box position](https://i.stack.imgur.com/ls3H3.png)](https://i.stack.imgur.com/ls3H3.png) There is a tab on the bottom for "Database Changes" that tracks changes and must be reviewed prior to force committing the changes back to the source DB.
365833
Here is the code snippet ``` string search = textBox1.Text; int s = Convert.ToInt32(search); string conn="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\Data.accdb"; string query="SELECT playerBatStyle FROM Player where playerID='" + s + "; OleDbDataAdapter dAdapter=new OleDbDataAdapter (query ,conn ); OleDbCommandBuilder cBuilder=new OleDbCommandBuilder (dAdapter ); DataTable dTable=new DataTable (); dAdapter .Fill (dTable ); dataGridView1.DataSource = dTable; ```
You had an unclosed single quote in your where clause. Try this instead: ``` string query = String.Format("SELECT playerBatStyle FROM Player where playerID={0}", s); ```
366203
Basically i need a program that given a URL, it downloads a file and saves it. I know this should be easy but there are a couple of drawbacks here... First, it is part of a tool I'm building at work, I have everything else besides that and the URL is HTTPS, the URL is of those you would paste in your browser and you'd get a pop up saying if you want to open or save the file (.txt). Second, I'm a beginner at this, so if there's info I'm not providing please ask me. :) I'm using Python 3.3 by the way. I tried this: ``` import urllib.request response = urllib.request.urlopen('https://websitewithfile.com') txt = response.read() print(txt) ``` And I get: ``` urllib.error.HTTPError: HTTP Error 401: Authorization Required ``` Any ideas? Thanks!!
You can do this easily with the requests library. ``` import requests response = requests.get('https://websitewithfile.com/text.txt',verify=False, auth=('user', 'pass')) print(response.text) ``` to save the file you would type ``` with open('filename.txt','w') as fout: fout.write(response.text): ``` (I would suggest you always set verify=True in the resquests.get() command) [Here is the documentation](http://docs.python-requests.org/en/latest/user/authentication/):
366333
I am following a documentation and executing some commands in Windows 10 command prompt. I have executed the first two commands using `setx`, since `setx` is the Windows' equivalent for export and when I try the third command `$OPENAI_LOGDIR` is not properly detected. Can someone help with the equivalent of this in windows? commands ``` export OPENAI_LOG_FORMAT='stdout,log,csv,tensorboard' export OPENAI_LOGDIR=path/to/tensorboard/data tensorboard --logdir=$OPENAI_LOGDIR ```
It depends on the shell. The $ symbol starts a name and indicates that's a variable in most Unix shells. To do the same in Windows cmd use `%OPENAI_LOGDIR%`. In Windows PowerShell use the same syntax as bash, i.e. `$OPENAI_LOGDIR`. However if it's an environment variable in PowerShell you need to access use the `env:` prefix: `$env:OPENAI_LOGDIR`
366458
I have two SQL tables in a SQL Server 2008 database that look like the following: ``` Customer -------- ID Name Order ----- ID CustomerID Total ``` I need to figure out what the most number of order placed by a customer has been. At this point, I've gotten here: ``` SELECT MAX([OrderCount]) FROM ( SELECT COUNT(o.[ID]) as 'OrderCount' FROM [Order] o GROUP BY o.[CustomerID] ) ``` When I execute this statement, I get a message that says "Incorrect syntax near ')'". My subquery works. Which would imply the problem is with SELECT MAX([OrderCount]), but everything looks correct to me (granted, i'm not a sql whiz). What am I doing wrong here? Am I even attacking this sql query correctly? Thank you
You are basically there: ``` SELECT MAX([OrderCount]) FROM ( SELECT COUNT(o.[ID]) as 'OrderCount' FROM [Order] o GROUP BY o.[CustomerID] ) t ``` You need the alias at the end. Another way to write this without the subquery is: ``` SELECT top 1 COUNT(o.[ID]) as OrderCount FROM [Order] o GROUP BY o.[CustomerID] order by OrderCount desc ```
366783
I've looked everywhere including [Apple's sample app](https://developer.apple.com/library/content/samplecode/PotLoc/Listings/Potloc_WatchKit_Extension_StreamLocationInterfaceController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_WatchKit_Extension_StreamLocationInterfaceController_swift-DontLinkElementID_11). But I can't find anywhere when I can request location without needing any code running on the phone, the below code when used in an 'interface controller' returns a "not determined" status. I did check that my info.plist has the privacy key values set. ``` import Foundation import CoreLocation class LocationManager: NSObject, CLLocationManagerDelegate { /// Location manager to request authorization and location updates. let manager = CLLocationManager() /// Flag indicating whether the manager is requesting the user's location. var isRequestingLocation = false var workoutLocation: CLLocation? func requestLocation() { guard !isRequestingLocation else { manager.stopUpdatingLocation() isRequestingLocation = false return } let authorizationStatus = CLLocationManager.authorizationStatus() switch authorizationStatus { case .notDetermined: isRequestingLocation = true manager.requestWhenInUseAuthorization() case .authorizedWhenInUse: isRequestingLocation = true manager.requestLocation() case .denied: print("Location Authorization Denied") default: print("Location AUthorization Status Unknown") } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard !locations.isEmpty else { return } DispatchQueue.main.async { let lastLocationCoordinate = locations.last!.coordinate print("Lat = \(lastLocationCoordinate.latitude)") print("Long = \(lastLocationCoordinate.longitude)") self.isRequestingLocation = false } } } ``` Main App info.plist ``` <key>NSLocationAlwaysUsageDescription</key> <string>We will read your location while performing a workout to create a workout route</string> <key>NSLocationUsageDescription</key> <string>We will read your location while performing a workout to create a workout route</string> <key>NSLocationWhenInUseUsageDescription</key> <string>We will read your location while performing a workout to create a workout route</string> ``` Watch Extension info.plist ``` <key>NSLocationAlwaysUsageDescription</key> <string>We will read your location while performing a workout to create a workout route</string> <key>NSLocationUsageDescription</key> <string>We will read your location while performing a workout to create a workout route</string> <key>NSLocationWhenInUseUsageDescription</key> <string>We will read your location while performing a workout to create a workout route</string> ```
The user can only grant access to their location on their iPhone. It cannot be done on the Apple Watch. If the iPhone to which the Watch is connected is unlocked, the prompt asking for location usage authorization will be displayed on the phone; you don't need to run any code for this on iOS. From the [App Programming Guide for watchOS: Leveraging iOS Technologies](https://developer.apple.com/library/content/documentation/General/Conceptual/WatchKitProgrammingGuide/iOSSupport.html) > > Be aware that permission for some technologies must be accepted on the > user’s iPhone. The user must grant permission to use specific system > technologies, such as Core Location. Using one of these technologies > in your WatchKit extension triggers the appropriate prompt on the > user’s iPhone. Apple Watch also displays a prompt of its own, asking > the user to view the permission request on the iPhone. For information > about the technologies that require user permission, see “Supporting > User Privacy” in App Programming Guide for iOS. > > >
367149
> > By inspection, find the inverse of the given one to one matrix > operator > > > 1.The reflection about the $xy-plane$ in $R^3$ > > > 2.The dilation by a factor of 5 in $R^2$ > > > 3.The reflection about the $z-axis$ in $R^3$ > > > 4.The contraction by a factor of $\frac{1}{3}$ in $R^3$ > > > 5.The rotaion through an angle of $\frac{\pi}{3}$ in $R^3$ > > > How to inspect it? Can someone just give some hint?
*Hints:* a) The transformations here are * reflection * dilation, contraction (scaling) * rotation These are linear transformations, so you can restrict yourself to $\mathbb{R}^{2\times 2}$ matrices for the 2D vectors and $\mathbb{R}^{3\times 3}$ for the 3D vectors. (The more general case would involve affine transformations, and thus homogenous coordinates needing an extra coordinate to use convenient matrices for the transformations) I would as well interpret "inspection" as "try it out". So you could think how a matrix $A$ of the above kind would act on an input vector $x = (x\_i)$ to produce the wanted output vector $y = A x$, with $y\_i = \sum\_j a\_{ij} x\_j$. b) Let us look at the easy one, 2.: We need to find a matrix $A$ such that $$ A x = 5 x \iff \\ \begin{pmatrix} 5 x\_1 \\ 5 x\_2 \end{pmatrix} = \begin{pmatrix} a\_{11} & a\_{12} \\ a\_{21} & a\_{22} \end{pmatrix} \begin{pmatrix} x\_1 \\ x\_2 \end{pmatrix} = \begin{pmatrix} a\_{11} x\_1 & a\_{12} x\_2 \\ a\_{21} x\_1 & a\_{22} x\_2 \end{pmatrix} $$ you could now figure out the coefficients $a\_{ij}$ from component-wise comparison. Then you could derive the inverse from it. Alternative: What is the inverse of increasing by a factor 5? Using the operation and then its inverse must give the original vector. You could go directly for the matrix of the inverse operation. c) Now try 1.: Here a vector has three coordinates $x = (x\_1, x\_2, x\_3)^t$. A reflection at the $x$-$y$-plane affects the $z$-coordinate. So the problem is to find an $A$ such that $$ A (x\_1, x\_2, x\_3)^t = (x\_1, x\_2, -x\_3)^t $$ The plane itself consists of the vectors $(x\_1, x\_2, 0)^t$ which will not be changed by the reflection. d) Regarding 3.: If we mirror a vector $x$ at some axis $a$, we get an image vector $y$ and expect the axis $a$ to bisect the line orthogonal which connects $x$ and $y$. A vector from the origin to a point on the axis should not be changed by the transformation. e) Regarding 4.: If you solved 2. this should be a piece of cake. The additional dimension should be easy to handle. f) Regarding 5.: @EmilioNovati pointed already out in the comments below, that this problem lacks information to nail it down to a unique solution. You need to know around which axis you rotate. Rotations themselves have the property that they preserve the length of the vectors. This they share with reflections. Also there is a restriction on how the coordinates are permuted, the determinant of the matrix must be $+1$. The easy case is to figure out how a 2D vector will get changed by a rotation in the $x$-$y$-plane (around the $z$-axis). This idea will extend to the 3D case and has to involve extra transformations if the axis of rotation is not parallel to one of the coordinate system axis or is not through the origin.
367193
I'm interested in registering my view controller for KVO notifications on a model object's properties. The "member" property of the view controller is an NSManagedObject subclass and uses Core Data's provided accessor methods (via `@dynamic`). It has four properties: firstName, lastName, nickname, and bio, which are all NSStrings. *Here's the registering and unregistering for KVO:* ``` - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.member addObserver:self forKeyPath:@"firstName" options:NSKeyValueObservingOptionNew context:kFHMemberDetailContext]; [self.member addObserver:self forKeyPath:@"lastName" options:NSKeyValueObservingOptionNew context:kMemberDetailContext]; [self.member addObserver:self forKeyPath:@"nickname" options:NSKeyValueObservingOptionNew context:kMemberDetailContext]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.member removeObserver:self forKeyPath:@"firstName" context:kMemberDetailContext]; [self.member removeObserver:self forKeyPath:@"lastName" context:kMemberDetailContext]; [self.member removeObserver:self forKeyPath:@"nickname" context:kMemberDetailContext]; } ``` *Implementation of callback method* ``` - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context != kFHMemberDetailContext) { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; return; } self.kvoCount++; if ([keyPath isEqualToString:@"firstName"]) { NSLog(@"firstName KVO'd"); } else if ([keyPath isEqualToString:@"lastName"]) { NSLog(@"lastName KVO'd"); } else if ([keyPath isEqualToString:@"nickname"]) { NSLog(@"nickname KVO'd"); } } ``` When I drive this code from a unit test, I receive three notifications when I modify the "bio" property, and four notifications when modifying firstName, lastName, or nickname. That's consistently three too many notifications! It seems to be something simple that I've done wrong, but I can't figure out what's causing the extraneous notifications. If I po the change dictionary, the NSKeyValueChangeKindKey is always NSKeyValueChangeSetting, but for the unwanted notifications the NSKeyValueChangeNewKey is NULL. *The test driving this bit of code:* ``` - (void)setUp { NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:@[[NSBundle mainBundle]]]; NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom]; [psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:NULL]; NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; [managedObjectContext setPersistentStoreCoordinator:psc]; member = [NSEntityDescription insertNewObjectForEntityForName:@"Member" inManagedObjectContext:managedObjectContext]; UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:[NSBundle mainBundle]]; memberDetailVC = [sb instantiateViewControllerWithIdentifier:kFHMemberDetailTableViewControllerIdentifier]; [memberDetailVC setMember:member]; } - (void)tearDown { [memberDetailVC viewWillDisappear:NO]; } - (void)testChangesToMemberFirstNamePropertyCausesKVO { [memberDetailVC viewWillAppear:NO]; [member setFirstName:@"Unit Test"]; STAssertTrue(memberDetailVC.kvoCount, (NSInteger)1, @"View controller should have received a single KVO notification"); } ``` Like I said, this fails having received 4 notifications (one for each property with a new value of null, and then finally the expected notification).
So the answer to my problem is an issue with my unit test. In my setup method, I'm creating the Managed Object Context, inserting a Managed Object into it, and then the context is getting dealloc'd at the end of my `-setUp` method. If I hold onto the MOC as an ivar in the test suite, the notifications come in as expected. This raises all kind of other questions, but I'll leave those for some other time. Right now it would seem I should turn off the computer and go have a whiskey or two ... or three.
367624
I must integrate: $$ \int \int\_D x^2y^2 dx dy$$ in the first quadrant. This is a triangle with vertices in $(0,0)$, $(0,1)$ and $(1,0)$. I tried to draw it in mathematica with implicit region: ``` R = ImplicitRegion[{x + y <= 1}, {x, y}]; Plot[R, {x, 0, 1}, {y, 0, 1}] ``` This is wrong and in addition I want to highlight that it is in the first quadrant (highlight $x$ and $y$ axis. Can someone please help me with that?
Try: ``` reg = ImplicitRegion[{x + y <= 1, x >= 0, y >= 0}, {x, y}] ``` You can then visualize the region with `RegionPlot[reg]`, or use it as the domain of an integral: ``` Integrate[x^2 y^2, Element[{x, y}, reg]] (* Out: 1/180 *) ```
367882
There are many ways to verify the schema of two data frames in spark like [here](https://stackoverflow.com/questions/47862974/schema-comparison-of-two-dataframes-in-scala). But I want to verify the schema of two data frames only in SQL, I mean SparkSQL. **Sample query 1:** ``` SELECT DISTINCT target_person FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('columnA','ColumnB') AND TABLE_SCHEMA='ad_facebook' ``` **Sample query 2:** ``` SELECT count(*) FROM information_schema.columns WHERE table_name = 'ad_facebook' ``` I know that there is no concept of a database (schema) in spark, but I read about metastore that it contains schema information etc. Can we write SQL queries like above in SparkSQL? EDIT: I am just checking why show create table is not working on spark sql, is it because it's a temp table? ``` scala> val df1=spark.sql("SHOW SCHEMAS") df1: org.apache.spark.sql.DataFrame = [databaseName: string] scala> df1.show +------------+ |databaseName| +------------+ | default| +------------+ scala> val df2=spark.sql("SHOW TABLES in default") df2: org.apache.spark.sql.DataFrame = [database: string, tableName: string ... 1 more field] scala> df2.show +--------+---------+-----------+ |database|tableName|isTemporary| +--------+---------+-----------+ | | df| true| +--------+---------+-----------+ scala> val df3=spark.sql("SHOW CREATE TABLE default.df") org.apache.spark.sql.catalyst.analysis.NoSuchTableException: Table or view 'df' not found in database 'default'; at org.apache.spark.sql.catalyst.catalog.SessionCatalog.requireTableExists(SessionCatalog.scala:180) at org.apache.spark.sql.catalyst.catalog.SessionCatalog.getTableMetadata(SessionCatalog.scala:398) at org.apache.spark.sql.execution.command.ShowCreateTableCommand.run(tables.scala:834) at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:58) at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:56) at org.apache.spark.sql.execution.command.ExecutedCommandExec.executeCollect(commands.scala:67) at org.apache.spark.sql.Dataset.<init>(Dataset.scala:182) at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:67) at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:623) ... 48 elided ```
Schema can be queried using `DESCRIBE [EXTENDED] [db_name.]table_name` See <https://docs.databricks.com/spark/latest/spark-sql/index.html#spark-sql-language-manual>
367921
The following code simulates finding the closest pair but when I generate a random amount of pairs greater than 250 it throws a stack overflow error. But 250 pairs and any even amount under seem to work fine. Any ideas? The error occurs at the recursive call of ComparePoints under the if statement. ``` public class Divide { Point2D closest1; Point2D closest2; double Distance = Double.MAX_VALUE; public Divide(Point2D[] RandArray){ SortArray s = new SortArray(); RandArray = s.SortPointsX(RandArray); SplitAndConquer(RandArray); } private double ComparePoints(Point2D a, Point2D b, Point2D[] s, int CurrentPoint, int NextPoint){ if(s[CurrentPoint] != null && s[NextPoint] != null){ if (Distance > a.distance(b) && (a.getX() != b.getX() || a.getY() != b.getY())){ Distance = a.distance(b); closest1 = new Point2D.Double(a.getX(), a.getY()); closest2 = new Point2D.Double(b.getX(), b.getY()); } if (NextPoint == (s.length - 1)){ NextPoint = s.length - ((s.length - 1) - CurrentPoint); CurrentPoint++; } if (CurrentPoint != (s.length - 1)){ if (NextPoint != (s.length - 1)){ NextPoint++; ComparePoints(s[CurrentPoint], s[NextPoint], s, CurrentPoint, NextPoint); } } if (CurrentPoint == (s.length - 1)){ CurrentPoint = 0; NextPoint = 0; } } return Distance; } private void SplitAndConquer(Point2D[] RandArray){ double median = RandArray[RandArray.length/2].getX(); int countS1 = 0; int countS2 = 0; boolean exact = false; int CurrentPoint = 0; int NextPoint = 0; Point2D[] s1 = new Point2D[RandArray.length/2]; Point2D[] s2 = new Point2D[RandArray.length/2]; for (int i = 0; i < RandArray.length; i++){ if (RandArray[i].getX() < median){ s1[countS1] = RandArray[i]; countS1++; } else if (RandArray[i].getX() > median){ s2[countS2] = RandArray[i]; countS2++; } else if (RandArray[i].getX() == median && exact == false){ s2[countS2] = RandArray[i]; exact = true; countS2++; } else if (RandArray[i].getX() == median && exact == true) { s1[countS1] = RandArray[i]; exact = false; countS2++; } } if (s1[0] != null && s1[1] != null){ Distance = ComparePoints(s1[0], s1[1], s1, CurrentPoint, NextPoint); Distance = ComparePoints(s2[0], s2[0], s2, CurrentPoint, NextPoint); }else{ System.out.println ("One of the subsets does not contain enough points!"); } CheckMid(RandArray, Distance, median, CurrentPoint, NextPoint); PrintClosest(); } private void PrintClosest() { System.out.println("The closest pair found using Divide " + "And Conquer is at (" + closest1.getX() + " " + closest1.getY() + "), and (" + closest2.getX() + " " + closest2.getY() + ")"); System.out.println("The distance between the pairs is: " + Distance); } private void CheckMid(Point2D[] randArray, double d, double m, int current, int next) { int MidCount = 0; Point2D[] MidArray = new Point2D[randArray.length]; for(int i = 0; i < randArray.length; i++){ if(randArray[i].getX() > (m - d) && randArray[i].getX() < (m + d)){ MidArray[MidCount] = randArray[i]; MidCount++; } } if (MidArray[0] != null && MidArray[1] != null){ ComparePoints(MidArray[0], MidArray[1], MidArray, current, next); } } } ```
Sounds like you're exceeding the the amount of stack memory allocated for your program. You can change the stack size with the -Xss option. E.g `java -Xss 8M` to change stack size to 8MB and run your program.
368599
I am attempting to Impersonate an administrator account from a LocalSystem Service in order to get data from administrators HKEY CURRENT USER registry - in order to impersonate I am using the codeproject code found at the following site written by Uwe Keim: [Impersonator](http://www.codeproject.com/KB/cs/zetaimpersonator.aspx?fid=171054&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=1#xx0xx) My source code is as follows: ``` using (new Impersonator("user", ".", "pass")) { RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software\\CompanyName"); string sValue = rk.GetValue("Value", "").ToString(); rk2.Close(); } ``` My expectation was that sValue would be from the user/pass account (as I am impersonating it) but oddly enough it is still the sValue from the LocalSystem account where my service is runnning ... Any clues on what I am doing wrong? Any help would be much appreciated. Thanks,
Everything I've read on the subject seems to indicate that impersonation should get you access to the HKEY\_CurrentUser for the impersonated account. However, it could be a quirk in the .NET Registry implementation. This is just a hunch, and an untested one at that, but have you considered using Registry.Users instead of Registry.CurrentUser? You'll need to [find the SID](http://www.codeproject.com/KB/cs/getusersid.aspx) for the Administrator account, but you should be able to deduce that using Regedit
368673
I am uploading a file to an api, and I have to copy my requestStream to a FileStream in order to post the file to the API. My code below works, but I have to save the file to a temp folder to create the FileStream, and then I have to clean up the temp folder again after the operation. Is there a cleaner way of doing that - e.g. creating the FileStream in memory (if that's possible) instead of saving it to the disk? ``` Stream requestStream = await Request.Content.ReadAsStreamAsync(); //Create filestream by making a temporary physical file using (FileStream fileStream = System.IO.File.Create(@"C:\tempFolder\" fileName)) { await requestStream.CopyToAsync(fileStream); var postedFile = ms.CreateMedia(fileName, folder.Id, "file"); postedFile.SetValue("umbracoFile", fileName, fileStream); ms.Save(postedFile); } // Clean up if ((System.IO.File.Exists(@"C:\tempFolder\" + fileName))) { System.IO.File.Delete(@"C:\tempFolder\" + fileName); } ```
The problem is that your call to `event.respondWith()` is inside your top-level promise's `.then()` clause, meaning that it will be asynchronously executed after the top-level promise resolves. In order to get the behavior you're expecting, `event.respondWith()` needs to execute synchronously as part of the `fetch` event handler's execution. The logic inside of your promise is a bit hard to follow, so I'm not exactly sure what you're trying to accomplish, but in general you can follow this pattern: ``` self.addEventListerner('fetch', event => { // Perform any synchronous checks to see whether you want to respond. // E.g., check the value of event.request.url. if (event.request.url.includes('something')) { const promiseChain = doSomethingAsync() .then(() => doSomethingAsyncThatReturnsAURL()) .then(someUrl => fetch(someUrl)); // Instead of fetch(), you could have called caches.match(), // or anything else that returns a promise for a Response. // Synchronously call event.respondWith(), passing in the // async promise chain. event.respondWith(promiseChain); } }); ``` That's the general idea. (The code looks even cleaner if you end up replacing promises with `async`/`await`.)
368751
Several days ago, I asked a question in serverfault. It is a question related to a problem I'm having in an Ubuntu proxy server. No one gave me an answer for two days, not even a comment or a clue. So I headed to the Serverfault chat room, [The Comms Room](http://chat.stackexchange.com/rooms/127/the-comms-room), and asked the guys out there about that question. They told me that it is not a bad question, but it'll get more chance at the unix site. After transferring the question here, still no response, even it got a vote to close claiming it is too localized. The Unix chat room is almost always empty (never interacting). So I wanna know what's wrong? and how it can be too localized? I'm asking for any kind of guidance or pointing to what might be the problem, and it is not too localized (but that's my problem). Here is a link to the question: [Sarg report error](https://unix.stackexchange.com/questions/41250/sarg-report-error)
This question is about a tool that few people use and is pretty long. This is an observation, not a criticism. I think it's well-written, you give a lot of facts, and they're (potentially) relevant. Unfortunately, such a question is not exciting: it isn't applicable to a wide audience, it isn't easy to understand. I expect most people saw the title, thought “Sarg, what's sarg, I don't care about this question”; and the few that viewed it went “too long, stopping reading”. I disagree that the question is too localized. Sure, it may end up being some peculiar line in your log files which nobody can reproduce. Even if that's the issue, how to diagnose the issue, how to locate the troublesome line are good questions that are applicable at least to the not-*that*-narrow world of Sarg users.
368843
I've an image and its pixels are in grid blocks. each pixel occupy 20x20px block of a grid . here is the image [![enter image description here](https://i.stack.imgur.com/l7ARA.jpg)](https://i.stack.imgur.com/l7ARA.jpg) I want to read color of each block of that grid. Here is the code which i tried. ``` Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc); for(int y=0; y<bmp.getHeight(); y=y+20){ for(int x=0; x<bmp.getWidth(); x=x+20){ pixelColor = bmp.getPixel(x,y); } } ``` The problem is now that, colors which are being read are of very slight difference and in result it is picking too many colors. For example in black color case it picks almost 10 black colors which slightly varies from each other. Please help me to pick all unique colors. any help would be much appreciated. Thank you
I've finally figured out myself by using [Palette](https://developer.android.com/reference/android/support/v7/graphics/Palette.html) class in android I've used its nested class Palette.Swatch to get all color swatches in the image. here is how i did this ``` ArrayList<Integer> color_vib = new ArrayList<Integer>(); Bitmap bitmap = BitmapFactory.decodeResource( getResources(), R.drawable.abc ); Palette.from( bitmap ).generate( new Palette.PaletteAsyncListener() { @Override public void onGenerated( Palette palette ) { //work with the palette here for( Palette.Swatch swatch : palette.getSwatches() ) { color_vib.add( swatch.getRgb() ); } } }); ``` Now I've all unique colors of any blocky pixelated image :)
368872
Resuming from Hibernate on my Windows 7 desktop takes an awefully long time, I'd guess 5 minutes. It is an Intel DP35DP with 64 bit Intel Core2 Duo E6750, 2GB and 2x320GB RAID0. Sony Lin's blog post [Fixing Windows 7 can't return from stand by (sleep) or hibernate when Readyboost is used](http://www.sonylin.net/Computers/windows_7_standby.php) points to the problem. It would seem that Windows 7 has to recreate the ReadyBoost cache, possibly at low speed, before it is able to come back up. Removing my ReadyBoost setup (Lexar Jump Drive Lightning II 120x 18MB/s 2GB USB key) eliminates the long resume issue. Challenge is that I'd like to use ReadyBoost, without having to wait for my system when it resumes? Anyone able to help?
The problem may also be that your hard disk and the ReadyBoost is has different formats (e.g. HD is NTFS and the USB/Flash Fat32). Reformat (the latter). See: [Microsoft Answers](http://answers.microsoft.com/en-us/windows/forum/windows_7-performance/black-screen-after-hibernation-with-readyboost-sd/1d679969-7888-47c5-b748-6ddebcc2ad76) A rather late answer ,-) but other may pop in via Google and find it useful.
369238
In a database that contains many tables, I need to write a SQL script to insert data if it is not exist. Table **currency** ``` | id | Code | lastupdate | rate | +--------+---------+------------+-----------+ | 1 | USD | 05-11-2012 | 2 | | 2 | EUR | 05-11-2012 | 3 | ``` Table **client** ``` | id | name | createdate | currencyId| +--------+---------+------------+-----------+ | 4 | tony | 11-24-2010 | 1 | | 5 | john | 09-14-2010 | 2 | ``` Table: **account** ``` | id | number | createdate | clientId | +--------+---------+------------+-----------+ | 7 | 1234 | 12-24-2010 | 4 | | 8 | 5648 | 12-14-2010 | 5 | ``` I need to insert to: 1. `currency` (`id=3, Code=JPY, lastupdate=today, rate=4`) 2. `client` (`id=6, name=Joe, createdate=today, currencyId=Currency with Code 'USD'`) 3. `account` (`id=9, number=0910, createdate=today, clientId=Client with name 'Joe'`) **Problem:** 1. script must check if row exists or not before inserting new data 2. script must allow us to add a foreign key to the new row where this foreign related to a row already found in database (as currencyId in client table) 3. script must allow us to add the current datetime to the column in the insert statement (such as `createdate` in `client` table) 4. script must allow us to add a foreign key to the new row where this foreign related to a row inserted in the same script (such as `clientId` in `account` table) **Note:** I tried the following SQL statement but it solved only the first problem ``` INSERT INTO Client (id, name, createdate, currencyId) SELECT 6, 'Joe', '05-11-2012', 1 WHERE not exists (SELECT * FROM Client where id=6); ``` this query runs without any error but as you can see I wrote `createdate` and `currencyid` manually, I need to take currency id from a select statement with where clause (I tried to substitute 1 by select statement but query failed). This is an example about what I need, in my database, I need this script to insert more than 30 rows in more than 10 tables. any help
If you're not going to need any methods specific to `B`, in other words, you're strictly going to use it as an `A`, it's an advantage for readability to state so. But the main advantage comes to light when you use the general type in a method declaration: ``` public String resolveName(A a) { ... } ``` If you used `B` here for no good reason, then you would unnecessarily cripple your method. It could have worked for any `A`, but it works only for `B`.
369305
I am writing a html document in which the output is as follows: ![enter image description here](https://i.stack.imgur.com/ZdweT.png) I have two problems with it: 1. I want to line up the first three input fields. 2. Radio buttons are not working properly. My html code is: ``` <!DOCTYPE html> <html> <head> <title> Contact Us </title> <link rel="stylesheet" href="styleit.css"/> </head> <body> <h1> Contact Us </h1> <form id="form"> Your Name : <input type = "text" value = "name" > </br> Mobile no : <input type = "text" value = " Mob" ></br> Email : <input type = "text" value = "Email"></br> Best time to call: <input type="radio" >evening <input type="radio">morning </br> Languages: <br> <input type="checkbox" > C <input type="checkbox" > C++ <br> <input type="checkbox" > C# <input type="checkbox" > python<br> <input type="checkbox" > Java <input type="checkbox" > CSS </input> <br> <input type="submit" value="submit"> </form> </body> </html> ``` My css code is: ``` form input { margin: 5px; display: inline-block; width: 150px; } h1 { text-align:center; } ``` What am I doing wrong ?
Pass the URL to the cron script, for example as environment variable or CLI argument: ``` */1 * * * * SITE_URL=example.com /usr/bin/php /pathto/send.php # or */1 * * * * /usr/bin/php /pathto/send.php example.com ``` In the script: ``` $siteURL = getenv('SITE_URL'); // or $siteURL = $argv[1]; ``` That's a better alternative to a) exposing your cron script publicly through the web server and b) going the long way round through an HTTP request for something that doesn't need it.
369500
I need to add a quantity increment button in cart page and mini cart popup like this. [![enter image description here](https://i.stack.imgur.com/meUfu.png)](https://i.stack.imgur.com/meUfu.png) I added the button but I can't assign the functionality. This is what I did *app/code/Amsi/UserManagement/view/frontend/layout/checkout\_cart\_index.xml* ``` <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.cart.form"> <block class="Magento\Framework\View\Element\RendererList" name="checkout.cart.item.renderers.override" as="renderer.list.custom"/> <arguments> <argument name="renderer_list_name" xsi:type="string">checkout.cart.item.renderers.override</argument> </arguments> </referenceBlock> </body> </page> ``` app/code/Amsi/UserManagement/view/frontend/layout/checkout\_cart\_item\_renderers.xml ``` <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.cart.item.renderers.override"> <block class="Magento\Checkout\Block\Cart\Item\Renderer" as="default" template="Amsi_UserManagement::cart/item/default.phtml" /> <block class="Magento\Checkout\Block\Cart\Item\Renderer" as="simple" template="Amsi_UserManagement::cart/item/default.phtml" /> </referenceBlock> </body> </page> ``` *app/code/Amsi/UserManagement/view/frontend/templates/cart/item/default.phtml* ``` ....... <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"> <div class="field qty"> <label class="label" for="cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty"> <span><?= /* @escapeNotVerified */ __('Qty') ?></span> </label> <div class="control qty"> <button>-</button> <input id="cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty" name="cart[<?= /* @escapeNotVerified */ $_item->getId() ?>][qty]" data-cart-item-id="<?= /* @escapeNotVerified */ $_item->getSku() ?>" value="<?= /* @escapeNotVerified */ $block->getQty() ?>" type="number" size="4" title="<?= $block->escapeHtml(__('Qty')) ?>" class="input-text qty" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty"/> <button >+</button> </div> </div> </td> ...... ``` How can i assign functionality to increment and decrements buttons ?
app/code/Amsi/UserManagement/view/frontend/templates/cart/item/default.phtml I have added For both increment and decrementing quantity. You can add the button near Quantiy using below code. ``` <div class="control qty"> <input id="cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty" name="cart[<?= /* @escapeNotVerified */ $_item->getId() ?>][qty]" data-cart-item-id="<?= /* @escapeNotVerified */ $_item->getSku() ?>" value="<?= /* @escapeNotVerified */ $block->getQty() ?>" type="number" size="4" title="<?= $block->escapeHtml(__('Qty')) ?>" class="input-text qty" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty"/> /*Code to add increment and decrement button*/ <div class="qty_control"> <button type="button" id="<?= /* @escapeNotVerified */ $_item->getId() ?>-upt" class="increaseQty"></button> <button type="button" id="<?= /* @escapeNotVerified */ $_item->getId() ?>-dec" class="decreaseQty"></button> </div> </div> <script type="text/javascript"> require(["jquery"],function($){ $('#<?php echo $_item->getId();?>-upt, #<?php echo $_item->getId();?>-dec').on("click",function(){ var $this = $(this); var ctrl = ($(this).attr('id').replace('-upt','')).replace('-dec',''); var currentQty = $("#cart-"+ctrl+"-qty").val(); if($this.hasClass('increaseQty')){ var newAdd = parseInt(currentQty)+parseInt(1); $("#cart-"+ctrl+"-qty").val(newAdd); }else{ if(currentQty>1){ var newAdd = parseInt(currentQty)-parseInt(1); $("#cart-"+ctrl+"-qty").val(newAdd); } } }); }); </script> ```
369561
I have got the Header values in Header Object. but I need "Last-Modified" into the string object for comparison. Please could you tell me how should I get the last header into the string. ``` HttpClient client = new DefaultHttpClient(); //HttpGet get = new HttpGet(url); HttpHead method = new HttpHead(url); HttpResponse response = client.execute(method); Header[] s = response.getAllHeaders(); String sh = String.valueOf(s); System.out.println("The value of sh:"+sh); System.out.println("The header from the httpclient:"); for (int i = 0; i < s.length; i++) { Header hd = s[i]; System.out.println("Header Name: "+hd.getName() + " " + " Header Value: " + hd.getValue()); } String last-modified = // here I need to convert this header(last-modified); ```
In many circumstances, you get just one Last-Modified header, so you could simply use: ``` String lastModified = response.getHeader("last-modified"); if (lastModified != null) { // in case the header isn't set // do something } ``` For multiple values, the JavaDoc says: *If a response header with the given name exists and contains multiple values, the value that was added first will be returned.*
369714
`ACPI PCC Probe Failed` is the error that pops up instead of the default GRUB loader after I updated my kernel to 3.19. I searched around and couldn't find much information except that it is a known error and it is registered in kernel.org's launchpad <https://bugzilla.kernel.org/show_bug.cgi?id=92551>. My question is, is anyone else facing it?, what are the impacts of this? And if only an update in the future can fix it, any suggestions or safety tips till then?
Apparently it is a harmless message related to a 'PCC' driver: > > So it looks like you build the PCC mailbox driver which is new in 3.19-rc and > that driver fails to load, because it doesn't find hardware to work with. > > > The message is harmless, but it also is not useful. The driver in question > seems to be overly verbose to me in general. > > > That is what I gleaned from this [conversation](http://permalink.gmane.org/gmane.linux.power-management.general/56400).
369901
I'm attempting to change the body color using the options provided in a dropdown menu and saving those changes so when the user refreshes the page, the background color will be equal to what they set it as. However I'm having a problem in changing the background color according to the dropdown menu options. **HTML** ``` <button class="btn-secondmenu">Button</button> <select name="colors" id="colors"> <option value="red">Red</option> <option value="green" selected="selected">Green</option> <option value="yellow">Yellow</option> <option value="black">Black</option> </select> ``` **JS** ``` $(function(){ var select = document.getElementById("colors"); select.onchange = function(){ var selectedColor = select.options[select.selectedIndex].value; alert(selectedString); } if (localStorage.getItem('background') !== null) { getColour = localStorage.background; $('.bdy').css('background', getColour); } else { getColour = 'green'; } $('.btn-secondmenu').click(function(){ if(getColour == 'blue'){ localStorage.removeItem('background'); $('.bdy').css('background', 'red'); localStorage.setItem('background', 'red'); } else { getColour = 'blue'; localStorage.removeItem('background'); $('.bdy').css('background', 'blue'); localStorage.setItem('background', 'blue'); } }); }); ``` Any suggestions would be greatly appreciated, thank you!
You are over complicating things here, you can achieve this in the `onchange` event of the dropdown, by getting the color with `$(this).val()` . ``` $('select[name="colors"]').change(function() { $('.bdy').css('background', $(this).val()); localStorage.setItem('background', $(this).val()); }); ``` **Note:** There's no need to remove the item from the localStorage then reset it, only use `.setItem()` it will override the value of the item, if you check [**Storage.setItem()** MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem) you can see that: > > The `setItem()` method of the Storage interface, when passed a key name and value, will **add** that key to the storage, **or update** that key's value if it already exists. > > > **Demo:** ```js $('select[name="colors"]').change(function() { $('.bdy').css('background', $(this).val()); //localStorage.setItem('background', $(this).val()); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="bdy"> <select name="colors" id="colors"> <option value="red">Red</option> <option value="green" selected="selected">Green</option> <option value="yellow">Yellow</option> <option value="black">Black</option> </select> </div> ```
370189
This is my main class, wherein run(), I am calling one another method install setup() which is for exe files. ``` public static void main(String[] args) { launch(args); } public void startSetup() { Runnable task=new Runnable() { @Override public void run() { try { Thread.sleep(1000); installSetup(); } catch (InterruptedException e) { e.printStackTrace(); } } }; Thread thread=new Thread(task); thread.start(); } ``` Here is my installsetup() method ``` public void installSetup() { try { Runtime.getRuntime().exec("cmd /c C:path\\setup.exe", null, new File("C:pathfolder\\01_Setupexe")); //process.waitFor(); } catch (IOException e) { e.printStackTrace(); } }; ``` I am calling it in my controller class like this: ``` public class Controller extends Thread { @FXML private ComboBox<?> dsetup; public void generateRandom() { if(dsetup.getValue()!=null) dsetupValue = dsetup.getValue().toString(); if(dsetupValue!=null)call.startSetup(); ``` Before I was just calling the install files with the exec method but not with threads concept, the application was working fine, but it was executing all the.exe files at once and then my interface freezes. So now I am using threads concept and trying to implement one thread at a time. I don't understand if it is a wrong way or not, but I do not get any error in console.
Runtime.exec has been obsolete for many years. Use [ProcessBuilder](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ProcessBuilder.html) instead: ``` ProcessBuilder builder = new ProcessBuilder("C:\\path\\setup.exe"); builder.directory(new File("C:pathfolder\\01_Setupexe")); builder.inheritIO(); builder.start(); ``` The inheritIO() method will make the spawned process use the Java program’s stdin, stdout, and stderr, so it will not hang waiting for input or waiting for an available output buffer. I doubt you need the new Thread or the sleep call, but I don’t know what files you’re calling or whether they depend on each other.
370543
I have a file structure that looks like this; ``` / /public -index.php -login.php /config.php /init.php /classes/ClassGroup/ClassName.class.php ``` \_\_autoload is defined in config.php, with absolute path to classes. config.php is required in index.php, but when I try to initiate a new class; ``` $user = new User_User; ``` Results in; ``` Fatal error: Class 'User_User' not found in /......./public/index.php on line 27 ``` It does not find it, and when trying to echo out something at the very start of \_\_autoload(), it doesnt do that either, so it seems to me that it does not run the function when not finding a class. Anyone have a clue what the problem might be? ``` function __autoload($class){ //echo "autoloader started"; $pieces = explode('_', $class); $path = __SITE_PATH.'/classes'; foreach( $pieces as $i ){ $path .= '/'.$i; } //echo "trying to include " .$path.".class.php"; require_once( $path . '.class.php' ); } ```
I found the problem, apparently this function is not being called automatically. Here is the fix; ``` spl_autoload_register('__autoload'); ``` This worked.
370871
Being pretty new to React, I'm facing an issue with navigating between 2 components. My app is as follows: App.js: ``` <div className="App"> <AuthProvider> <ThemeProvider theme={theme}> <CssBaseline /> <CartProvider> <SiteHeader/> <div> <Routes> {getRoutes(routes)} <Route path="/auth" element={<AuthPage />} /> <Route path="/cart" element={<CartPage />} /> <Route path="/search_results" element={<SearchResultPage />} /> <Route exact path="/_healthz" element={<HealthPage />} /> <Route path="/orders" element={<OrderPage />} /> <Route path="/category/:id" element={<CategoryPage />} /> <Route path="/product/:id" element={<ProductPage />} /> <Route path="/recipe/:id" element={<RecipePage />} /> <Route path="/" element={<HomePage />} /> </Routes> </div> </CartProvider> </ThemeProvider> </AuthProvider> </div> ``` As you can see, there is the SiteHeader component on every page. On this SiteHeader Component, I have a search field, triggering a navigate() to SearchResultPage Although the navigation itself is working (SearchResultPage is displaying), the parameters passed to navigate() are not propagated: ``` const search = () => { console.log("Calling search =>" + searchTerm); navigate("/search_results",{ state: { searchText: searchTerm }}); } ``` Below the code part for SearchResultPage: ``` export default function SearchResultPage(props) { console.log(props); let searchText = props.location.searchText ``` I don't understand why **props is empty** although I populated the navigate(path,state) correctly
### `react-router-dom` v6 Route components rendered via the element prop don't receive [route props](https://v5.reactrouter.com/web/api/Route/route-props). You can use hook for getting the state given you are navigating to that page by passing some state value as follows: ``` const location = useLocation(); const searchText = location?.state?.searchText; ``` For getting `state` you need to access `props.location.state` and then subsequent state property if you are using `v5` or below.
370906
I'd like to be able to link to certain portions of my page using URL fragments, eg: ```html <h3 id="overview">Overview</h3> ... <a href="#overview">Go to Overview</a> ``` Unfortunately the IDs i set from within LWC templates get overwritten, so my links don't work. Is there any way to define the ID attribute so it won't change?
Assuming you want to scroll to an element you have access to, you could always use scrollIntoView: ``` this.template.querySelector("h3").scrollIntoView(); ``` You can basically use any valid CSS selector to find a specific element (e.g. based on a data-id or another attribute). As far as I can tell, from a lack of documentation, you can't specify an anchor target. You would write the link like this: ``` <a onclick={handleClick} data-target-id="overview">Overview</a> ``` Given an H3 like this: ``` <h3 data-id="overview">Overview</h3> ``` And scroll with this: ``` handleClick(event) { let targetId = event.target.dataset.targetId; let target = this.template.querySelector(`[data-id="${targetId}"]`); target.scrollIntoView(); } ``` ((Note: Not tested, you might need to tweak the CSS selector.)) This assumes that the link and target are in the same template, otherwise this won't work. As far as I can tell, you can't target arbitrary elements.
371230
I am trying to build an image with stunnel. My base image OS is, > > Linux 2338b11efbe1 4.9.93-linuxkit-aufs #1 SMP Wed Jun 6 16:55:56 UTC > 2018 x86\_64 x86\_64 x86\_64 GNU/Linux > > > Installing libssl as below. ``` RUN apt-get -y update RUN apt-get -y install libssl1.0.0 libssl-dev && \ ln -s libssl.so.1.0.0 libssl.so.10 && \ ln -s libcrypto.so.1.0.0 libcrypto.so.10 ``` Below command lists the libs. > > RUN ls libssl.so.\* libcrypto.so\* > > > Output ------>>> ``` libcrypto.so.10 libssl.so.10 ``` Still, below command fails. > > RUN ./stunnel > > > **Error :-** > > ./stunnel: error while loading shared libraries: libssl.so.10: cannot > open shared object file: No such file or directory > > > Am i missing any other instruction here. Here is my complete dockerfile. ``` from <BASE_IMAGE> COPY stunnel . ENV DEBIAN_FRONTEND noninteractive RUN apt-get -y update && \ apt-get -y install libssl1.0.0 libssl-dev && \ ln -s libssl.so.1.0.0 libssl.so.10 && \ ln -s libcrypto.so.1.0.0 libcrypto.so.10 RUN ./stunnel ```
The failure mode suggests that your `libssl.so.10` is a broken symlink. Meaning the file `libssl.so.1.0.0` does not exist. A command such as `ln -s libssl.so.1.0.0 libssl.so.10` will succeed even if the target of the symlink does not (yet) exist. Plain `ls` on the broken symlinks will not report anything untoward either. If you want to be sure the symlinks are not broken, check each symlink with `test -e`. More specifically using `ln -s libssl.so.1.0.0 libssl.so.10` as some kind of 'fix' indicates you have other issues: the version component of a soname consists of abi-version.patch-level.backwards-compatibility fields and this is used by the loader to determine whether or not a given library file (symlinked or otherwise) could possibly match the library requested by the application. As you can see, using `ln` you are claiming that ABI version 1 is the same as ABI version 10. That may not work as expected. Finally, your `ln` commands use relative paths so you are probably working in the wrong directory -- hence why you end up creating broken symlinks. On Debian based systems `libssl.so` can typically be found in `/usr/lib/x86_64-linux-gnu/`. The `x86_64-linux-gnu` bit depends on architecture (as defined by Debian multi arch support), this particular example is valid for 64 bit x86 code.
371415
So I am trying pass in parameters to my "buttonClicked" function so that I can dynamically control what happens when you click the button. Every way that I try to do it on my own just breaks my code. I have searched many different sites and answers on stackOverflow, but I can't seem to find an answer. I am fairly new to objective C, especially with functions, So I could really use some help figuring out how to do this. Thanks in advance Here is my code thus far and what I am trying to do: ``` UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; NSLog(@"Hi 1!"); [button addTarget:self action:@selector(buttonClicked:buttonType:buttonID:) forControlEvents:UIControlEventTouchUpInside]; button.frame = CGRectMake(buttonViewXvalue, buttonViewYvalue, buttonViewWidth, buttonViewLength); [self.view addSubview:button]; ``` Then the Declaration in the Header File: ``` - (IBAction)buttonClicked:(id)sender theButtonType: (int)buttonType: theButtonID: (int) buttonID; ``` and the implementation: ``` - (IBAction)buttonClicked:(id)sender theButtonType: (int)buttonType: theButtonID: (int) buttonID { //Here I would use the buttonType and buttonID to create a new view. NSLog(@"Hi!"); } ```
You can't use multi-parameter methods with `addTarget:action:forControlEvents:`. Instead you might set the button's `tag`, then look up information later based on the tag.
371745
I am trying to call scheduled job from my UI action in my scoped application. But it gives me an error saying "SncTriggerSynchronizer is not allowed in scoped applications". Here is my code: ``` var rec = new GlideRecord('sysauto_script'); rec.get('name', 'Load Micello Files'); SncTriggerSynchronizer.executeNow(rec); ``` Can anyone please tell me how I can overcome this error? Thanks
For scoped apps you need to change: ``` SncTriggerSynchronizer.executeNow(rec); ``` To: ``` gs.executeNow(rec); ```
371806
Running PHP 5.3.1 on a Windows server, I have to modify a PHP script to access XML files on a network share. For various reasons the files cannot be placed on the PHP server, and I am not allowed to create a mapped drive on the PHP server so I have to modify the open\_basedir parameter in PHP.ini to include the UNC path to the share, e.g.: ``` open_basedir = "E:\inetpub\;E:\DB_HubDataFiles\;\\stdmfps01\inter-departements$\CVSC-CDT-Estimation-Cedule\" ``` However when I try to access files on the share I get the "open\_basedir restriction in effect" error. I am trying to access the files as follows: ``` $jobfilename = "//stdmfps01/inter-departements$/CVSC-CDT-Estimation-Cedule/" .$job . ".xml"; if (file_exists($jobfilename)) { $jobxml = simplexml_load_file($jobfilename); etc... ``` I have been assured that it is not a problem of rights, and anyway the error indicates a problem with open\_basedir. So my questions are: 1. does open\_basedir handle UNC paths under Windows (I have seen conflicting statements about this)? 2. if so is there some problem with my syntax? 3. do I have other options than using open\_basedir? Thanks.
I'm looking everywhere for the best answer for this. Here what I found. ``` @media (min-width:320px) { /* smartphones, iPhone, portrait 480x320 phones */ } @media (min-width:481px) { /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */ } @media (min-width:641px) { /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */ } @media (min-width:961px) { /* tablet, landscape iPad, lo-res laptops ands desktops */ } @media (min-width:1025px) { /* big landscape tablets, laptops, and desktops */ } @media (min-width:1281px) { /* hi-res laptops and desktops */ } ``` I think this is better considering with mobile first approach. Start from mobile style sheet and then apply media queries relevant for other devices. Thanks for @ryanve. Here is the [link](https://stackoverflow.com/a/7354648/2408913).
371829
Regarding [this question](https://electronics.stackexchange.com/questions/32833/suggest-a-timer-chip). In the question was asked for a solution for monitoring a voltage over a long time. The question contains hints to a microcontroller solution, and a couple of answers also covered that, but the real question didn't need a microcontroller at all. Now if it *would* require a microntroller, what are the best choices for low power? Concrete: I need to measure temperature once every 5 minutes and wirelessly transmit the value and go back to sleep. Transmission is <20m, not line-of-sight. Any protocol/frequency. Just two bytes of data to send. I want the battery, a 600mAh CR2450, to last as long as possible. Interval precision better than 0.5% possible (that's 1.5" in 5 minutes)? **edit** (by stevenvh) Federico mentions a home weather station with **wireless outdoor thermometer** in a comment. I think that could give a good idea of the type of application. The thermometer indeed transmits its data every 5 minutes, and works for more than a year on one set of batteries. If it makes any difference: how about sampling once every hour?
I can tell you about my experience with Jennic [JN5148](http://www.jennic.com/products/wireless_microcontrollers/jn5148), which I'm now using for my thesis. It's a module embedding a microcontroller and a 2.4 GHz transceiver, working with ZigBee and JenNet, a very simple proprietary protocol. Plus, it embeds error checking in the 802.15 protocol and, if you want, encryption. With a proper power management, you can go down to 2 uA in sleep mode, or even lower but then you need an external event to wake your microcontroller. It uses a 32 kHz oscillator for sleep time, so you can check if it's stable enough for your application. The current when transmitting-receiving is 15-17.5 mA. The range is nominal 100-500 m clear space, tested by me to be (very approximately) around 30 m with walls and doors. Since I'm going low low power, I'm collecting some statistics about the consumption, and for your application (just measuring voltage), you should stay below 3 uA of current during sleep time (considering some leakage from the board), and around 50-100 uC (A\*s), which at your duty cycle (once every 5 minutes) gives an **average current of 3.5 uA**. You'll see that this current is much lower than the leakage of the battery, and for the 600 mAh case you should run for **171'000 hours** (fair enough?) **in theory**. About the average power, I disagree with Olin :). In my experience, at that low duty cycle the power consumption will largely be dominated by the standby current (no matter how small), which should be below 1 uA (very very small for a real circuit, not only the specs) to be comparable. And you have to ***CAREFULLY*** design and program your board (*pay attention* to I/O pins) to achieve those low values. Energy scavenging ----------------- If it's an outdoor application, and it has to run for a long time, why don't you provide it with a small solar panel (around 5-10$) which may give to your thermometer a virtually infinite life? We're doing it, and the panel provides - indoor - enough current for the circuit to survive, outdoors will really be a breeze, and a 50 mAh LiPo battery (again, few dollars) will be enough.
372166
Reports are deployed and working, verified in Report Manager. My application is an MVC2 app with my report on its own aspx page. This page worked with version 8 of the report viewer control, but we moved to new servers, upgraded sql server, and are trying to update our website to match. The servers are Windows Server 2008 with IIS 7.5. I am testing in both chrome and IE 9. Despite my best efforts, I still get this error: > > Report Viewer Configuration Error > > > The Report Viewer Web Control HTTP Handler has not been registered in > the application's web.config file. Add `<add verb="*" > path="Reserved.ReportViewerWebControl.axd" type = > "Microsoft.Reporting.WebForms.HttpHandler, > Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, > PublicKeyToken=b03f5f7f11d50a3a" />` to the system.web/httpHandlers > section of the web.config file, or add `<add > name="ReportViewerWebControlHandler" preCondition="integratedMode" > verb="*" path="Reserved.ReportViewerWebControl.axd" > type="Microsoft.Reporting.WebForms.HttpHandler, > Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, > PublicKeyToken=b03f5f7f11d50a3a" />` to the system.webServer/handlers > section for Internet Information Services 7 or later. > > > But, I've already done this. in fact, I even read this from [MSDN](http://msdn.microsoft.com/en-us/library/ms251661%28v=VS.100%29.aspx): > > To use IIS 7.0 in Integrated mode, you must remove the HTTP handler in system.web/httpHandlers. Otherwise, IIS will not run the application, but will display an error message instead. > > > Just to be safe, I tried a combo of neither while adding the handler into IIS directly, just the web server http handler in my config, just the http handler in my config, and both. Let's start with my web.config ``` <configuration <system.web> <httpRuntime maxQueryStringLength="4096" /> <compilation targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" /> <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" /> </assemblies> <buildProviders> <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </buildProviders> </compilation> </system.web> <system.webServer> <handlers> <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </handlers> </system.webServer> </configuration> ``` I have the assemblies, the build provider, and the handler. What else could be wrong?
I found a quick and dirty workaround - to your web config add this: ``` <location path="Reserved.ReportViewerWebControl.axd"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location> ``` I saw in fiddler that for some reason when page requested Reserved.ReportViewerWebControl.axd instead of getting HTTP 200 response server would send 302 - moved to login.aspx?returnurl="Reserved.ReportViewerWebControl.axd. So allowing all users to the handler path solves the problem.
372450
Problem: from a json file, read it up from disk and add a field to a child object and print it back to disk. File: ``` { "name": "api", "script": "index.js", "instances": "1", "env": { "PORT": 3000 }, "env_production": { "PORT": 3000 } } ``` So i've managed to pipe it and add the field: ``` cat pm2.json | jq --arg key val '. as $parent | .env_production + {"abc": "123"}' ``` Which returns the child object with the field added. However, I need to update the file on disk. So I also need to print the whole object (the parent). I can do that by printing it the `$parent` variable. But I cannot get it to work since it is immutable. ``` cat pm2.json | jq --arg key val '. as $parent | .env_production + {"abc": "123"}| $parent' ``` Question: how can I do this so that the `$parent` variable have the new added field, so that I can pipe it back to the original file?
Adding onto Luc's answer; In your config you should change your 'response.headers.server' to '' or something custom to hide the version in browser headers as well. You can edit the template code as well to remove the Powered By. For example this will replace it with a ''. ``` cherrypy.__version__ = '' cherrypy._cperror._HTTPErrorTemplate = cherrypy._cperror._HTTPErrorTemplate.replace('Powered by <a href="http://www.cherrypy.org">CherryPy %(version)s</a>\n','%(version)s') ```
373154
I have an excel spreadsheet with sports data - a header row with things like Team, Result, Date, etc, and rows with all of the teams in them (for example, if baseball, the first 162 rows are individual games for one team, then the next 162 are for another, etc). I'm able to read these into python with XLRD easy enough, but i'm not sure exactly how to store them so that I can easily access information about a specific team. I can use a defaultdict(list) but i'm honestly not too sure how to actually access anything specific. For example: ``` import xlrd import xlwt import os.path import math import pandas as pd from xlutils.copy import copy as xl_copy from collections import defaultdict result = defaultdict(list) workbook = xlrd.open_workbook("Sample.xls") worksheet = workbook.sheet_by_index(1) headers = worksheet.row(0) for index in range(worksheet.nrows)[1:]: for header, col in zip(headers, worksheet.row(index)): result[header.value].append(col.value) ``` This stores everything I need in "Result" and the output (if I print it) is like this (example for a 3-row file): ``` Team {'Boston Red Sox','Boston Red Sox','Boston Red Sox'} Score {'11-4','4-0','5-6'} Result {'W','W','L'} ``` How can this information be better stored/sorted **by team** in order for me to easily access information pertaining to a specific team? \*\*If I wanted to add up how many victories they had, for example, how would I even do that? Is deafultdict a good use for this situation? Thanks
According to the [express docs](http://expressjs.com/th/api.html#req) it looks like the differences between `req.query` and `req.params` are just as you mentioned, in that they are a different way to achieve a similar end result. Which you choose is really just a matter of your personal preference for how you want to pass data to Express.
373569
I have two physical volumes ( /dev/sda3 and /dev/sdb1 ) connected to one volume group (fileserver). When I boot up my computer and open up the file explorer, on the left, I see a Devices pane that says my volume group. However, I cannot connect to this server from any client until I click it. Clicking the volume group mounts it because it shows the eject arrow sign right next to it. As soon as I click it, then I am able to connect to the server and see my files. My question is: how do I automate this process every time Ubuntu starts? I tried going to the Startup Applications and using this command ``` mount /dev/mapper/fileserver-media /media/bfbe53bd-3306-401b-a8df-4363564cf1fc ``` but it didn't seem to do anything. I attached a picture to show what I mean. This is what it looks like when I turn on my computer. <http://i1285.photobucket.com/albums/a582/sameetandpotatoes/Before_zpsa67a3e4f.png> Now, this is what it looks like when I click on the device: <http://i1285.photobucket.com/albums/a582/sameetandpotatoes/2_zps5c91a322.png> Here are the Terminal outputs of pvscan, vgscan, etc. **sameet@sapraserver:~$ sudo pvscan** PV /dev/sda3 VG fileserver lvm2 [216.07 GiB / 18.89 GiB free] PV /dev/sdb1 VG fileserver lvm2 [232.83 GiB / 0 free] Total: 2 [448.89 GiB] / in use: 2 [448.89 GiB] / in no VG: 0 [0 ] **sameet@sapraserver:~$ sudo vgscan** Reading all physical volumes. This may take a while... Found volume group "fileserver" using metadata type lvm2 **sameet@sapraserver:~$ sudo lvdisplay** --- Logical volume --- LV Name /dev/fileserver/media VG Name fileserver LV UUID lrY16C-bNwH-fFvA-aVDW-Gtx6-2vIG-urrGpD LV Write Access read/write LV Status available # open 2 LV Size 430.00 GiB Current LE 110080 Segments 2 Allocation inherit Read ahead sectors auto currently set to 256 Block device 252:0 Thanks in advance for your help.
Okay, I figured it out finally. Here's what I did: 1. First, I made sure I had the right Logical Volume name by running `lvdisplay` in terminal. 2. Then, I had to edit the `rc.local` file in `/etc/rc.local`. I added the command there because I couldn't run a command as root in the Startup Applications (I would have to enter a password). In this file, for my system I added the following command: ``` mount /dev/fileserver-media /media/ ``` The /dev/fileserver-media is the name of the logical volume (found with lvdisplay). The /media/ represents where I want the logical volume to be mounted. 3. And then with Samba, I ran `gksudo nautilus` in the terminal, edited permissions, and shared it. The reason I ran this command in the terminal is to open up the file manager as root so I can be the "owner". I would not have been able to edit permissions without running this command.
183693
``` Int32 number = new Random().Next(); Console.WriteLine(number); Func<Int32> GenerateRandom = delegate() { return new Random().Next(); }; Console.WriteLine("Begin Call"); GenerateRandom.DoAsync(number => Console.WriteLine(number)); Console.WriteLine("End Call"); ```
``` Dim number As Int32 = New Random().[Next]() Console.WriteLine(number) Dim GenerateRandom As Func(Of Int32) = Function() New Random().[Next]() Console.WriteLine("Begin Call") GenerateRandom.DoAsync(Function(number) Console.WriteLine(number)) Console.WriteLine("End Call") ```