qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
4,093
I'm setting a document that includes some music; I'm using lilypond-book for the musical examples. However, there are some points where the author has inserted a musical symbol in the text; I'm using MusiXTeX for those bits. Notes and accidentals are easy, but I can't find a way to put in just a clef sign. For example, the author says > > The *G sol re ut* clef . . . is made thus, <treble-clef>. > > > I'd like to have a treble clef right in the text where it says <treble-clef>.
2010/10/13
[ "https://tex.stackexchange.com/questions/4093", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/1470/" ]
Found my own answer after help from Seamus: ``` The G sol re ut clef . . . is made thus, \begin{music}\trebleclef\end{music}. ``` That is, of course, after including `\usepackage{musixtex}` in the header.
There are various packages that allow you to include musical symbols. See p.88 *et seq.* of the [LaTeX comprehensive symbols list](http://www.tex.ac.uk/tex-archive/info/symbols/comprehensive/symbols-a4.pdf). Weirdly, I'm not actually sure the above document contains the "clef" symbols you want. (I don't actually know the terminology well enough to know if it's there) But if it isn't there, I don't know where you'll find it... Your best bet might be to try and get musixtex to work inline... Searching musixtex documentation for "inline" gets only one hit, and it's no use... You could print a pdf of just the symbol, and then `\includegraphics` it?
66,286,464
I am trying to test if a number is even or odd. It works fine with numbers of 8 digits, but when ever I go over 9 digits it looks weird. The number I type in changes. Example with 8 digits: ``` Enter the ID : 20202020 20202020 is even. Program ended with exit code: 0 ``` But when doing it with 10 digits it looks like this: ``` Enter an integer: 2345678915 -1949288381 is odd. Program ended with exit code: 0 // these nr that are different, what are they? //Have not found any info about it either... ``` Code: ``` #include <stdio.h> int main() { int id; printf("Enter the Id: "); scanf("%d", &id); if(id % 2 == 0) printf("%d is even.\n", id); else printf("%d is odd.\n", id); return 0; } ``` I tried changing it to double, does not help. Does it have anything to do with the if statement? ``` if(id % 2 == 0) ```
2021/02/19
[ "https://Stackoverflow.com/questions/66286464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15235039/" ]
This problem comes from the fact that, as everybody mentionned, you are trying to fit more information that what can be contained in a signed (32 bits) integer. Nevertheless I feel that other answers are just kicking the can down the road, so I will provide you a solution that would also work for a **REALLY high (odd and even) number** (up to BUFFER\_SIZE digits...): ```c #include <stdio.h> #define BUFFER_SIZE 1024 int main(int argc, char **argv) { if (argc < 2) return 1; char buffer[BUFFER_SIZE + 1]; printf("Enter the Id: "); fgets(buffer, BUFFER_SIZE, stdin); unsigned len = strlen(buffer); buffer[len -1] = '\0'; // remove '\n' from fgets // you might want to check that the user input a valid number // https://stackoverflow.com/questions/16644906/how-to-check-if-a-string-is-a-number int id = buffer[len - 2] - '0'; // get last digit if(id % 2 == 0) printf("%s is even.\n", buffer); else printf("%s is odd.\n", buffer); return 0; } ``` output: ``` Enter the Id: 6734863486834863486348648564386803486438683456438658438764568435864783 6734863486834863486348648564386803486438683456438658438764568435864783 is odd. ```
Typical `int` (signed 32-bit long) can store only upto 2,147,483,647. Your input `2345678915` is beyond this. If this is supported in your environment, you can use `long long`, which is typically 64-bit long and can store upto 9,223,372,036,854,775,807. ``` #include <stdio.h> int main() { long long id; printf("Enter the Id: "); scanf("%lld", &id); if(id % 2 == 0) printf("%lld is even.\n", id); else printf("%lld is odd.\n", id); return 0; } ``` Another option is using `int64_t`, which may be supported in wider environments. ``` #include <stdio.h> #include <inttypes.h> int main() { int64_t id; printf("Enter the Id: "); scanf("%" SCNd64, &id); if(id % 2 == 0) printf("%" PRId64 " is even.\n", id); else printf("%" PRId64 " is odd.\n", id); return 0; } ``` --- Being inspired from @0\_\_\_\_\_\_\_\_\_\_\_, you can judge if a number is even or odd by just seeing the last digit. ``` #include <stdio.h> #include <stdlib.h> #include <ctype.h> int main() { int input; int is_valid_number = 1; size_t input_len = 0; char* id = malloc(1); if (id == NULL) { perror("malloc"); return 1; } printf("Enter the Id: "); /* read the first line */ while ((input = getchar()) != '\n' && input != EOF) { char* next_id = realloc(id, input_len + 2); /* +1 for new character and +1 for NUL */ if (next_id == NULL) { perror("realloc"); free(id); return 1; } /* check if the input correctly represents a number */ is_valid_number = is_valid_number && (isdigit(input) || (input_len == 0 && input == '-')); /* store this digit */ id = next_id; id[input_len++] = (char)input; } id[input_len] = '\0'; if (input_len == 0 || !is_valid_number) printf("%s is not a number.\n", id); else if((id[input_len - 1] - '0') % 2 == 0) printf("%s is even.\n", id); else printf("%s is odd.\n", id); free(id); return 0; } ```
30,807
I am looking for a solution to carry 2 check-in (around 50 lbs each) roller bags to airport. Since I am alone its hard to pull both at same time. Options I think I have: 1. Use taxi and pay him around 80bucks 2. Use option like luggage cart that can carry up to 100lbs. 3. Any other innovative idea. In other words, I am trying to understand the usefulness of luggage carts: e.g. ![cart](https://i.stack.imgur.com/x9XVu.jpg) ([cart at Amazon)](http://rads.stackoverflow.com/amzn/click/B000USIM5M) or something as easy as travel dolly e.g. ![dolly](https://i.stack.imgur.com/1OfWI.jpg) [(dolly at Amazon)](http://rads.stackoverflow.com/amzn/click/B005N11RQ2)
2014/06/21
[ "https://travel.stackexchange.com/questions/30807", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/16770/" ]
I've done this once or twice and it's generally horrible. Some tips: * you have two hands, so you can generally handle two things, though doors and whatnot will provide a challenge. But you really can't do three. So your carry on should either be a backpack (so it doesn't use up any hands) or be strapped to one of the suitcases. * the suitcases need wheels. * ask people to help you: "Can you open that door for me?" or "could you push the button for me?" will make you much less frustrated * if you have to navigate stairs, you will probably have to do it in shifts - try not to get too far from either bag or they may be stolen. * don't feel guilty about being slow. You have every right to be on a sidewalk or platform. * if you chain the bags up somehow, do accept the fact that it might not work in some circumstances and be able to get them apart quickly * you may want to use a taxi for some small part of the trip to get around a particularly hard-to-navigate portion, and use public transit for the rest. Finally, pull up a picture in your head of someone about your age who is struggling with a 50 lb suitcase, a baby stroller, a diaper bag full of baby stuff, a carry on bag for the plane, and oh yes, an actual baby, who is crying. Think about this person every time you start to feel sad about lugging two 50 lb suitcases. **It could be worse.**
You can check with hotels near you (or with the airport) if there are shuttle buses that go to hotels on demand. You can then take a taxi just up to the airport and then the shuttle bus the rest of the way. Another way you can do it is to only take one bag at a time, and use an airport locker to store one of the bags, and then go and pick up the other bag.
62,111,828
This is my first day learning python from a book called "Automate the Boring Stuff with Python". On the "your first program" section the program is this ``` # This program says hello and asks for my name. print('Hello world!') print('What is your name?') # ask for their name myName = input("Mizu") print('It is good to meet you, ' + myName) print('The length of your name is:') print(len(myName)) print('What is your age?') # ask for their age myAge = input('20') print('You will be ' + str(int(myAge) + 1) + ' in a year.') ``` but the program only runs ``` Hello world! What is your name? Mizu ``` but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine. What am i doing wrong here? i used the default python editor and pycharm and both show no errors or anything.
2020/05/31
[ "https://Stackoverflow.com/questions/62111828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13651086/" ]
You are not setting $\_SESSION['username'] after your user was found in the db. Im not a PHP expert, but you need to do something like $\_SESSION['username'] = 'xyz' i think. Besides that your select query is vunerable to sql injection. <https://www.php.net/manual/en/security.database.sql-injection.php>
In your script there is one mistake ``` $sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1"; ``` in this query near username `where korisnickoime='".$username."'AND sifrajedan='".$password."'` there is not space between `$username` and `AND`. The end result of this query after appending username and password will be like ``` SELECT * FROM loginform where korisnickoime='user1'AND sifrajedan='xyz' limit 1"; ``` This Query will break so please add a little space between, replace your Query string with this. ``` $sql="SELECT * FROM loginform where korisnickoime='".$username."' AND sifrajedan='".$password."' limit 1"; ``` Your PHP script could be like this --- > > index.php > > > ``` <form method="post" name="login"> <label for="username">Username:</label><br> <input type="text" name="username"><br> <label for="password">Password:</label><br> <input type="password" name="password"><br> <button type="submit" name="login">Log in</button> </form> <?php session_start(); if(isset($_POST['username']) and isset($_POST['password'])) { $username = $_POST['username']; $pass = $_POST['password']; $query = "SELECT * FROM `person` WHERE name='$username' and pass='$pass'"; $result = mysql_query($query) or die(mysql_error()); $count = mysql_num_rows($result); if ($count == 1){ $_SESSION['username'] = $username; header('Location: homepage.php'); } else { $msg = "Wrong credentials"; } } if(isset($msg) & !empty($msg)){ echo $msg; } ?> ``` --- > > Then in homepage.php > > > ``` <nav> <ul class="nav__links"> <li><a href="#">Services</a></li> <li><a href="#">Projects</a></li> <li><a href="#">About</a></li> <li><a href="#"> <span> <?php session_start(); if(!isset($_SESSION['username'])) { die("You are not logged in!"); } $username = $_SESSION['username']; echo "Hai " . $username; ?> </span></a></li> </ul> </nav> ``` PS: TO make your Query Secure use parameterized query like this ``` <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $stmt = $conn->prepare(SELECT * FROM loginform where korisnickoime='?' AND sifrajedan='?' limit 1"); $stmt->bind_param("ss", $username, $password); // set parameters and execute $username = "John"; $password = "Doe"; $result = $stmt->execute(); ?> ```
52,478,211
I'm building my app with the **Ionic Framework**. I'm facing a problem with the *Ionic Native HTTP plugin*, because it works only on iOS and Android platforms. Is there an alternative to HTTP plugin that works also on Browser platform? I use it in a straight way: ``` import { HTTP } from '@ionic-native/http'; ... constructor(private http: HTTP) ... this.http.get('http://www.google.com', { 'q' : 'hello' }, {}) .then(data => { console.log("OK"); console.log(data.status); console.log(data.data); // data received by server console.log(data.headers); }) .catch(error => { console.log("NO"); console.log(error.status); console.log(error.error); // error message as string }); ```
2018/09/24
[ "https://Stackoverflow.com/questions/52478211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3642532/" ]
It looks like there's a problem when there is an input inside a `menuItem`. You can do: ``` sidebar <- dashboardSidebar( sidebarMenu( id="tabs", menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")), conditionalPanel( "input.tabs == 'dashboard'", sliderInput("slider", "Slider Input", min = 0, max = 10, step = 1, value = 5)) ) ) ```
Below is the code which works. ``` library(shiny) library(shinydashboard) ui <- dashboardPage( dashboardHeader(), dashboardSidebar( sidebarMenu( menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard"), sliderInput("slider", "Slider Input", min = 0, max = 10, step = 1, value = 5)) ) ), dashboardBody( textOutput("dashboard") )) server <- function(input, output, session) { output$dashboard <- renderText({ paste("You've selected:", input$slider) }) } shinyApp(ui, server) ```
52,614,923
I have a webpage. Suppose I don't know that the page contains a `<p>` or any other HTML tag. The script runs in the background and when I click anywhere on the webpage if there is a corresponding HTML tag to the click then the script returns the tag with its index number. ``` <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <p></p> <div></div> <div></div> </body> </html> ``` Now when I click on the tag p then the script should return `<p>` and its index. Somewhat like this: ``` $("body").click(function(){ /* return the clicked html tag within body and its index*/ }); ``` For this: ``` $("tag name").click(function(){ // return tag }); ``` I need to know which tag I am clicking on. But I don't know on which tag I'm going to click. Pure JS will also do.
2018/10/02
[ "https://Stackoverflow.com/questions/52614923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9422949/" ]
Just use event delegation within the `on` method. <http://api.jquery.com/on/> If you provide a selector JQuery will setup the event to fire only when an element within the parent matches that selector. In the below it grabs any element because the selector is `"*"` - this has the added benefit of providing the current clicked element as `this` or `e.currentTarget` within the function call. ``` $("body").on("click", "*", function(e) { alert(this) }); ``` To get the index of the specified element within the `body` you can use that `this` context to grab the index based on its `tagName` (a.e. paragraphs have a `tagName` of `p`) ``` $("body").on("click", "*", function(e) { alert(this + " " + $(this).index(this.tagName))} ``` ```js $("body").on("click", "*", function(e) { alert(this + " " + $(this).index(this.tagName)) }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <p>paragraph</p> <div>div</div> <div>div</div> </body> </html> ```
Without jQuery you can attach an `onclick` handler to your elements like so: ``` for (let i = 0, len = document.body.children.length; i < len; i++) { document.body.children[i].onclick = function(){ alert(i) ; } } ``` This will show you the index of the item on the page.
412,256
Can the iPhone determine if you're facing north, south, east or west?
2009/01/05
[ "https://Stackoverflow.com/questions/412256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46182/" ]
This maybe a bit of a hack but what I was doing was keeping tracking of the lat/long and then determining by that the direction. Within my code that returns the GPS information I created a delegate that would return back the latitude and longitude ``` [[self delegate] currentDirectionLat:newLocation.coordinate.latitude Long:newLocation.coordinate.longitude]; ``` The code that was consuming the delegate would then have a method like so to get the coordinates and then set a label on the screen to the direction. ``` -(void)currentDirectionLat:(float)latitude Long:(float)longitude { prevLongitude = currentLongitude; prevLatitude = currentLatitude; currentLongitude = longitude; currentLatitude = latitude; NSString *latDirection = @""; if (currentLatitude > prevLatitude) latDirection = @"N"; else if (currentLatitude < prevLatitude) latDirection = @"S"; NSString *longDirection = @""; if (currentLongitude > prevLongitude) longDirection = @"E"; else if (currentLongitude < prevLongitude) longDirection = @"W"; if ([longDirection length] > 0) [lblDirection setText:[NSString stringWithFormat:@"%@%@",latDirection,longDirection]]; } ``` I've not 100% tested this out but seems to have worked on my one application I was writing. If you want more information please let me know and I can forward you my code that I've done on it. You will also not get a good reading until the iPhone is moving to get the lat and long change. However, this does not take much to get it to change!
To my knowledge there is **no compass in the iPhone 3G**. Unfortunately, unless I'm missing something I don't think looking at GPS and accelerometer data will help you determine which direction the iPhone is facing - only the direction you're travelling. Sorry. **UPDATE**: Note that the question and this post was written when iPhone 3G was the current model, since then Apple has released the **iPhone 3GS** which **introduced a compass**.
35,228,035
I'm looking for any modern resources for setting up a video streaming server. Preferably open source solutions. My searching on this has lead to a lot of dead ends. I also do need to build my own instead of paying for a service.
2016/02/05
[ "https://Stackoverflow.com/questions/35228035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3609124/" ]
Use nginx mp4 module to stream videos. Limit bandwidth, concurrent connection, max buffer size and more. Use md5 key and ttl for security.
There is a site (<https://www.youphptube.com>) a it's project on github (<https://github.com/DanielnetoDotCom/YouPHPTube>) for building your own video sharing site. I didn't digged in this project, it may or may not be cool project.
94,591
I can never remember the number. I need a memory rule.
2008/09/18
[ "https://Stackoverflow.com/questions/94591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054/" ]
Here's a mnemonic for remembering 2\*\*31, subtract one to get the maximum integer value. a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9 ``` Boys And Dogs Go Duck Hunting, Come Friday Ducks Hide 2 1 4 7 4 8 3 6 4 8 ``` I've used the powers of two up to 18 often enough to remember them, but even I haven't bothered memorizing 2\*\*31. It's too easy to calculate as needed or use a constant, or estimate as 2G.
You will find in binary the maximum value of an Int32 is 1111111111111111111111111111111 but in ten based you will find it is 2147483647 or 2^31-1 or Int32.MaxValue
26,018
This question is regarding **One Piece**. As I was going through the design of the **Thousand Sunny** on Wikia, I came across [**this**](http://onepiece.wikia.com/wiki/Thousand_Sunny?file=Thousand_sunny_boys_room.png) image of **The boys' room**, which I've posted below: [![enter image description here](https://i.stack.imgur.com/yX81N.png)](https://i.stack.imgur.com/yX81N.png) As can be seen here, there are six hammocks in the image, verified by [**this**](http://onepiece.wikia.com/wiki/Thousand_Sunny#Men.27s_and_Women.27s_Quarters) link. > > Suspended from the ceiling like wooden hammocks are **three > double-decker bunks**, which the men sleep in. > > > It also adds that > > Behind these bunks, at > the back of the room, are **six** lockers where the men can store their > clothes. > > > Since there are seven male members in the Straw Hat crew, there must be one person who doesn't get to sleep in a hammock and who doesn't have a locker. My question is, who is it? I came across [**this**](http://www.narutoforums.com/showthread.php?t=810848) and [**this**](http://feriowind.deviantart.com/art/OP-Daily-life-on-Sunny-1-132802881) link which pose a similar question. The answers which seem to be valid are * Sanji sleeping in the kitchen I don't think Sanji sleeps in the kitchen, but there is a couch to the right [**here**](http://onepiece.wikia.com/wiki/Thousand_Sunny?file=Thousand_sunny_kitchen.png), does Sanji sleep there? I think Sanji does have a locker to himself. * Zoro sleeping in the crow's nest The [**crow's nest**](http://onepiece.wikia.com/wiki/Thousand_Sunny?file=Thousand_sunny_crows_nest.png) seems to have wooden benches, but I doubt Zoro sleeps there. I think Zoro has a locker to himself, too. * Brook not sleeping In an SBS question, Oda has said that Brook sleeps for five hours. [**This**](http://onepiece.wikia.com/wiki/Straw_Hat_Pirates/Miscellaneous#Typical_Hours_of_Sleep) is the link. [**This**](http://onepiece.wikia.com/wiki/SBS_Volume_74#Chapter_737.2C_Page_126) link gives their sleep timings. So that eliminates the possibility that Brook doesn't sleep. Maybe he doesn't sleep in this room though? I can't guess if he has a locker or not. * Chopper sleeping on the bed in the Sick Bay This seems like the most plausible solution, since Chopper considers the [**Sick Bay**](http://onepiece.wikia.com/wiki/Thousand_Sunny?file=Thousand_sunny_sick_bay.png#Kitchen.2C_Dining_Room.2C_and_Sick_Bay) as his personal room, provided the bed isn't reserved for patients. He might be the one who doesn't have a locker, since he can keep his stuff in the infirmary. * One of them is on night watch, so there are enough hammocks for the rest This is possible, but is it true? If it is, was there any rare occasion when none of them was on watch? I highly doubt it, but if the answer is yes, how did they sleep then? Even if they did manage to sleep somehow (one of them on the floor, for example), there are still six lockers though, so who doesn't have a locker to himself? The following image provides a pretty nice solution, but this is an image from when the Straw Hats were on the *Going Merry*. Do they use the same solution on the *Thousand Sunny* too? [![enter image description here](https://i.stack.imgur.com/z9Vaj.jpg)](https://i.stack.imgur.com/z9Vaj.jpg) A person who has seen the anime or read the manga, or done both, might probably know the answer. Any help is highly appreciated. --- I apologize for the lengthy question. I haven't watched or read One Piece. I came across it about a month ago and it drew my attention greatly. My knowledge is mostly limited to the information I gained by reading the Wikipedia and Wikia pages of One Piece.
2015/09/20
[ "https://anime.stackexchange.com/questions/26018", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/15820/" ]
Brook was the newest official member of the strawhat crew and therefore the Sunny was not modified yet to showcase his own personal space. This is mostly in part to the 2Y timeskip that occurred when the crew got back together there hasn't been a real revamp of the Sunny. The crew just bought stuff with them and added it to the ship. So the person who doesn't have a space is Brook.
It's a working ship, so the crew will be split into watches, e.g. First/morn, afternoon/middle, last dog. This means that at all times a portion of the crew is awake and on duty, so unless the crew drastically increases in size, six bunks for the men is more than adequate.
50,486,314
I am newbie in spring boot rest services. I have developed some rest api in spring boot using maven project. I have successfully developed **Get** and **Post** Api. My **GET** Method working properly in postman and mobile. **when i am trying to hit post method from postman its working properly but from mobile its gives 403 forbidden error.** This is my Configuration: ``` spring.datasource.url = jdbc:mysql://localhost/sampledb?useSSL=false spring.datasource.username = te spring.datasource.password = test spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect Hibernate ddl auto (create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto = update ``` Please Suggest me how to solve error. [![enter image description here](https://i.stack.imgur.com/sdY6h.png)](https://i.stack.imgur.com/sdY6h.png)
2018/05/23
[ "https://Stackoverflow.com/questions/50486314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8220128/" ]
In Spring Security Cross-site check is by default enable, we need to disable it by creating a separate class to stop cross-checking. ```java package com.baba.jaxws; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override //we have stopped the csrf to make post method work protected void configure(HttpSecurity http) throws Exception{ http.cors().and().csrf().disable(); } } ```
To build on the accepted answer Many HTTP client libraries (eg Axios) implicitly set a `Content-Type: JSON` header for POST requests. In my case, I forgot to allow that header causing only POSTS to fail. ``` @Bean CorsConfigurationSource corsConfigurationSource() { ... configuration.addAllowedHeader("Content-Type"); // <- ALLOW THIS HEADER ... } ```
7,344,908
How can I make my registration fields like this ![enter image description here](https://i.stack.imgur.com/Y221i.jpg) How can I achieve this via CSS? I mean, that my textboxes should be aligned from label's end to the page's end... EDIT Here is my view part ``` <div id="member-search"> <h5>Last Name:</h5> @Html.TextBox("member-last-name") </div> <div> <h5>Pass:</h5> @Html.TextBox("member-pass") </div> <input type="submit" value="Search" class="button"/> </div> ``` In CSS I tried a lot, but with no success. width:auto doesn't help and I don't find solution for this. Thanks for help.
2011/09/08
[ "https://Stackoverflow.com/questions/7344908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/867232/" ]
After I had to refator your HTML to properly reflect the actual rendered code, this is the best I can come up with. HTML: ``` <div id="member-search"> <label for="member-last-name">Last Name:</label> <input type="text" name="member-last-name" class="myInput"> </div> <div class="clear"> <label for="member-pass">Pass:</label> <input type="text" name="member-pass" class="myInput"> </div> <div class="clear"> <input type="submit" value="Search" class="button"/> </div> ``` CSS: ``` #member-search { width: 100%; } label { float: left; } .myInput { float: right; width: 88%;/*MILES AN HOUR, MARTY!*/ } .clear { clear: both; } ``` [Check here for an example](http://jsfiddle.net/Kyle_Sevenoaks/SxuUX/).
here you go <http://jsfiddle.net/8YAhW/> Pay attention to the label tag and the "for" attribute. This helps when tabbing across items commonly used when making forms. Hope this helps you out
30,488,440
I am using an AsyncTask to run database querying in the background. I get this error when I run my applection. ``` 05-27 16:35:13.638: I/Choreographer(3421): Skipped 53 frames! The application may be doing too much work on its main thread. 05-27 16:35:13.859: I/Choreographer(3421): Skipped 57 frames! The application may be doing too much work on its main thread. 05-27 16:35:14.029: E/AndroidRuntime(3421): FATAL EXCEPTION: AsyncTask #4 05-27 16:35:14.029: E/AndroidRuntime(3421): java.lang.RuntimeException: An error occured while executing doInBackground() 05-27 16:35:14.029: E/AndroidRuntime(3421): at android.os.AsyncTask$3.done(AsyncTask.java:299) 05-27 16:35:14.029: E/AndroidRuntime(3421): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 05-27 16:35:14.029: E/AndroidRuntime(3421): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 05-27 16:35:14.029: E/AndroidRuntime(3421): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 05-27 16:35:14.029: E/AndroidRuntime(3421): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 05-27 16:35:14.029: E/AndroidRuntime(3421): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 05-27 16:35:14.029: E/AndroidRuntime(3421): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 05-27 16:35:14.029: E/AndroidRuntime(3421): at java.lang.Thread.run(Thread.java:856) 05-27 16:35:14.029: E/AndroidRuntime(3421): Caused by: java.lang.NullPointerException 05-27 16:35:14.029: E/AndroidRuntime(3421): at com.example.iqraa.Buy$SearchBook.doInBackground(Buy.java:189) 05-27 16:35:14.029: E/AndroidRuntime(3421): at com.example.iqraa.Buy$SearchBook.doInBackground(Buy.java:1) 05-27 16:35:14.029: E/AndroidRuntime(3421): at android.os.AsyncTask$2.call(AsyncTask.java:287) 05-27 16:35:14.029: E/AndroidRuntime(3421): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 05-27 16:35:14.029: E/AndroidRuntime(3421): ... 4 more 05-27 16:35:14.469: I/Choreographer(3421): Skipped 134 frames! The application may be doing too much work on its main thread. 05-27 16:35:15.369: I/Choreographer(3421): Skipped 107 frames! The application may be doing too much work on its main thread. 05-27 16:35:16.309: I/Choreographer(3421): Skipped 33 frames! The application may be doing too much work on its main thread. 05-27 16:35:22.089: I/Process(3421): Sending signal. PID: 3421 SIG: 9 ``` Here is my AsyncTask@buy.java: ``` public class Buy extends Activity { String ISBN=""; public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0; private ProgressDialog mProgressDialog; String s; String index; ArrayList<HashMap<String, String>> MyArrList; @SuppressLint("NewApi") @Override ```
2015/05/27
[ "https://Stackoverflow.com/questions/30488440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4945552/" ]
based on your logcat, I can sense the error occurs in catch block of doinbackground function. You are using toast in that method, toast cannot be executed in background. that should be in main thread. So actual error is at line 189, what ever is at 189 is null. So it is going to catch and throwing another error at toast.
according to your logcat, you have an error on line 189 ``` Caused by: java.lang.NullPointerException 05-27 16:35:14.029: E/AndroidRuntime(3421): at com.example.iqraa.Buy$SearchBook.doInBackground(Buy.java:189) 05-27 16:35:14.029: ``` So something on that line is not initialized and your trying to access it.
9,041,681
I'm having a hard time finding examples for rotating an image around a specific point by a specific (often very small) angle in Python using OpenCV. This is what I have so far, but it produces a very strange resulting image, but it is rotated somewhat: ``` def rotateImage( image, angle ): if image != None: dst_image = cv.CloneImage( image ) rotate_around = (0,0) transl = cv.CreateMat(2, 3, cv.CV_32FC1 ) matrix = cv.GetRotationMatrix2D( rotate_around, angle, 1.0, transl ) cv.GetQuadrangleSubPix( image, dst_image, transl ) cv.GetRectSubPix( dst_image, image, rotate_around ) return dst_image ```
2012/01/27
[ "https://Stackoverflow.com/questions/9041681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/514086/" ]
I had issues with some of the above solutions, with getting the correct "bounding\_box" or new size of the image. Therefore here is my version ``` def rotation(image, angleInDegrees): h, w = image.shape[:2] img_c = (w / 2, h / 2) rot = cv2.getRotationMatrix2D(img_c, angleInDegrees, 1) rad = math.radians(angleInDegrees) sin = math.sin(rad) cos = math.cos(rad) b_w = int((h * abs(sin)) + (w * abs(cos))) b_h = int((h * abs(cos)) + (w * abs(sin))) rot[0, 2] += ((b_w / 2) - img_c[0]) rot[1, 2] += ((b_h / 2) - img_c[1]) outImg = cv2.warpAffine(image, rot, (b_w, b_h), flags=cv2.INTER_LINEAR) return outImg ```
You need a homogenous matrix of size 2x3. First 2x2 is the rotation matrix and last column is a translation vector. [![enter image description here](https://i.stack.imgur.com/VkRVA.gif)](https://i.stack.imgur.com/VkRVA.gif) Here's how to build your transformation matrix: ```py # Exemple with img center point: # angle = np.pi/6 # specific_point = np.array(img.shape[:2][::-1])/2 def rotate(img: np.ndarray, angle: float, specific_point: np.ndarray) -> np.ndarray: warp_mat = np.zeros((2,3)) cos, sin = np.cos(angle), np.sin(angle) warp_mat[:2,:2] = [[cos, -sin],[sin, cos]] warp_mat[:2,2] = specific_point - np.matmul(warp_mat[:2,:2], specific_point) return cv2.warpAffine(img, warp_mat, img.shape[:2][::-1]) ```
25,094,642
I was basically playing with data types in order to learn java and here is what i am confused about. ``` double douVar = 30000000000.323262342134353; int intVar = (int)douVar; // casting System.out.println(intVar); ``` Now converting the `douVar` to string i overwrite the `double` variable: ``` douVar = 345839052304598; // returns an error: Integer number too long System.out.println(Double.toString(douVar)); ``` complete error: ``` Error:(20, 18) java: integer number too large: 345839052304598 ``` I'm using IntellijIDEA compiler. I didnt try this over eclipse though but i assume the compiler would not be so different. Does this mean that casting would result in modifying the original variable as well?
2014/08/02
[ "https://Stackoverflow.com/questions/25094642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2351202/" ]
The literal **345839052304598** will be considered as an `integer` by the `compiler`, since this value is to large for an integer, a compile time error is thrown. Therefore you need to tell the compiler that the value you want to use is actually double value, that you can do the following way: ``` douVar =345839052304598D; // note D at the end which tells comipler that it is double ```
Just change `douVar = 345839052304598;` to `douVar = 345839052304598.00;`
47,078,123
I have the following boundary dataset for the United Kingdom, which shows all the counties: ``` library(raster) library(sp) library(ggplot) # Download the data GB <- getData('GADM', country="gbr", level=2) ``` Using the `subset` function it is really easy to filter the shapefile polygons by an attribute in the data. For example, if I want to exclude Northern Ireland: ``` GB_sub <- subset(UK, NAME_1 != "Northern Ireland") ``` However, there are lots of small islands which distort the scale data range, as shown in the maps below: [![enter image description here](https://i.stack.imgur.com/noa1P.png)](https://i.stack.imgur.com/noa1P.png) Any thoughts on how to elegantly subset the dataset on a minimum size? It would be ideal to have something in the format consistent with the subset argument. For example: ``` GB_sub <- subset(UK, Area > 20) # specify minimum area in km^2 ```
2017/11/02
[ "https://Stackoverflow.com/questions/47078123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7347699/" ]
You have to put name attribute on all input tags which you want send, e.g: ``` <input class="CreateAccountInput" type="text" id="Username" placeholder="Username" style="" name="username"> ```
> > You are missing the `name` attribute in every input . > > >
28,737,292
I wrote a script to read text file in python. Here is the code. ``` parser = argparse.ArgumentParser(description='script') parser.add_argument('-in', required=True, help='input file', type=argparse.FileType('r')) parser.add_argument('-out', required=True, help='outputfile', type=argparse.FileType('w')) args = parser.parse_args() try: reader = csv.reader(args.in) for row in reader: print "good" except csv.Error as e: sys.exit('file %s, line %d: %s' % (args.in, reader.line_num, e)) for ln in args.in: a, b = ln.rstrip().split(':') ``` I would like to check if the file exists and is not empty file but this code gives me an error. I would also like to check if program can write to output file. **Command:** ``` python script.py -in file1.txt -out file2.txt ``` **ERROR:** ``` good Traceback (most recent call last): File "scritp.py", line 80, in <module> first_cluster = clusters[0] IndexError: list index out of range ```
2015/02/26
[ "https://Stackoverflow.com/questions/28737292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3573959/" ]
On Python3 you should use pathlib.Path features for this purpose: ```py import pathlib as p path = p.Path(f) if path.exists() and path.stat().st_size > 0: raise RuntimeError("file exists and is not empty") ``` As you see the Path object contains all the functionality needed to perform the task.
``` def exist_and_not_empty(filepath): try: import pathlib as p path = p.Path(filepath) if '~' in filepath: path = path.expanduser() if not path.exists() and path.stat().st_size > 0: return False return True except FileNotFoundError: return False ``` This leverages all of the suggestions above and accounts for missing files and autoexpands tilde if detected so it just works.
2,308,669
The projection of the point $(11,-1,6)$ onto the plane $3x+2y-7z-51=0$ is equal to (A) $(14,1,-1$ (B)$(4,2,-5)$ (C)$(18,2,1)$ (D) None of these I'm exactly sure how to do this but if $(a,b,c)$ is the projection of the point then the line connecting $(a,b,c)$ and $(11,-1,6)$ must be orthgonal to the plane $3x+2y-7z-51=0$ and $(a,b,c)$ must be located on the this plane. But this does not take me anywhere . I would like to have complete solution .
2017/06/03
[ "https://math.stackexchange.com/questions/2308669", "https://math.stackexchange.com", "https://math.stackexchange.com/users/71612/" ]
The point which is foot of perpendicular on the plane and the original point itself,when joined are parallel to the normal to the plane. So you get the Dr's of the line formed by the original point and foot of perpendicular same as Dr's of normal to the plane. I.e. $(3,2,-7)$. So you can take a parametric point : $$(a,b,c)=(11,-1,6)+\lambda(3,2,-7)$$Now what you need to do is just satisfy this on the equation of plane to get the value of $\lambda$
The plane: $f(x) = 3x + 3 y + 7 z - 51 = 0$. The normal $\vec{N}$ to this plane : $\nabla f = (3, 2, -7)$. Vector joining original point to projection point is parallel to the normal $\vec{N}$: A) $\vec{v\_1} = (11, -1, 6) - (14, 1, -1) = (-3, -2, 7)$. First time lucky, $( -3, -2, 7)$ is $(-1)(3, 2, -7)$, hence parallel. B) $\vec{v\_2} = (11, -1, 6) - (4, 2, -5) = (7, -3, 11)$. C) $\vec{v\_3} = (11, -1, 6) - (18, 2, 1) = (-7, -3, -5)$. A is the answer.
42,826,448
I am trying to download a theme automatically on Wordpress by utilizing PhantomJS. As my script stands, the page is not evaluated until it has stopped loading, the problem is as follows: When I try to click an element on the page, it is not yet visible because the query to their database still has to be returned. EVEN THOUGH the page has been considered to be done loading, there is one essential part that is still missing. Have a look below: [![enter image description here](https://i.stack.imgur.com/QUQTR.png)](https://i.stack.imgur.com/QUQTR.png) This page was rendered AFTER the `install now` button was supposed to be clicked. As you can see, the theme card has yet to even appear. Instead, the only thing that can be seen is the little spinner. This little guy has been causing any theme-related script to become null objects, which is obviously very undesirable. Does anybody have any idea how I can fix this issue? I've already tried `setTimeout()` but this is a VERY ugly method, and has actually never been successful in my testing. Thanks! **ADDED INFORMATION** All of the functions for my program are executed after a set amount of time. This was accomplished by implementing the `setInterval` property. It works flawless, but the solution to my question is now how can I dynamically set the interval time as the functions execute? Example of the code below: ``` var steps = [ function() { console.log('Going') page.open('http://google.com') //Does not need too much time. }, function() { console.log('Searching') page.evaluate(function() { //BIG Task List Here, Needs A lot of Time }) }] //How the interval is set: setInterval(executeRequestsStepByStep, 250) function executeRequestsStepByStep(){ if (loading == false && steps[stepindex]) { steps[stepindex]() stepindex++ } if (!steps[stepindex]) { phantom.exit() } } page.onLoadStarted = function() { loading = true } page.onLoadFinished = function() { loading = false } ``` Any ideas on how we can accomplish this?
2017/03/16
[ "https://Stackoverflow.com/questions/42826448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5893866/" ]
Try this : ``` $data = array( array( 'contact_id' => '1', 'ib_volume' => 5, 'ib_comm' => 8), array( 'contact_id' => '2', 'ib_volume' => 10, 'ib_comm' => 2), array( 'contact_id' => '2', 'ib_volume' => 6, 'ib_comm' => 2), array( 'contact_id' => '3', 'ib_volume' => 8, 'ib_comm' => 5), array( 'contact_id' => '4', 'ib_volume' => 8, 'ib_comm' => 6), array( 'contact_id' => '5', 'ib_volume' => 3, 'ib_comm' => 7), array( 'contact_id' => '6', 'ib_volume' => 7, 'ib_comm' => 4), ); $count = 0; foreach ($data as $value) { $id = $data[$count]['contact_id']; $ib_volume = $data[$count]['ib_volume']; $ib_comm = $data[$count]['ib_comm']; if ($temp == $id) { $newArray = array( 'contact_id' => $id, 'ib_volume' => $tempib_volume + $data[$count]['ib_volume'], 'ib_comm' => $tempib_comm + $data[$count]['ib_comm'] ); unset($array[$temp-1]); $array[$temp] = $newArray; } else { $array[$count] = $data[$count]; } $temp = $id; $tempib_volume = $data[$count]['ib_volume']; $tempib_comm = $data[$count]['ib_comm']; $count++; } echo "<pre>"; print_r(array_values($array));exit; ``` ?>
U can use `foreach`loop,like this: ``` $arr = Array ( '0' => Array ( 'contact_id' => 458, 'contact_fullName' => 'Karla Pearson', 'contact_email' => 'karla.pearson@kp.com', 'ib_level' => 1, 'ib_volume' => 0, 'ib_comm' => 0, 'parent_ib_code' => 70770, ), '4' => Array ( 'contact_id' => 466, 'contact_fullName' => 'Kelvin Brian', 'contact_email' => 'kelvin.brian@kb.in', 'ib_level' => 4, 'ib_volume' => 2.0000, 'ib_comm' => 20, 'parent_ib_code' => 97349, ), '5' => Array ( 'contact_id' => 466, 'contact_fullName' => 'Kelvin Brian', 'contact_email' => 'kelvin.brian@kb.in', 'ib_level' => 4, 'ib_volume' => 5.0000, 'ib_comm' => 222, 'parent_ib_code' => 97349, ) ); $arr2 = array(); foreach ($arr as $key => $value) { foreach ($arr2 as $k=> &$val) { if ($val['contact_id'] == $value['contact_id']) { $val['ib_volume'] = $val['ib_volume']+$value['ib_volume']; $val['ib_comm'] = $val['ib_comm']+$value['ib_comm']; continue 2; } } $arr2[] = $value; } ```
37,595,322
Is there a code to put in the settings or a plugin that will show the total number of lines along the current line and column in the status bar in Sublime Text 3?
2016/06/02
[ "https://Stackoverflow.com/questions/37595322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2319308/" ]
The code to show the number of lines in the status bar is very simple, just get the number of lines ```py line_count = view.rowcol(view.size())[0] + 1 ``` and write the to the status bar ```py view.set_status("line_count", "#Lines: {0}".format(line_count)) ``` If you want to pack in a plugin you just need to write this in a function and call it on some [EventListener](https://www.sublimetext.com/docs/3/api_reference.html#sublime_plugin.EventListener). Create a plugin by clicking `Tools >> Developer >> New Plugin...` and paste: ```py import time import sublime import sublime_plugin last_change = time.time() update_interval = 1.5 # s class LineCountUpdateListener(sublime_plugin.EventListener): def update_line_count(self, view): line_count = view.rowcol(view.size())[0] + 1 view.set_status("line_count", "#Lines: {0}".format(line_count)) def on_modified(self, view): global last_change current_change = time.time() # check if we haven't embedded the change in the last update if current_change > last_change + update_interval: last_change = current_change sublime.set_timeout(lambda: self.update_line_count(view), int(update_interval * 1000)) on_new = update_line_count on_load = update_line_count ``` This does in essentially call the command, when creating a new view, loading a file, and modifying the views content. For performance reason it has some logic to not call it on every modification.
Goto menu -> find -> find in files. Then select regex. use this pattern to count line including white spaces in each line- ``` ^(.*)$ ``` To count the number of lines excluding white spaces, use pattern ``` ^.*\S+.*$ ``` you can specify if you exclude some directories of file types like ``` c:\your_project_folder\,*.php,*.phtml,*.js,*.inc,*.html, -*/folder_to_exclude/* ``` Note - Characters other than white spaces will get also count because they too have start and end with white space.
68,012,808
I'm working on a personal project that involves a Beaglebone blue. I want to access it remotely from anywhere. I'm not sure what the best way to do this is. I know I could just forward a corresponding port (unsafe) or something along those lines but I want to avoid too many security flaws. The board controls a camera which I plan on displaying in a UI that also allows me to move the camera around. There are so many companies that have devices that can be controlled from anywhere...so how do I?
2021/06/17
[ "https://Stackoverflow.com/questions/68012808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4496298/" ]
There are a lot of solutions for this question. I will mention a few. **In general your device should either:** Have a public ip (if your infra allows it and your ISP provides this service), and then you can access it directly. Connect to an online server using some service: 1. Using VPN. Connecting your device to an openVPN server (I think this is the most popular solution). Wiregurd is also quite popular 2. Using consul or etcd or similar service for its service discovery feature 3. Using a cloud provider (AWS, Azure, GCP etc.) IoT service products
So let me post my comments as a coherent answer. Assuming you have a dynamic IP but otherwise unrestricted access to it from public Internet: 1. Make sure your router always gives the BB the same address in LAN 2. Install your Web UI and other stuff on BB 3. Configure SSH server on BB to accept only key-based authentication, no passwords (`PasswordAuthentication no` in `/etc/ssh/sshd_config`). 4. Generate a keypair in your PC and give your public key to the BB (in `/home/<youruser>/.ssh/authorized_keys`). Ensure key-based SSH logins works in local network before proceeding. 5. Subscribe to a dynamic DNS service with a Linux client that runs on ARM. Install the client on BB. I use No-IP, where the client comes as source code and probably compiles on BB (haven't tested). It's a bit annoying as you have to re-activate your free subscription once a month, maybe there are better services. 6. In your router forward a random external port (8822, 62222, pick a mnemonic) to the BB-s IP and port 22. 7. Remotely SSH into the BB using your dynamic DNS and external port (e.g. myhome.no-ip.org:62222). While testing in your LAN, note some routers support a "hairpin" connection to the public IP from inside the LAN, some don't. Don't forget to configure your SSH client to activate local port 80 forwarding in the client (`-L 80:localhost:80` in command line, similar in Putty GUI) 8. While the SSH link is up, you can access the Web UI running in BB from your local PC on address `http://localhost:80` (securely tunneled through the SSH connection).
6,487,649
I’m getting a lot of errors. And I've tried several suggestion across different sites, deleted the parent function, removed the array, updated my php ini file, no luck. This is the first of 13 errors I’m getting. A PHP Error was encountered Severity: Warning Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?) Filename: libraries/Email.php Line Number: 1673 Someone please help. ``` class Email extends CI_Controller { function index() { $config['protocol'] = 'smtp'; $config['smtp_host'] = 'ssl://smtp.googlemail.com'; $config['smtp_port'] = 465; $config['smtp_user'] = 'myemail@gmail.com'; $config['smtp_pass'] = 'mypassword'; $this->load->library('email'); $this->email->initialize($config); $this->email->set_newline("\r\n"); $this->email->from('myemail@gmail.com', 'My Name'); $this->email->to('myemail@gmail.com'); $this->email->subject('This is an email test'); $this->email->message('Its working. Great!'); if($this->email->send()) { echo 'Your email was sent, dude.'; } else { show_error($this->email->print_debugger()); } } ``` }
2011/06/27
[ "https://Stackoverflow.com/questions/6487649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/798060/" ]
Use a phpinfo(); statement in a .php file to check if the openssl extension actually loaded. In your `php.ini` enable **php\_openssl** ``` extension=php_openssl.so ``` if you are on Windows, then ``` extension=php_openssl.dll ```
Mayowa: Perhaps I'm a little late and you already has this solved. After searching a lot in the web I found out that for mail configuration simple quotes and double quotes is not the same. I use the /application/config/email.php file and after many attempts I found out that this will not work: ``` $config['protocol'] = 'smtp'; $config['smtp_host'] = 'ssl://smtp.googlemail.com'; $config['smtp_port'] = 465; $config['smtp_user'] = 'myemail@gmail.com'; $config['smtp_pass'] = 'mypassword'; ``` But this will: ``` $config['protocol'] = "smtp"; $config['smtp_host'] = "ssl://smtp.googlemail.com"; $config['smtp_port'] = 465; $config['smtp_user'] = "myemail@gmail.com"; $config['smtp_pass'] = "mypassword"; ``` Hope it helps.
50,618,661
I am trying to load the multibyte character with length more than 7000 char from my External Tables to SQL DW Internal tables. I have the data stores in a compressed format in BLOB Storage and External tables are pointed to the BLOB Storage Location. External table with varchar supports till 4000 charater. is there any other approach for this.
2018/05/31
[ "https://Stackoverflow.com/questions/50618661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9874394/" ]
If you use PolyBase to load the data directly into the SQL DW production tables (dbo.) from the Azure Blob Storage via the linked External (ext.) tables, you should be able to get around the external table limitation. This tutorial walks you through the process: [Tutorial: Load New York Taxicab data to Azure SQL Data Warehouse](https://learn.microsoft.com/en-us/azure/sql-data-warehouse/load-data-from-azure-blob-storage-using-polybase)
How have you defined your database column? The limit for a varchar is 8,000 characters, but an nvarchar is 4,000 characters. Because you're using multi-byte characters I guess you're using nvarchar. Consider using nvarchar(max) as your target type for this column. (EDIT) As pointed out in the comments, an EXTERNAL table does not support (max).
1,383,721
I come across this problem in an advanced maths textbook for grade 11 in my country. And it's marked a star, which means that it's a difficult exercise, and so, no solution for this problem is given. I can solve problems asking for which conditions do $\sin(\alpha + \beta) = \sin(\alpha) + \sin(\beta)$, and $\tan(\alpha + \beta) = \tan(\alpha) + \tan(\beta)$ hold. They are pretty easy, and straight-forward. But for this problem ($\cos(\alpha + \beta) = \cos(\alpha) + \cos(\beta)$), I have tried using all kinds of formulas, from *Sum of Angles*, to *Sum to Product*, and *Double Angles*, but without any luck. So, I think there should be some glitch here that I haven't been able to spot it out. So I hope you guys can give me some hints, or just a little push as a start. Any help would be greatly appreciated, Thank you very much, And have a good day, :D
2015/08/04
[ "https://math.stackexchange.com/questions/1383721", "https://math.stackexchange.com", "https://math.stackexchange.com/users/49685/" ]
The following contour plots hint us why the third equation defies many attempts. [![enter image description here](https://i.stack.imgur.com/C0yXP.png)](https://i.stack.imgur.com/C0yXP.png) Another possible explanation is that, if we substitute $x = \tan(\alpha/2)$ and $y = \tan(\beta/2)$ then the formulas $$ \sin \alpha = \frac{2x}{1+x^2}, \quad \cos \alpha = \frac{1-x^2}{1+x^2}, \quad \tan \alpha = \frac{2x}{1-x^2} $$ show that \begin{align\*} \sin(\alpha+\beta) = \sin\alpha+\sin\beta &\quad \Longleftrightarrow \quad xy(x+y) = 0, \\ \tan(\alpha+\beta) = \tan\alpha+\tan\beta &\quad \Longleftrightarrow \quad xy(x+y)(1-xy) = 0, \\ \cos(\alpha+\beta) = \cos\alpha+\cos\beta &\quad \Longleftrightarrow \quad 3x^2y^2 - x^2 - 4xy - y^2 - 1 = 0. \end{align\*} This may be another reason why our equation seems impossible to solve in simple terms. Finally, one interesting observation is that $$ \cos(\alpha+\beta) + 1 = \cos\alpha + \cos\beta \quad \Longleftrightarrow \quad xy(1-xy) = 0 $$ can be easily solved.
Write $x=\cos\alpha$, $y=\cos\beta$, and now write $\cos(\alpha+\beta)$ in terms of just $x$ and $y$. Rearrange the terms of the equation $\cos(\alpha+\beta)=\cos\alpha+\cos\beta$ and square both sides. You should now get an equation you can use to solve for $y$ in terms of $x$. It doesn't look like the solution is going to be very pretty though!
5,580
Every time I try to hold water with a obstacle, it leaks out. Here is one example I have made. ![Water leaking through bowl](https://i.stack.imgur.com/BvB6O.png) The shape has no holes, and the water is partially contained but slowly leaks out. This has occurred every time I have tried this. What could the cause be?
2013/12/16
[ "https://blender.stackexchange.com/questions/5580", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/1165/" ]
For me it helped when I applied *Surface Thickness* to the obstacle. [![enter image description here](https://i.stack.imgur.com/BV5Ad.png)](https://i.stack.imgur.com/BV5Ad.png)
Try to apply modifiers on your obstacle, especially Solidify. Fluid seems to leak when the obstacle's geometry has to be computed on-the-fly.
53,294,979
Below is the versions i am using "@types/jasmine": "^2.8.9" "typescript": "~2.6.2" ``` "devDependencies": { "@ionic/app-scripts": "3.2.0", "@types/jasmine": "^2.8.9", "@types/node": "^10.12.5", "angular2-template-loader": "^0.6.2", "html-loader": "^0.5.5", "istanbul-instrumenter-loader": "^3.0.1", "jasmine": "^3.3.0", "jasmine-spec-reporter": "^4.2.1", "karma": "^3.1.1", "karma-chrome-launcher": "^2.2.0", "karma-coverage-istanbul-reporter": "^2.0.4", "karma-jasmine": "^1.1.2", "karma-jasmine-html-reporter": "^1.4.0", "karma-sourcemap-loader": "^0.3.7", "karma-webpack": "^3.0.5", "null-loader": "^0.1.1", "protractor": "^5.4.1", "ts-loader": "^3.5.0", "ts-node": "^7.0.1", "typescript": "~2.6.2" }, ``` But still i am getting the below error ``` Error: node_modules/@types/jasmine/index.d.ts(138,47): error TS1005: ';' expected. node_modules/@types/jasmine/index.d.ts(138,90): error TS1005: '(' expected. node_modules/@types/jasmine/index.d.ts(138,104): error TS1005: ']' expected. node_modules/@types/jasmine/index.d.ts(138,112): error TS1005: ',' expected. node_modules/@types/jasmine/index.d.ts(138,113): error TS1136: Property assignment expected. node_modules/@types/jasmine/index.d.ts(138,121): error TS1005: ')' expected. node_modules/@types/jasmine/index.d.ts(138,147): error TS1005: '(' expected. node_modules/@types/jasmine/index.d.ts(138,162): error TS1005: ']' expected. node_modules/@types/jasmine/index.d.ts(138,163): error TS1005: ',' expected. node_modules/@types/jasmine/index.d.ts(138,164): error TS1136: Property assignment expected. node_modules/@types/jasmine/index.d.ts(138,165): error TS1136: Property assignment expected. node_modules/@types/jasmine/index.d.ts(138,179): error TS1005: ',' expected. node_modules/@types/jasmine/index.d.ts(138,183): error TS1005: ':' expected. node_modules/@types/jasmine/index.d.ts(138,208): error TS1005: '{' expected. node_modules/@types/jasmine/index.d.ts(138,217): error TS1005: ':' expected. node_modules/@types/jasmine/index.d.ts(138,222): error TS1005: ',' expected. node_modules/@types/jasmine/index.d.ts(138,227): error TS1005: ':' expected. node_modules/@types/jasmine/index.d.ts(138,228): error TS1109: Expression expected. node_modules/@types/jasmine/index.d.ts(138,230): error TS1005: ')' expected. ``` I am not getting how to resolve this. Can anyone please help me.
2018/11/14
[ "https://Stackoverflow.com/questions/53294979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4675072/" ]
You have just change typescript@2.8.4 and @types/jasmine@2.8.3 Like 1. npm install typescript@2.8.4 --save-dev 2. npm install @types/jasmine@2.8.3 --save-dev It's working 100%. Thanks,
If you have reached this page when you are not using Jasmine anywhere in your application, then I would suggest checking your import statements on the top of your ts file. It should have this added on the top: ``` import { ConsoleReporter } from 'jasmine'; ``` I saw this accidentally added on the top when I was using console object to log into the browser and the autocomplete feature of VS Code completed it with ConsoleReporter and this import statement was added. Removing this statement fixed my issue.
336,495
Working with Microsoft SQL Server I found extremely useful SQL Server Profiler and Estimated Execution Plan (available in Management Studio) to optimize queries during development and production system monitoring. Are there similar tools (open source or commercial) or techniques available for MySQL?
2008/12/03
[ "https://Stackoverflow.com/questions/336495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42512/" ]
You can get information about how a query will execute using [`EXPLAIN`](http://dev.mysql.com/doc/refman/5.0/en/explain.html). For example: ``` EXPLAIN SELECT * FROM foo INNER JOIN bar WHERE foo.index = 1 AND bar.foo_id = foo.id ``` It will then tell you which indexes will be used, what order the tables will be joined in, how many rows it expects to select from each table and so on.
As RoBorg suggests, you can use EXPLAIN to show the details of how MySQL will execute your query. I found [this article](http://dev.mysql.com/doc/refman/5.0/en/using-explain.html) more useful, as it tells you how to interpret the results and improve your SQL. Also helpful are these articles on [query cache configuration](http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html) and [using ALTER TABLE](http://dev.mysql.com/doc/refman/5.0/en/alter-table.html) to add and remove indexes.
49,520,971
I have installed hunspell 1.6 in python 3.5 environment using conda. When I try to import, it gives a import error. ``` ImportError: No module named 'hunspell' ``` Here is the screenshot attached. [Hunspell Error](https://i.stack.imgur.com/KPB6B.png)
2018/03/27
[ "https://Stackoverflow.com/questions/49520971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9418332/" ]
It's pages\_messaging permission, Facebook not allow it at this time. Please remove it for now until Facebook update.
You need a Login Review in your app for use 'user\_friends' permission <https://developers.facebook.com/blog/post/2018/03/26/facebook-platform-changes/>
32,076,963
I've read and read and looked at examples on SO and tried to find the answer to my question but cant seem to find it but, here's the scenario to my particular problem: **Main.php** has a a search form up top, based on search, it posts results on left side of page with help of css. when you click a result, based on some sql queries it runs, it does a check to see if the person has done a certain event. IF they haven't I want it to post on right side a form to enter some info since if its your first time, with is another php page Main.php Search form ----------------------------------------------------- Results posted...| Tabset.php w/ another ...........................| form for first time users ...........................| ...........................| ...........................| ...........................| Apologies for the crude ASCIIish type art, just trying to give a better visual of whats going on. **Tabset.php** So in the tabset php page I have the following code: ``` <div id="main_form"> <h3>Please enter the following:</h3> <FORM id="form1" METHOD="POST"> <INPUT TYPE = "text" id = "someVAR1" placeholder="someVAR1"/> / <INPUT TYPE = "text" id = "someVAR2" placeholder="someVAR2"/> <INPUT TYPE = "submit" id = "submit" VALUE = "ok"/> </FORM> </div> <?php if($_POST) { $someVAR1=$_POST['someVAR1']; $someVAR2=$_POST['someVAR2']; } ``` **refreshform.js** ``` $(document).ready(function() { $("#submit").click(function(e) { e.preventDefault(); var someVAR1= $("#someVAR1").val(); var someVAR1= $("#someVAR2").val(); if(someVAR1=='' || someVAR2=='') { alert("Some Fields are Blank....!!! Please enter something!!!"); } else { $.ajax({ type: "POST", url: "Tabset.php", success: function(){ $('#form1').fadeOut(200).hide(); $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); $('#form1')[0].reset(); } }); } return false; }); }); ``` When I click the submit button, its not catching that the fields are empty AND its still refreshing my main.php page Any help would be greatly appreciated... I also tried this for my JS as well, with the same results: ``` $(document).ready(function(){ $("#submit").click(function(){ var someVAR1= $("#someVAR1").val(); var someVAR2= $("#someVAR2").val(); //alert(sBP); if(someVAR1==''|| someVAR2==''){ alert("Some Fields are Blank....!!! Please enter something!!!"); } else{ alert("Resetting data now..."); $('#form')[0].reset(); //To reset form fields } }); }); ```
2015/08/18
[ "https://Stackoverflow.com/questions/32076963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5178089/" ]
You are only getting the start and end positions for the first element, which has 21 characters. Therefore for the elements that have 20 characters you are including the closing parenthesis, thereby making `as.numeric` return `NA`. You should change it to extract the entire column for these values: ``` start <- stringi::stri_locate(Input_String, regex = "\\(")[,1] end <- stringi::stri_locate(Input_String, regex = "\\)")[,1] ``` Or alternatively you could use base functions to extract the correct values: ``` start.end <- regexpr("\\d+",t) as.numeric(substr(t, start.end, start.end + attr(start.end,"match.length")-1))/1000 [1] 1184889600 1377648000 1386201600 1099353600 1403222400 1052092800 [7] 1324425600 1115942400 1343260800 940377600 1438819200 975715200 [13] 1125446400 1194566400 1331856000 1396569600 1346803200 1438560000 [19] 950832000 1380326400 1432771200 1436572800 1376438400 1428537600 [25] 869788800 1343001600 1382486400 1259539200 1427500800 1421971200 [25] 869788800 1343001600 1382486400 1259539200 1427500800 1421971200 ```
You could run those dates through the date handler `R_json_dateStringOp` in `RJSONIO::fromJSON` after removing three zeros from the end of your string. ``` library(RJSONIO) ## create the JSON string after removing three zeros at the end of each 't' make <- toJSON(gsub("0{3}(?=\\))", "", t, perl = TRUE)) ## run it through fromJSON() with the date handler and collapse result to an atomic vector do.call(c, fromJSON(make, stringFun = "R_json_dateStringOp")) # [1] "2007-07-19 17:00:00 PDT" "2013-08-27 17:00:00 PDT" "2013-12-04 16:00:00 PST" # [4] "2004-11-01 16:00:00 PST" "2014-06-19 17:00:00 PDT" "2003-05-04 17:00:00 PDT" # [7] "2011-12-20 16:00:00 PST" "2005-05-12 17:00:00 PDT" "2012-07-25 17:00:00 PDT" #[10] "1999-10-19 17:00:00 PDT" "2015-08-05 17:00:00 PDT" "2000-12-01 16:00:00 PST" #[13] "2005-08-30 17:00:00 PDT" "2007-11-08 16:00:00 PST" "2012-03-15 17:00:00 PDT" #[16] "2014-04-03 17:00:00 PDT" "2012-09-04 17:00:00 PDT" "2015-08-02 17:00:00 PDT" #[19] "2000-02-17 16:00:00 PST" "2013-09-27 17:00:00 PDT" "2015-05-27 17:00:00 PDT" #[22] "2015-07-10 17:00:00 PDT" "2013-08-13 17:00:00 PDT" "2015-04-08 17:00:00 PDT" #[25] "1997-07-24 17:00:00 PDT" "2012-07-22 17:00:00 PDT" "2013-10-22 17:00:00 PDT" #[28] "2009-11-29 16:00:00 PST" "2015-03-27 17:00:00 PDT" "2015-01-22 16:00:00 PST" ```
42,198,417
I want to delete a record from my table named post. I am sending a param named tag in my view to delete a certain record against this tag. So here is my route ``` Route::get('/delete' , array('as' =>'delete' , 'uses' => 'Postcontroller@deletepost')); ``` by this route i am delete my post against it's 'tag' field. my table has two column. one is tag and other is content My delete fucntion in PostController is ``` public function deletepost($tag){ $post = post::find($tag); //this is line 28 in my fuction $post->delete(); echo ('record is deleted') ; } ``` I am send tag from my view but it is giving the following error ``` ErrorException in Postcontroller.php line 28: Missing argument 1 for App\Http\Controllers\Postcontroller::deletepost() ```
2017/02/13
[ "https://Stackoverflow.com/questions/42198417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5796642/" ]
Your action should look like this: ``` use Illuminate\Http\Request; public function deletepost(Request $request) // add Request to get the post data { $tagId = $request->input('id'); // here you define $tagId by the post data you send $post = post::find($tagId); if ($post) { $post->delete(); echo ('record is deleted!'); } else { echo 'record not found!'); } } ```
You have to pass the parameter for an example if you pass it like tag\_id then you have to capture it inside the controller function using Request. ``` public function deletepost(Request $request){ $post = post::find($request::get('tag_id')); $post->delete(); echo ('record is deleted'); } ```
338,944
I'm working on a JIRA implementation and need to make use of the API. Does anyone know of an existing .NET wrapper for the JIRA SOAP API?
2008/12/03
[ "https://Stackoverflow.com/questions/338944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3452/" ]
In a Visual Studio .NET project, right click the project references and choose 'Add Service Reference', enter the URL of JIRA's WSDL descriptor (<http://your_installation/rpc/soap/jiraservice-v1.wsdl>), and Visual Studio will auto-generate a .NET class for accessing the JIRA SOAP API. The parameter names aren't particularly meaningful so you'll need to refer back to the documentation quite a bit at first.
As per this page <https://developer.atlassian.com/jiradev/support/archive/jira-rpc-services/creating-a-jira-soap-client/remote-api-soap-examples>, JIRA SOAP API has been deprecated, and as per this page <https://developer.atlassian.com/jiradev/latest-updates/soap-and-xml-rpc-api-deprecation-notice>, completely removed from JIRA 7.0+. I would recommend to go with JIRA REST API.
23,142,021
When I run the following query on a table that has 22M rows it in it takes 20 seconds to run: ``` select p.*, (select avg(close) from endOfDayData p2 where p2.symbol = p.symbol and p2.date between p.date - interval 6 day and p.date ) as MvgAvg_X from endOfDayData p where p.symbol = 'AAPL' ``` The table structure looks like: ``` mysql> desc endOfDayData; +--------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------+------+-----+---------+-------+ | date | date | NO | PRI | NULL | | | symbol | varchar(14) | NO | PRI | NULL | | | open | decimal(10,4) | NO | | NULL | | | high | decimal(10,4) | NO | | NULL | | | low | decimal(10,4) | NO | | NULL | | | close | decimal(10,4) | NO | | NULL | | | volume | int(11) | NO | | NULL | | +--------+---------------+------+-----+---------+-------+ ``` and the following indexes exist: ``` mysql> show index from endOfDayData; +--------------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +--------------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | endOfDayData | 0 | PRIMARY | 1 | date | A | 162294 | NULL | NULL | | BTREE | | | | endOfDayData | 0 | PRIMARY | 2 | symbol | A | 24019617 | NULL | NULL | | BTREE | | | | endOfDayData | 1 | EOD_dates | 1 | date | A | 50145 | NULL | NULL | | BTREE | | | | endOfDayData | 1 | EOD_symbol | 1 | symbol | A | 14322 | NULL | NULL | | BTREE | | | +--------------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ 4 rows in set (0.00 sec) ``` The machine is a dedicated box with 80GB of ram and dual processor. I feel that it should be running in under a second with the correct indexes. Thanks ``` | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------------+-------+------+------------------------------+-------‌​-----+---------+--------------------+------+-----------------------+ | 1 | PRIMARY | p | ref | EOD_symbol | EOD_symbol | 16 | const | 8409 | Using index condition | | 2 | DEPENDENT SUBQUERY | p2 | ref | PRIMARY,EOD_dates,EOD_symbol | EOD_symbol | 16 | financial.p.symbol | 1677 | Using index condition | ``` I have created a new table with ID int as a primary key and created an index on symbol, date. ``` CREATE INDEX EODDateSym ON endOfDayData_new (symbol, date) USING BTREE; ``` and still getting 17 seconds. Thanks again for all the ideas and help my my.conf is ``` [mysql] # CLIENT # port = 3306 socket = /var/lib/mysql/mysql.sock [mysqld] # GENERAL # user = mysql default-storage-engine = InnoDB socket = /var/lib/mysql/mysql.sock pid-file = /var/lib/mysql/mysql.pid # MyISAM # key-buffer-size = 32M myisam-recover = FORCE,BACKUP # SAFETY # max-allowed-packet = 16M max-connect-errors = 1000000 # DATA STORAGE # datadir = /var/lib/mysql/ # BINARY LOGGING # log-bin = /var/lib/mysql/mysql-bin expire-logs-days = 14 sync-binlog = 1 server_id = 1 # CACHES AND LIMITS # tmp-table-size = 32M max-heap-table-size = 32M query-cache-type = 0 query-cache-size = 0 max-connections = 500 thread-cache-size = 50 open-files-limit = 65535 table-definition-cache = 4096 table-open-cache = 4096 # INNODB # innodb-flush-method = O_DIRECT innodb-log-files-in-group = 2 innodb-log-file-size = 512M innodb-flush-log-at-trx-commit = 1 innodb-file-per-table = 1 innodb-buffer-pool-size = 68G # LOGGING # log-error = /var/lib/mysql/mysql-error.log log-queries-not-using-indexes = 1 slow-query-log = 1 slow-query-log-file = /var/lib/mysql/mysql-slow.log ```
2014/04/17
[ "https://Stackoverflow.com/questions/23142021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3546638/" ]
I got around this issue by executing some javascript to fill out date fields. ``` protected void FillOutDate(string cssSelector, DateTime date) { var js = Driver as IJavaScriptExecutor; if (js != null) js.ExecuteScript(string.Format("$('{0}').val('{1}').change()", cssSelector,date.ToString("yyyy-MM-dd"))); } ``` OR simply ``` ((IJavaScriptExecutor)Driver).ExecuteScript("$('#IdSelector').val('2014-06-11').change()"); ```
I believe the input type of "date" is new to html 5 and requires a specific to the RFC 3339: <http://www.ietf.org/rfc/rfc3339.txt> Try using 1981-01-01 and it should work. YYYY-MM-DD instead of MM/DD/YYYY as you have provided.
25,197,480
Thanks a lot in advance for helping me out! ``` var f2 = function() { x = "inside f2"; }; f2(); console.log(x); // → inside f2 ``` Why do I get the x as a global variable with value "inside f2" when I didn't declare it to be a global variable with "var x;" before defining the function? ``` var f2 = function() { var x = "inside f2"; }; f2(); console.log(x); // → Uncaught ReferenceError: x is not defined ``` Am I right in assuming that x is not defined in this case because there is no global variable x, only the local variable x within the function f2?
2014/08/08
[ "https://Stackoverflow.com/questions/25197480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3774341/" ]
> > Why do I get the x as a global variable with value "inside f2" when I didn't declare it to be a global variable with "var x;" before defining the function? > > > Because the [specification](http://es5.github.io/#x11.13.1) [says so](http://es5.github.io/#x8.7.2). If you assign to an undeclared variable, a global variable is created. In [strict mode](https://stackoverflow.com/q/1335851/218196) this will throw an error (which is more reasonable). > > Am I right in assuming that x is not defined in this case because there is no global variable x, only the local variable x within the function f2? > > > Yes. --- > > [**8.7.2 `PutValue (V, W)`**](http://es5.github.io/#x8.7.2) > > [...] > > 3. If IsUnresolvableReference(V), then > >    a. If IsStrictReference(V) is true, then > >      i. Throw ReferenceError exception. > >    b. Call the [[Put]] internal method of the global object, passing GetReferencedName(V) for the property name, W for the value, and false for the Throw flag. > > >
Doing `x = "inside f2"` will climb the scope chain until it hits an `x` or until the global space, where it will do property assignment on the global object. It doesn't matter if you've *declared* `x` in the global space or not.
33,994,046
I am trying to set `LatLangBound` in map.When I give `SouthWest LatLang` & `NorthEast Latlang` of India, I am getting an error message that latitude of SouthWest > latitude of NorthEast (28.5827577 > 20.593684). Is there any other way to display India regions when I start `MapFragment`. My code snippet is. ``` private LatLngBounds India=new LatLngBounds(new LatLng(28.5827577,77.0334179),new LatLng(20.593684,78.96288)); mapView = (MapView) rootview.findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mMap = mapView.getMap(); try { mMap.setMyLocationEnabled(true); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, latitude), 6)); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(India.getCenter(),6)); CameraPosition cameraPosition =new CameraPosition.Builder().target(new LatLng(latitude,latitude)).zoom(2).bearing(0).tilt(90).build(); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); }catch (Exception e) { e.printStackTrace(); } return rootview; ```
2015/11/30
[ "https://Stackoverflow.com/questions/33994046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5413238/" ]
For people who are upgrading their php from 7.0 to 7.4 like me, and not able to get php-redis working. These are the steps I used after following the answers above. 1) remove Redis ``` sudo apt purge php-redis ``` 2) Install Igbinary ``` sudo apt-get install php-igbinary ``` 3) Install php-redis again ``` sudo apt-get install php-redis ``` I did the steps above because it seems only php7.0 is recognising the php-redis install but not the currently enabled php7.4 I also recommend removing other versions of PHP if you have should your problem continue unsolved.
just resolve the same problem: php-pecl-redis installed by yum will cause this problem. so you need to install the php-redis manually. wget the package and phpize - configure - make ....
5,343,689
How do you read the contents of a file into an `ArrayList<String>` in Java? **Here are the file contents:** ``` cat house dog . . . ```
2011/03/17
[ "https://Stackoverflow.com/questions/5343689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618712/" ]
To share some analysis info. With a simple test how long it takes to read ~1180 lines of values. If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms The Scanner is much slower. Took me ~138ms The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.
Here is an entire program example: ``` import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class X { public static void main(String[] args) { File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt"); try{ ArrayList<String> lines = get_arraylist_from_file(f); for(int x = 0; x < lines.size(); x++){ System.out.println(lines.get(x)); } } catch(Exception e){ e.printStackTrace(); } System.out.println("done"); } public static ArrayList<String> get_arraylist_from_file(File f) throws FileNotFoundException { Scanner s; ArrayList<String> list = new ArrayList<String>(); s = new Scanner(f); while (s.hasNext()) { list.add(s.next()); } s.close(); return list; } } ```
21,448,735
I am new to cakephp and trying to implement `AJAX` . I have a view `add.ctp` in which I have written the following lines : ``` $('#office_type').change(function(){ var office_id = $('#office_type').val(); if(office_id > 0) { var data = office_id; var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/"; $.ajax({ type: "GET", url: url_to_call, data = data, //dataType: "json", success: function(msg){ alert(msg); } }); } }); ``` And the function `get_office_names_by_catagory()` within `OfficenamesController.php` is: ``` public function get_office_name_by_catagory($type = '') { Configure::write("debug",0); if(isset($_GET['type']) && trim($_GET['type']) != ''){ $type = $_GET['type']; $conditions = array("Officename.office_type"=> $type); $recursive = -1; $office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive)); } $this->layout = 'ajax'; //return json_encode($office_names); return 'Hello !'; } ``` But unfortunately, its not alerting anything ! Whats wrong ?
2014/01/30
[ "https://Stackoverflow.com/questions/21448735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/729144/" ]
Could be caused by two issues: 1) In your js snippet, you are querying `http://localhost/testpage/officenames/get_office_names_by_catagory/`. Note the plural 'names' in `get_office_names_by_category`. In the PHP snippet, you've defined an action `get_office_name_by_catagory`. Note the singular 'name'. 2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this [link](http://book.cakephp.org/2.0/en/views/json-and-xml-views.html).
I think, you have specified data in wrong format: ``` $.ajax({ type: "GET", url: url_to_call, data = data, // i guess, here is the problem //dataType: "json", success: function(msg){ alert(msg); } }); ``` To ``` $.ajax({ type: "GET", url: url_to_call, data: { name: "John", location: "Boston" }, //example success: function(msg){ alert(msg); } }); ``` You should specify the data in key:value format.
2,437,622
I'm practicing Jquery and I've written this simple Jquery statement: ``` var someText = $("table tr td").text(); ``` Should this not return all text of td elements found within tr's that are found within tables? How do I fix this? Currently when I run this, it says that `table tr td` is null, but I have a table on the page I'm testing on. Thanks!
2010/03/13
[ "https://Stackoverflow.com/questions/2437622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205930/" ]
Python 2.7 and 3.1 have [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) and there are pure-Python implementations for earlier Pythons. ``` from collections import OrderedDict class LimitedSizeDict(OrderedDict): def __init__(self, *args, **kwds): self.size_limit = kwds.pop("size_limit", None) OrderedDict.__init__(self, *args, **kwds) self._check_size_limit() def __setitem__(self, key, value): OrderedDict.__setitem__(self, key, value) self._check_size_limit() def _check_size_limit(self): if self.size_limit is not None: while len(self) > self.size_limit: self.popitem(last=False) ``` You would also have to override other methods that can insert items, such as `update`. The primary use of `OrderedDict` is so you can control what gets popped easily, otherwise a normal `dict` would work.
There have been many good answers, but I want to point out a simple, pythonic implementation for LRU cache. It's similar to Alex Martelli's answer. ``` from collections import OrderedDict, MutableMapping class Cache(MutableMapping): def __init__(self, maxlen, items=None): self._maxlen = maxlen self.d = OrderedDict() if items: for k, v in items: self[k] = v @property def maxlen(self): return self._maxlen def __getitem__(self, key): self.d.move_to_end(key) return self.d[key] def __setitem__(self, key, value): if key in self.d: self.d.move_to_end(key) elif len(self.d) == self.maxlen: self.d.popitem(last=False) self.d[key] = value def __delitem__(self, key): del self.d[key] def __iter__(self): return self.d.__iter__() def __len__(self): return len(self.d) ```
19,430,868
Can you please help me to find a expression to accept these : ``` C1D3 A1Z5R7 H2L7V5X3 ``` but does not accept these : ``` A1B2A2 //Because the A repeated 2 times C4F5F3 C2C1 B1B2F6 ``` I am tring to create a expression to use it in C#.Net
2013/10/17
[ "https://Stackoverflow.com/questions/19430868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985084/" ]
In this sort of problem back-references are you're friend. so `(.).*\1` will match a character followed by anything followed by whatever the first capture group matched
You can use this negative lookahead based rgex to avoid matching duplicate containing strings: ``` /^(?:(.)(?!.*?\1))+$/ /^(?:(.)(?!.*?\1))+$/.test('A1B2D3'); // true /^(?:(.)(?!.*?\1))+$/.test('A1B2A3'); // false ```
8,920,199
If I do the following in code for an 8-bit processor: ``` typedef union { unsigned long longn ; unsigned char chars[4]; } longbytes; ``` Is `longbytes.chars[0]` always going to be the lowest byte of `longbytes.longn`, or does it depend on endianness/compiler/platform/target/luck etc.? I've viewed the disassembly of my complied code and that's how it is in my specific case, but I'm curious if this code is portable.
2012/01/19
[ "https://Stackoverflow.com/questions/8920199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/894445/" ]
There are several reasons why this is not portable: * It depends on the endianess your platform (or compiler) enforces which byte is written first, so you can't count on `chars[0]` addressing the lowest byte * `unsigned long` is not guaranteed to be exactly as long as `4` chars, so depending on the platform you might not even get the complete `long` (or sizeof(`long`) might be smaller then `4` and you read further, but that's unlikely for 8Bit processors at least. * Reading a different union member then you wrote to is generally not portable, it is implementation defined behaviour. The reason for this is basically the combination of the two other issues. So all in all that code is not portable at all.
In general, if you ever need to care about endianness you're doing something wrong, and need to work around your problem (e.g. with shifts and masks, or serialisation/de-serialisation). For example, rather than having a union maybe you should do something like: ``` uint32_t pack(uint8_t byte0, uint8_t byte1, uint8_t byte2, uint8_t byte3) { long result; result = byte0; result |= byte1 << 8; result |= byte2 << 16; result |= byte3 << 24; return result; } uint8_t unpack(int byteNumber, uint32_t value) { return (value >> (byteNumber * 8)); } ```
7,032,743
Is it possible to define an overloaded `operator[]` that takes more than one argument? That is, can I define `operator[]` as follows: ``` //In some class double operator[](const int a, const int b){ return big_array[a+offset*b];} ``` and later use it like this? ``` double b=some_obj[7,3]; ```
2011/08/11
[ "https://Stackoverflow.com/questions/7032743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/789750/" ]
Prior to C++23 it isn't possible. You can do this from C++23. [From cppreference](https://en.cppreference.com/w/cpp/language/operators#Array_subscript_operator): --------------------------------------------------------------------------------------------------- > > Since C++23, operator[] can take more than one subscripts. For example, an operator[] of a 3D array class declared as `T& operator[](std::size_t x, std::size_t y, std::size_t z);` can directly access the elements. > > > example code from there: <https://godbolt.org/z/993s5dK7z> [From C++23 draft](https://timsong-cpp.github.io/cppwp/over.sub#2): ------------------------------------------------------------------- ```cpp struct X { Z operator[](std::initializer_list<int>); Z operator[](auto...); }; X x; x[{1,2,3}] = 7; // OK, meaning x.operator[]({1,2,3}) x[1,2,3] = 7; // OK, meaning x.operator[](1,2,3) ``` Thus, the snippets you posted will work in C++23.
The better way to do that, since it doesn't lock you into creating temporaries and allows multiple arguments, is `operator()`. More details are in the [C++ FAQ](http://www.parashift.com/c++-faq/operator-overloading.html#faq-13.10).
10,670,379
You are given a large range [a,b] where 'a' and 'b' can be typically between 1 and 4,000,000,000 inclusive. You have to find out the XOR of all the numbers in the given range. This problem was used in TopCoder SRM. I saw one of the solutions submitted in the match and I'm not able to figure out how its working. Could someone help explain the winning solution: ```c long long f(long long a) { long long res[] = {a,1,a+1,0}; return res[a%4]; } long long getXor(long long a, long long b) { return f(b)^f(a-1); } ``` Here, `getXor()` is the actual function to calculate the xor of all number in the passed range [a,b] and "f()" is a helper function.
2012/05/20
[ "https://Stackoverflow.com/questions/10670379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1305805/" ]
I found out that the below code is also working like the solution given in the question. May be this is little optimized but its just what I got from observing repetition like given in the accepted answer, I would like to know / understand the mathematical proof behind the given code, like explained in the answer by @Luke Briggs Here is that JAVA code ``` public int findXORofRange(int m, int n) { int[] patternTracker; if(m % 2 == 0) patternTracker = new int[] {n, 1, n^1, 0}; else patternTracker = new int[] {m, m^n, m-1, (m-1)^n}; return patternTracker[(n-m) % 4]; } ```
Adding on even further to FatalError's answer, it's possible to prove (by induction) that the observed pattern in `f()` will cycle for every 4 numbers. We're trying to prove that for every integer `k >= 0`, ``` f(4k + 1) = 1 f(4k + 2) = 4k + 3 f(4k + 3) = 0 f(4k + 4) = 4k + 4 ``` where `f(n)` is `1 ^ 2 ^ ... ^ n`. As our **base case**, we can work out by hand that ``` f(1) = 1 f(2) = 1 ^ 2 = 3 f(3) = 3 ^ 3 = 0 f(4) = 0 ^ 4 = 4 ``` For our **inductive step**, assume that these equations are true up to a particular integer `4x` (i.e. `f(4x) = 4x`). We want to show that our equations are true for `4x + 1`, `4x + 2`, `4x + 3` and `4x + 4`. To help write and visualize the proof, we can let `b(x)` denote the binary (base-2) string representation of `x`, for example `b(7) = '111'`, `b(9) = '1001'`. and ``` b(4x) = 'b(x)00' b(4x + 1) = 'b(x)01' b(4x + 2) = 'b(x)10' b(4x + 3) = 'b(x)11' ``` Here is the inductive step: ``` Assume: f(4x) = 4x = 'b(x)00' Then: f(4x + 1) = f(4x) ^ (4x + 1) // by definition = f(4x) ^ 'b(x)01' // by definition = 'b(x)00' ^ 'b(x)01' // from assumption = '01' // as b(x) ^ b(x) = 0 f(4x + 2) = f(4x + 1) ^ (4x + 2) = f(4x + 1) ^ 'b(x)10' = '01' ^ 'b(x)10' = 'b(x)11' // this is 4x + 3 f(4x + 3) = f(4x + 2) ^ (4x + 3) = f(4x + 2) ^ 'b(x)11' = 'b(x)11' ^ 'b(x)11' = '00' For the last case, we don't use binary strings, since we don't know what b(4x + 4) is. f(4x + 4) = f(4x + 3) ^ (4x + 4) = 0 ^ (4x + 4) = 4x + 4 ``` So the pattern holds for the next four numbers after `4x`, completing the proof.
2,997,264
Sorry for this title, I didn't know how to describe it better. **I have** the following table: ``` <tr class="row-vm"> <td>...</td> <td>...</td> ... </tr> <tr class="row-details"> <td colspan="8"> <div class="vmdetail-left"> ... </div> <div class="vmdetail-right"> ... </div> </td> </tr> ``` Every second row contains detail data for the first row. By default, it is hidden with CSS, but I can slide it open with jQuery. **What I would like to achieve**: Table sorting similar to this jQuery plugin: <http://tablesorter.com/docs/> **The problem**: The plugin should "glue together" all pair rows, and move them together. The sorting should be done only with the data of the first row (`.row-vm`), while ignoring the content of the second row (`.row-details`). Is there a jQuery plugin that supports this?
2010/06/08
[ "https://Stackoverflow.com/questions/2997264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/284318/" ]
I [found this fiddle](http://jsfiddle.net/q7VL3/) for the jQuery tablesorter in another post, worked beautifully for me! ``` <tr class="row-vm"> <td>John</td> </tr> <tr class="row-details expand-child"> <td colspan="6"> Detail About John </td> </tr> ```
The plugin available at Datatables.net supports detail rows, though the way I use them the detail rows are opened via ajax rather than all the data always being present. But when you do sort/reorder the details stay with the main data.
38,096,937
How can I push another element to the `variables` property from the below object? ``` var request = { "name": "Name", "id": 3, "rules":[ { "name": "Rule name", "tags": [ { "tagId": 1, "variables":[ { "variable": "var1", "matchType": "Regex", "value": ".*" }, { "variable": "var2", "matchType": "Regex", "value": ".*" } ], "condition": false, }, { "tagId": 1, "condition": false, } ], "ruleSetId": 3, } ] } ``` For exaple, I need to add `{"variable": "var3", "matchType": "Regex", "value": ".*"}` to the `variables` property from `request` Object...how can I do this? ``` for(i=0;i<duplicates.length; i++) { var request = { "name": duplicates[i].scope, "id": 3, "rules":[ { "name": duplicates[i].scope + " " + "OP SDR Sync", "tags": [ { "tagId": 1, "variables":[ { } ], "condition": false, }, { "tagId": 1, "condition": false, } ], "ruleSetId": 3, } ] } request.rules[0].tags[0].variables[0].push({ "variable":"var3", "matchType": "Regex", "value": ".*" }); } ```
2016/06/29
[ "https://Stackoverflow.com/questions/38096937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737546/" ]
Try like this: ``` object = {"variable": "var3", "matchType": "Regex", "value": ".*"}; request.rules[0].tags[0].variables.push(object); ```
dot operator(.) can be used to get the value of a particular object property. square brackets ([]) can be used to access an element of an array. Now the answer to your question: ``` request.rules[0].tags[0].variables.push({ "variable": "var3", "matchType": "Regex", "value": ".*" }); ``` here, `[0]` specifies the first element of your array.
32,397,753
I have a table with the fields: Parent references the primary key ID in the same table (not foreign key). ``` +----+--------+------------+ | ID | Parent | Title | +----+--------+------------+ | 1 | 0 | Wallpapers | | 2 | 1 | Nature | | 3 | 2 | Trees | | 4 | 3 | Leaves | +----+--------+------------+ ``` I'm trying to select a row and all its parents. For example if I select "Leaves" I want to get "Trees", "Nature", and "Wallpaper" as well since that is the parent path up the hierarchy. Is this possible in one query? At the moment I'm using a loop in ColdFusion to get the next parent each iteration but it's not efficient enough.
2015/09/04
[ "https://Stackoverflow.com/questions/32397753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5300603/" ]
In PHP, I wrote a function that retrieve all the hierarchy of my route table (infinite depth). I think that, in this example, **you can see SQL syntax of query you are looking for**. I use same column names except in lowercase. ``` function get_breadcrumb($route_id) { //access PDO mysql object instance global $db; // sanitize route ID $route_id = intval($route_id); // query construction $q = "SELECT T2.* FROM ( SELECT @r AS parent_id, (SELECT @r := `parent` FROM `route` WHERE id = parent_id) AS `parent`, @l := @l + 1 AS `depth` FROM (SELECT @r := $route_id, @l := 0) vars, `route` T3 WHERE @r <> 0) T1 JOIN `route` T2 ON T1.parent_id = T2.id ORDER BY T1.`depth` DESC"; // call query in database if($res = $db->query($q)) { if($res = $res->fetchAll(PDO::FETCH_ASSOC)) { if($size = sizeof($res) > 0) { // push results in breadcrumb items array $breadcrumb['items'] = $res; $breadcrumb['levels'] = $size; // retrieve only titles $titles = array_column($res, 'title'); // construct html result seperated by '>' or '/' $breadcrumb['html']['gt'] = implode(' > ', $titles); $breadcrumb['html']['sl'] = implode(' / ', $titles); // returns all result (added in SESSION too) return $_SESSION['app']['breadcrumb'] = $breadcrumb; } } } // no result for that route ID return false; } ```
Use a UNION to combine the query that returns the main row with another query that returns the parent row. ``` SELECT * FROM YourTable WHERE Title = "Leaves" UNION SELECT t1.* FROM YourTable AS t1 JOIN YourTable AS t2 ON t1.id = t2.parent WHERE t2.Title = "Leaves") ```
370,156
*This tag has been burninated. Please do not recreate it. If you need advice on which tag to use, see the answer below. If you see this tag reappearing, it may need to be blacklisted.* --- I don't see how the [ebay](https://stackoverflow.com/questions/tagged/ebay "show questions tagged 'ebay'") tag is on topic here. I don't think we should have tags for sites (generally). The tag should be for an API that lets you talk to a site, and there is already an [ebay-api](https://stackoverflow.com/questions/tagged/ebay-api "show questions tagged 'ebay-api'") tag. 1. **Does it describe the contents of the questions to which it is applied? and is it unambiguous?** Perhaps, but [ebay-api](https://stackoverflow.com/questions/tagged/ebay-api "show questions tagged 'ebay-api'") is almost always a better tag for describing the contents of the question. 2. **Is the concept described even on-topic for the site?** I don't think so. The specific technology/API is what's on topic, not the name of the site. 3. **Does the tag add any meaningful information to the post?** Maybe a little, but again [ebay-api](https://stackoverflow.com/questions/tagged/ebay-api "show questions tagged 'ebay-api'") is much more meaningful. 4. **Does it mean the same thing in all common contexts?** I suppose. --- I came across a [comment](https://meta.stackoverflow.com/questions/316034/merge-ebay-api-into-ebay#comment302237_316034) on this [question](https://meta.stackoverflow.com/questions/316034/merge-ebay-api-into-ebay) that proposed the following: > > Check if ebay have any good api questions, retag, kill ebay with fire. > > > I suggest doing that.
2018/06/26
[ "https://meta.stackoverflow.com/questions/370156", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/3479456/" ]
* [258 questions tagged [ebay]+[api]](https://stackoverflow.com/questions/tagged/ebay+api) can have both tags removed and [ebay-api](https://stackoverflow.com/questions/tagged/ebay-api "show questions tagged 'ebay-api'") added where missing. * [~659 questions tagged [ebay] containing 'api'](https://stackoverflow.com/search?q=%5Bebay%5D+api+is%3Aquestion) can *probably all* have [ebay](https://stackoverflow.com/questions/tagged/ebay "show questions tagged 'ebay'") removed and [ebay-api](https://stackoverflow.com/questions/tagged/ebay-api "show questions tagged 'ebay-api'") added. * [~420 questions tagged [ebay] not containing 'api'](https://stackoverflow.com/search?q=%5Bebay%5D+-api+is%3Aquestion) might need to be retagged and possibly closed. [As MrTux said](https://meta.stackoverflow.com/questions/370156/should-we-auction-off-ebay/370158?noredirect=1#comment604085_370156), some of them are about CSS and JS problems for customising your own pages on the eBay site. I'm not entirely sure why the numbers are 659 and 420 when there are only 1060 questions tagged [ebay](https://stackoverflow.com/questions/tagged/ebay "show questions tagged 'ebay'").
There is already a widespread consensus that company-specific tags usually don't work very well on the site. For example, [the Apple and Microsoft tags were blacklisted awhile back](https://meta.stackoverflow.com/questions/284167/blacklist-the-microsoft-and-apple-tags) following a [burnination effort](https://meta.stackoverflow.com/questions/333833/should-we-burninate-the-apple-tag). In short, these tags rarely accurately describe on-topic questions. After all, questions about the eBay SDK and the eBay API are presumably on-topic here, but questions about the company are not. That being said, people should just use more specific tags for what they're actually asking about. Admittedly, [there has been at least one exception to this](https://meta.stackoverflow.com/questions/352209/burninate-the-cisco-tag), but by and large company-specific tags have been removed. It seems rather arbitrary to say that we should get rid of the [Microsoft] and [Apple] tags but keep [ebay] as a tag. I say we let this one go the same way as the other company-specific names and get rid of it.
9,374,008
i have a database structure like this ![enter image description here](https://i.stack.imgur.com/j1zqt.png) and am trying to print the rows count but am getting 1 only the code am using is ``` $sql="select Count(*) from uniqueviews where hour=13"; $result=mysql_query($sql); $ml=mysql_num_rows($result); echo $ml; ``` according to the query it should print 6 but its printing 1 where am doing wrong ? i think its counting the rows ? how can i print the result after rows count ?
2012/02/21
[ "https://Stackoverflow.com/questions/9374008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196338/" ]
`Count(*)` only returns one row, containing the number of rows. That's why you get only `1` as return value. If you want the actual value, you can either do this: ``` $sql="select * from uniqueviews where hour=13"; $result=mysql_query($sql); $ml=mysql_num_rows($result); echo $ml; ``` or this: ``` $sql="select COUNT(*) from uniqueviews where hour=13"; $result=mysql_query($sql); $row = mysql_fetch_array($result, MYSQL_NUM); $ml=$row[0]; echo $ml; ```
Num rows returned by your query is always 1, because there is only 1 record returned - record with count of rows from that select. Replace: ``` $sql="select Count(*) from uniqueviews where hour=13"; ``` With: ``` $sql="select id from uniqueviews where hour=13"; ``` Then use mysql\_num\_rows. But you should get value returned by count(), mysql\_num\_rows is not for operations like this.
140,312
GE seems to make two variants of their arc-fault breakers for use in their residential panels: * [THQL1115AF](https://www.geempower.com/ecatalog/ec/EN_NA/p/THQL1115AF) * [THQL1115AF2](https://www.geempower.com/ecatalog/ec/EN_NA/p/THQL1115AF2) (also similar models for 20A which are THQL1120AF / THQL1120AF2). I can't figure out what the differences between these two models are. The product info pages (linked above) seem to read almost identically, as does the packaging: [![enter image description here](https://i.stack.imgur.com/S8eFI.png)](https://i.stack.imgur.com/S8eFI.png) [![enter image description here](https://i.stack.imgur.com/R4rrQ.png)](https://i.stack.imgur.com/R4rrQ.png) I don't have any physically at hand to inspect for some obvious difference. My first impression was that the `-AF` breakers might be an older model than `-AF2`, but since they still seem to be sold that doesn't seem to be the case.
2018/06/09
[ "https://diy.stackexchange.com/questions/140312", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/41781/" ]
[This forum discussion](http://www.diychatroom.com/f18/ge-thql1115af-vs-thql1115af2-561106/) includes the following statement describing the differences between the two breaker models - *which may or may not be accurate*: > > The ... older [THQL1115AF] AFCI breakers contain an EPD device. It's the same > concept and technology as GFCI except the current imbalance threshold > is 30 mA instead of 5 mA. Newer GE AFCI breakers [THQL1115AF2] have omitted this. > > > I'm adding this as an answer here but comments are welcome to improve / clarify this answer (or post your own obvs).
af2 is gray with black handle and black test switch, it can share a neutral in a three wire. very difficult getting them on ebay because packages get mixed up. im not sure what a afp2 is
2,706,776
In solving the wave equation $$u\_{tt} - c^2 u\_{xx} = 0$$ it is commonly 'factored' $$u\_{tt} - c^2 u\_{xx} = \bigg( \frac{\partial }{\partial t} - c \frac{\partial }{\partial x} \bigg) \bigg( \frac{\partial }{\partial t} + c \frac{\partial }{\partial x} \bigg) u = 0$$ to get $$u(x,t) = f(x+ct) + g(x-ct).$$ **My question is: is this legitimate?** The partial differentiation operators are not variables, but here in 'factoring' they are treated as such. Also it does not seem that both factors can individually be set to zero to obtain the solution--either one or the other, or both might be zero.
2018/03/24
[ "https://math.stackexchange.com/questions/2706776", "https://math.stackexchange.com", "https://math.stackexchange.com/users/147776/" ]
Yes, this logic is totally legitimate. In the language of linear algebra, we have two operators $A$ and $B$ and the wave equation is $$AB \psi = 0, \quad A = \partial\_t - c \partial\_x, \quad B = \partial\_t + c \partial\_x.$$ Since $A$ and $B$ commute, they may be simultaneously diagonalized, i.e. there is a basis $\psi\_i$ where $$A \psi\_i = \lambda\_i \psi\_i, \quad B \psi\_i = \lambda'\_i \psi\_i$$ so the wave equation becomes $$AB \psi\_i = \lambda\_i \lambda'\_i \psi\_i = 0.$$ This is satisfied for $\lambda\_i = 0$ or $\lambda'\_i = 0$, so the set of solutions to the wave equation is just the union of the nullspaces of $A$ and $B$.
Let us define $$ f(u)=\frac{\partial u}{\partial t}-c\frac{\partial u}{\partial x},\ g(u)=\frac{\partial u}{\partial t}-c\frac{\partial u}{\partial x} $$ Then, wave equation can be expressed by composition of two functions. $$ f(g(u))=g(f(u))=\frac{\partial^2 u}{\partial t^2}-c^2\frac{\partial^2 u}{\partial x^2}=0 $$ This equation is vaild for all function u, so that $$ g(u)=f(u)=0 $$ I hope this helps you. '^'
5,357,254
I'm trying to profile a system with XPerf. And see that performance problems occurs when there is activity in HardFaults ! ![Hard faults graph](https://i.stack.imgur.com/GbZZo.jpg) But what I cant figure out and find in google what are these Hard Faults that xperf shows. What are they related to? What do they indicate? Is there any universal remedy for such situations? [Hard faults table](https://i.stack.imgur.com/7XH1U.jpg)
2011/03/18
[ "https://Stackoverflow.com/questions/5357254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/548894/" ]
A hard fault is when a the request process private page or file backed page is not in RAM. Hard faults occur for allocations that have been paged out, but also accesses to data file and executable images. The type of page will determine where the data data will be read from. Most hard faults are not for data from teh page file, but for data files (your word doc, for example).
Vaguely I remember a hard fault is when the requested virtual memory block is not in memory anymore and needs to be paged-in from the swapfile.
92,935
I'm connecting to the internet through a router at the moment, a Linksys WRT54G, do I need to have a software firewall set up? It seems kind of redundant if you're never going to directly connect to the modem.
2010/01/08
[ "https://superuser.com/questions/92935", "https://superuser.com", "https://superuser.com/users/20944/" ]
A software firewall on your computer can be useful because it can alert you to unexpected OUTGOING connections. A hardware firewall (because it has no user interface) pretty much has to let outgoing connections happen by default because otherwise you can't do anything with it! A software firewall can be more discerning - Internet Explorer should certainly be making connections, while a program you've never heard of trying to make outgoing SMTP (e-mail) connections is probably malware trying to send spam. This can be bad, of course, because you end up with alerts whenever something that's never connected before comes up, but it quites down after a day or so, and then you only get alerts when you install something new, or something goes wrong. So, a software firewall CAN be a good compliment to a hardware firewall, but it's mostly useful as a detection tool, and to prevent things like bot networks from spreading. Of course, if you have other PCs on the local network (behind the router), a software firewall will also be useful in preventing local attacks.
I second [Michael Kohne] Your router should by default include a firewall, if it does not then assume all ports are always open. You dont NEED a firewall on your router but it is HIGHLY suggested that EVERY computer has a firewall of its own up and running when connected to this modem. In short your don't NEED a firewall at all but any technician would not recommend you naked through the web. If you need a firewall for your computer i suggest you use Avast or AVG. (without piracy) You dont need to be directly connected to the modem to catch a virus, (this seems to be your thinking). If your connected by wire or wifi you can pass viruses.
34,284,036
Let say I have 3 Activities, `Activity A`, `Activity B` and `Activity C`. Activity A and Activity B sends an intent to activity C with let say the following code: ActivityA sending an intent: ``` Intent i = new Intent(); i.putExtra("ListName", s); i.setClass(ActivityA.this, ActivityC.class); startActivity(i); ``` ActivityB sending an Intent: ``` Intent i = new Intent(); i.putExtra("PersonName", s); i.setClass(Activityb.this, ActivityC.class); startActivity(i); ``` How do I know in ActivityC which Intent has been received, because whenever ActivityC is called it will always pass this line of code, either for ActivityA or ActivityB ``` if(getIntent() != null && getIntent().getExtras() != null) ``` and then give me `NullPointerException` on this line of code, if the intent was sent from ActivityB ``` String s = getIntent().getStringExtra("ListName"); ```
2015/12/15
[ "https://Stackoverflow.com/questions/34284036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3712490/" ]
Add an extra field for class name in Intent, ``` In ActivityA, Intent i = new Intent(); i.putExtra("ListName", s); i.putExtra("Class","A"); i.setClass(ActivityA.this, ActivityC.class); startActivity(i); ``` In ActivityB, ``` Intent i = new Intent(); i.putExtra("PersonName", s); i.putExtra("Class","B"); i.setClass(Activityb.this, ActivityC.class); startActivity(i); ``` In your ActivityC, check the tag "Class" ``` String className = getIntent().getStringExtra("Class"); if(className.equals("B")) { String s = getIntent().getStringExtra("ListName"); } ```
You need to add one extra value to the intent with the classs name of the calling activity ``` Intent intent = new Intent(); intent.setClass(A.this,MyActivity.class); intent.putExtra("ClassName","A"); A.this.startActivity(intent); Intent intent = new Intent(); intent.setClass(B.this,MyActivity.class); intent.putExtra("ClassName","B"); B.this.startActivity(intent); Intent intent = new Intent(); intent.setClass(C.this,MyActivity.class); intent.putExtra("ClassName","C"); C.this.startActivity(intent); ``` And then in MyActivity's onCreate Method ``` Intent intent = this.getIntent(); if(intent !=null) { String clsname= intent.getExtras().getString("ClassName"); if(clsname.equals("A")) { //Do Something here... } if(clsname.equals("B")) { //Do Something here... } if(clsname.equals("C")) { //Do Something here... } } } else { //do something here } ```
65,305,779
I wrote a class to share a limited number of resources (for instance network interfaces) between a larger number of threads. The resources are pooled and, if not in use, they are borrowed out to the requesting thread, which otherwise waits on a `condition_variable`. Nothing really exotic: apart for the fancy `scoped_lock` which requires c++17, it should be good old c++11. Both gcc10.2 and clang11 compile the test main fine, but while the latter produces an executable which does pretty much what expected, the former hangs without consuming CPU (deadlock?). With the help of <https://godbolt.org/> I tried older versions of gcc and also icc (passing options `-O3 -std=c++17 -pthread`), all reproducing the bad result, while even there clang confirms the proper behavior. I wonder if I made a mistake or if the code triggers some compiler misbehavior and in case how to work around that. ``` #include <iostream> #include <vector> #include <stdexcept> #include <mutex> #include <condition_variable> template <typename T> class Pool { /////////////////////////// class Borrowed { friend class Pool<T>; Pool<T>& pool; const size_t id; T * val; public: Borrowed(Pool & p, size_t i, T& v): pool(p), id(i), val(&v) {} ~Borrowed() { release(); } T& get() const { if (!val) throw std::runtime_error("Borrowed::get() this resource was collected back by the pool"); return *val; } void release() { pool.collect(*this); } }; /////////////////////////// struct Resource { T val; bool available = true; Resource(T v): val(std::move(v)) {} }; /////////////////////////// std::vector<Resource> vres; size_t hint = 0; std::condition_variable cv; std::mutex mtx; size_t available_cnt; public: Pool(std::initializer_list<T> l): available_cnt(l.size()) { vres.reserve(l.size()); for (T t: l) { vres.emplace_back(std::move(t)); } std::cout << "Pool has size " << vres.size() << std::endl; } ~Pool() { for ( auto & res: vres ) { if ( ! res.available ) { std::cerr << "WARNING Pool::~Pool resources are still in use\n"; } } } Borrowed borrow() { std::unique_lock<std::mutex> lk(mtx); cv.wait(lk, [&](){return available_cnt > 0;}); if ( vres[hint].available ) { // quick path, if hint points to an available resource std::cout << "hint good" << std::endl; vres[hint].available = false; --available_cnt; Borrowed b(*this, hint, vres[hint].val); if ( hint + 1 < vres.size() ) ++hint; return b; // <--- gcc seems to hang here } else { // full scan to find the available resource std::cout << "hint bad" << std::endl; for ( hint = 0; hint < vres.size(); ++hint ) { if ( vres[hint].available ) { vres[hint].available = false; --available_cnt; return Borrowed(*this, hint, vres[hint].val); } } } throw std::runtime_error("Pool::borrow() no resource is available - internal logic error"); } void collect(Borrowed & b) { if ( &(b.pool) != this ) throw std::runtime_error("Pool::collect() trying to collect resource owned by another pool!"); if ( b.val ) { b.val = nullptr; { std::scoped_lock<std::mutex> lk(mtx); hint = b.id; vres[hint].available = true; ++available_cnt; } cv.notify_one(); } } }; /////////////////////////////////////////////////////////////////// #include <thread> #include <chrono> int main() { Pool<std::string> pool{"hello","world"}; std::vector<std::thread> vt; for (int i = 10; i > 0; --i) { vt.emplace_back( [&pool, i]() { auto res = pool.borrow(); std::this_thread::sleep_for(std::chrono::milliseconds(i*300)); std::cout << res.get() << std::endl; } ); } for (auto & t: vt) t.join(); return 0; } ```
2020/12/15
[ "https://Stackoverflow.com/questions/65305779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2140449/" ]
This error message can be very confusing and the solution can be surprisingly primitive. In my case: Oracle stored procedure sends recordset to MS Excel via "Provider=OraOLEDB.Oracle;Data Source= ...etc" . The problem was many decimal numbers in the Oracle data column sent to Excel 2010. When I used Oracle SQL query ROUND(grosssales\_eur,2) AS grosssales\_eur, it worked fine.
The system cannot find message text for message number 0x80040e0c in the message file for OraOLEDB, such error message indicates single or multiple errors like integrity constraint including null inserting into not null columns, unique constraint. I have fixed the error by redirecting such bad/incorrect records before inserting them into the destination table. You can try if you are getting such error message. Thanks!
8,499,608
Coming from a C++ background, I religiously use the `use strict` and `use warnings` features of Perl: ``` #!/usr/bin/perl -w use strict; use warnings; $foo = 1; #Throws "$foo" requires explicit package name error foobar( 1 ); ``` The `use strict` construct is immensely helpful to catch errors when you mistype a variable name. Is there an equivalent construct to catch mistyped function names? In the above example, it would be great if there was something like `perl -c` that caught the fact that there is no **foobar** function available to call. Of course running the script throws an **Undefined subroutine** error, but I would like to catch it sooner.
2011/12/14
[ "https://Stackoverflow.com/questions/8499608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/764882/" ]
Try this: ``` perl -MO=Lint -cw /path/to/script.pl ``` This uses the [B::Lint module](https://metacpan.org/pod/B::Lint).
Perl cannot possibly know at compile time that there won't be a sub to call once the sub call is reached, so `-c` cannot possibly tell you that. [`perlcritic`](http://search.cpan.org/perldoc?perlcritic) is a tool designed to scan Perl code and *guess* at possible problems like this one. The Perl::Critic::StricterSubs `perlcritic` rule checks for this problem.
33,109,236
My college gave me a exercise: *1. Create a new document in Jasmin* *2. Use the AL-Register to to add 9 to 8.* *3. Subtract 2.* *4. Divide by 7.* My solution is: ``` mov al,9 add al,8 sub al,2 ``` But how do I divide by 7? I tried something like `div al,7` but that doesn't work.
2015/10/13
[ "https://Stackoverflow.com/questions/33109236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5300594/" ]
`div` operation divides (unsigned) the value in the AX, DX:AX, or EDX:EAX registers (dividend) by the source operand (divisor) and stores the result in the AX (AH:AL), DX:AX, or EDX:EAX registers. [source](http://x86.renejeschke.de/html/file_module_x86_id_72.html) so, to divide value in al, you need to do: ``` mov ah, 0 # clean up ah, also you can do it before, like move ax, 9 mov bl, 7 # prepare divisor div bl # al = ax / bl, ah = ax % bl ``` after that al will contain quotient and ah will contain remainder
There's a `DIV` instruction [which does division](http://x86.renejeschke.de/html/file_module_x86_id_72.html), but you'll need to put the dividend into `AX` (or one of its siblings) first.
2,713,022
I have a project that i use at two places(i dont use git server). When i copy the project at second place i have to check-in all the files(but they have not changed), git shows me for example ``` @@ -1,8 +1,8 @@ -#Sat Mar 06 19:39:27 CET 2010 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 +#Sat Mar 06 19:39:27 CET 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 ``` i did at both places the command `git config --global core.autocrlf false` but it doesnt help with this problem
2010/04/26
[ "https://Stackoverflow.com/questions/2713022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30453/" ]
Altough not answering your question - do not copy your git repo. Assuming you copy via USB memstick or something like that - create a third repo on the memstick (in 'bare' mode, preferrably), and sync your changes between the two computers via that repo.
I usually just [`git clone`](http://git-scm.com/docs/git-clone) stuff between computers - if you have network access to git (ie, via ssh). You can also use a third repo, either a public one (see [github](http://github.com/) and friends) or a private one (I really like [gitosis](http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way) to manage my git "server") - this way you also get the benefit of having a backup.
11,867
I have three goods: * beer * carp (fish) * museum ticket Is it possible to tell anything about market structure if I have annual price data of the industries? Here's the time-series plot on a single graph: [![enter image description here](https://i.stack.imgur.com/8ypWs.png)](https://i.stack.imgur.com/8ypWs.png) I would like to give advice whether a firm should entry the market or not. Is is it possible to decode price data like "the incumbent firms must have been playing a Bertrand's price competition game at the carp market"? Or do I need further details to say anything about the market structure? Is it possible to apply IO theory if I have only price data of an industry? I really need some clues, please.
2016/05/06
[ "https://economics.stackexchange.com/questions/11867", "https://economics.stackexchange.com", "https://economics.stackexchange.com/users/5017/" ]
That that we have linear supply and demand functions, pretty much the simplest case such that quantity supplied of good $i$ is: $$ Q\_{s,i,t} = \alpha\_{0,i,t} + \alpha\_{1,i,t} \cdot P\_{i,t}$$ and quantity demanded is: $$ Q\_{d,i,t} = \beta\_{0,i,t} + \beta\_{1,i,t} \cdot P\_{i,t}$$ In equilibrium $Q\_{i,t}=Q\_{d,i,t}=Q\_{s,i,t}$ so substitute and solve: $$ Q\_{i,t} = \alpha\_{0,i,t} + \alpha\_{1,i,t} \cdot P\_{i,t} = \beta\_{0,i,t} + \beta\_{1,i,t} \cdot P\_{i,t}$$ $$ P\_{i,t} = \frac{\alpha\_{0,i,t}-\beta\_{0,i,t}}{\beta\_{1,i,t} - \alpha\_{1,i,t}}$$ As you can see, the price depends on supply and demand. Unfortunately, shifts to the level or slope of either the supply or demand functions both affect the price. Therefore, in general, you can't tell anything about the supply function from the behavior of the price. And if you can't tell anything about the supply function I don't see how you'd know anything about the IO of the producer industries.
You cannot say anything about the underlying market structure if you only have aggregated data. This phenomenon is known as heterogeneity, and it can pose significant problems even for studies of the aggregated data itself. But that doesn't mean your data is useless. I'm guessing IO theory stands for Industrial Organization theory, and this is a very wide field. I am sure you can come up with something interesting and use the data that you've got. Note, though, that what you have graphed is data of price levels, but of price changes. This may be something you want to explore. For example, do you think the change in average market price is relevant for a single firm in that market? And what does this imply for entry into a market? And more generally, should the market price be the deciding factor for market entry decision?
21,951,416
I'm playing with `memcpy` in order to acquire better perception of its work and i've run into things i can't understand. I start from very simple piece of code: ``` char str [] = "0123456789abcdef"; memcpy(str + 5, str, 5); puts(str);// prints 0123401234abcdef ``` that's absolutely understandable for me. Then i move on: ``` char str [] = "0123456789abcdef"; memcpy(str + 5, str, 6); puts(str); // 01234012340bcdef ``` at first i expected the output to be `01234012345bcdef` assuming that the function will take first six characters but it started from 0 again. Ok, thought i, probably it somehow takes characters from already built new string. And putting 7 like this `memcpy(str + 5, str, 7);` confirmed this my assumption because it had produced `012340123401cdef` as output. But then things started to get more unclear. If i do this `memcpy(str + 5, str, 8);` it outputs `0123401234567def`!!!. Just like i expected from the beginning. I'm totally confused. Why it behaves this way? Ok, i can even understand printing 01 as 11th and 12th characters of the string (but this is not what i expected and i would be grateful for an explanation). But why when i determine the length as 8 it changes its behaviour??? I hope you understand what i mean. Please provide a detailed explanation. Thanks a lot in advance
2014/02/22
[ "https://Stackoverflow.com/questions/21951416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/994107/" ]
> > [The memcpy() function shall copy n bytes from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.](http://pubs.opengroup.org/onlinepubs/009695399/functions/memcpy.html) > > > `memcpy` assumes that the source and destination don't overlap. If they do, anything can happen, and exactly what happens may depend on what compiler you use, what machine you compile or run on, how big the region you're copying is, what time of day it is, etc. If you want to copy a block of memory to a destination overlapping the original position, use `memmove`.
For [**`memcpy()`**](http://en.cppreference.com/w/c/string/byte/memcpy): > > [...] If the objects overlap, the behavior is **undefined**. > > > You should use [**`memmove()`**](http://en.cppreference.com/w/c/string/byte/memmove) instead for overlapping cases. > > [...] The objects may overlap: copying takes place as if the characters were copied to a temporary character array and then the characters were copied from the array to dest. > > >
3,234,575
[![ ](https://i.stack.imgur.com/A8Ha1.jpg)](https://i.stack.imgur.com/A8Ha1.jpg) This is an exercise from Loring Tu's Introduction to Manifolds that I am stuck at. I know that a tangent bundle is trivial if it is isomorphic to the product bundle $M \times \mathbb{R}^{n}$. Here $n$ is the dimension of the (smooth of course) manifold $M$. I think I have to construct a smooth frame from the the isomorphism and vice versa; but I cannot find a way to do so...Could anyone please help me?
2019/05/21
[ "https://math.stackexchange.com/questions/3234575", "https://math.stackexchange.com", "https://math.stackexchange.com/users/164955/" ]
On $\mathbb{R}^n$ there is the obvious basis $e\_1,e\_2,\dots,e\_n$. Since $TM\cong M\times\mathbb{R}^n$ you have the $p\mapsto e\_i$ for all $p$ defines a smooth section $X\_i$ of $TM$. The $X\_1,\dots,X\_n$ defines a frame at every point. Conversely, if you have global frame field $X\_1,\dots,X\_n$, then for $v\in T\_pM$ we have $v=v^iX\_i(p)$, and you send this $v$ to $(p,(v^i))\in M\times\mathbb{R}^n$. Check it works.
If there is a smooth frame $X\_1,\dots,X\_n$, then each tangent vector $V$ is uniquely written as $$V=v^1X\_1+\dots+v^nX^n.$$ What can you say about the map $(x,V)\mapsto(x,v^1,\dots,v^n)$?
57,055,876
i have a program where i post data by radio button and send it to a php page by jquery ajax function . I want to get variable data from this page so that i can use it in my page from where i send the data . can anyone help me ``` <script type="text/javascript"> function getDesign() { var radioValue = $("input[name='metal']:checked").val(); $.ajax({ type: "POST", url: "<?php echo SITE_URL; ?>image_filter.php", data:'metal='+radioValue, success: function(data){ //$("#desc2").html(data); alert(data); } }); } </script> <?php $metal = $_POST['metal']; $finish = $_POST['finish']; echo $metal; ?> ``` i want to use the metal variable in my main page
2019/07/16
[ "https://Stackoverflow.com/questions/57055876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11785768/" ]
Use `dataType` option to accept the response in `JSON` format. ``` <script type="text/javascript"> function getDesign() { var radioValue = $("input[name='metal']:checked").val(); $.ajax({ type: "POST", dataType: "json", url: "<?php echo SITE_URL; ?>image_filter.php", data: { metal: radioValue, finish: '' }, success: function(data){ console.log(data.metal); console.log(data.finish); } }); } </script> <?php $metal = $_POST['metal']; $finish = $_POST['finish']; echo json_encode([ 'metal' => $metal, 'finish' => $finish ]); ?> ``` Refer to [this](https://api.jquery.com/jQuery.ajax/) documentation regarding dataType
You can return json in PHP this way: ``` <?php $metal = $_POST['metal']; $finish = $_POST['finish']; header('Content-Type: application/json'); $json = json_encode(array("metal"=>$metal)); echo $json; exit; ?> ```
16,202
I am trying to teach myself to create music. I know it is not a learned behavior and is rather a skill dependent process, but the basics have to be learned and that is where I am stuck. I play some piano, beginner level and has some knowledge of Indian classical music - Carnatic. What I am finding difficult is to choose which chord to use at a specific part of the melody. When I attempt to play melody with a violin and add piano chords in the background (for example) there are a plethora of options before me. It is not practical to play every one of them and decide which one to choose and I may not be able to remember how all the chords sound. Is the decision of chord taken based on some rules, or is it based on the skill of the song writer? If yes, what forms the basis for such a skill?
2014/03/18
[ "https://music.stackexchange.com/questions/16202", "https://music.stackexchange.com", "https://music.stackexchange.com/users/9269/" ]
One helpful starting point, though you may need to gather some further information to fully comprehend and apply: Within a given key, all notes of the scale can be harmonized by one of three chords while giving a functional harmony. These 3 chords would be the I, IV and V chords of the scale. We can use C Major as an example: C Major Scale: C, D, E, F, G, A, B * I = C Major: C, E, G * IV = F Major: F, A, C * V = G Major: G, B, D Each note of the scale is in at least one of the chords. This means that whatever melody you play, assuming it fits into a diatonic scale, can be harmonized by at least one of these chords. You will have to make choices when there are common tones between chords but this will significantly decrease the amount of experimenting necessary to decide which of your options is best suited. Not all notes should be harmonized as a chord tone though. A lot of times you will have a melodic phrase with a handful of notes that will be harmonized with a single chord. You then have to choose which of the chords will properly harmonize the entire phrase, not just the individual notes. This approach works but you might find the outcome boring. All of the chords will work and properly support your melody in a traditional way but there is very little textural change, which leads to a very narrow artistic/emotional expression. A next step could be to look into relative relationships, which can point out the similarities between two different chords. Though the two chords are different and have different textures, they can serve the same function. This will allow you to incorporate minor chords, which is a huge textural change from exclusively using major chords. Eventually the melodies you are trying to harmonize may have notes beyond the diatonic scale. That would make the 3 chord approach less than effective. However, if you learn and practice the 3 chord approach, then you will have a good understanding of harmonizing and will likely find it much easier to pick a chord.
If you are trying to find the chords to play a specific song (as opposed to playing/improvising a new melody), here is a much simpler approach. Given that I, IV and V chords often work for most melodies, it is far easier to apply this same idea in the following manner: play the root notes at 1, 3 or 5 note intervals BELOW each melodic note played on the main down beats. These three melodic-bass note intervals will work for a large majority of the time, particularly for simple songs. Most of all, you can use this simple scheme to identify the root notes by simply looking at and mirroring whatever note you’re playing on the right hand (with little or no mental effort). To find the chord, play the bass note and the notes at 3 and 5 note intervals ABOVE the bass note (or 1-5-10). After playing three or four simple songs (e.g. traditional xmas carols), you’ll start to get the hang of it!
136,036
I've got two points which I need to create a bounding box with, and then check to see if points are within this bounding box. The end result is a marquee selection tool. So, here is the code I started with: ``` var v1 = Camera.main.ScreenToViewportPoint( screenPosition1 ); var v2 = Camera.main.ScreenToViewportPoint( screenPosition2 ); var min = Vector3.Min( v1, v2 ); var max = Vector3.Max( v1, v2 ); //min.z = camera.nearClipPlane; //max.z = camera.farClipPlane; var bounds = new Bounds(); bounds.SetMinMax( min, max ); return bounds; ``` So then when I run it, it seems to create the correct bounds: Center (0.4,0.4,22.3), Extends (0.2,0.2,0.0) And the point seems like it should be within: (0.4,0.3,22.4) Now, my initial thoughts were that the z-index was off. However, i've tried setting that a bunch of different ways, including setting the z index of the center to 22, and the extent to 25. Nothing works. I'm checking to see if it's contained, with: ``` bool unitInsideSelection = viewportBounds.Contains(camera.WorldToViewportPoint( gameObject.transform.position ) ); ``` Where viewportBounds is the return object of the function above. Any Thoughts?
2017/01/19
[ "https://gamedev.stackexchange.com/questions/136036", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/96577/" ]
This is an X/Y problem. You want to select something on the screen, right? So do things in screen space. Get your point in the world in question `p_w`. Project it onto the screen giving `p_s` in pixels. Then check a pixel rectangle on the screen to see if it contains `p_s`. Easy right? Here's some pseudocode. ``` // Tells if a point on the screen is within a rectangle given by min and max bounds. bool contains(Point2 pointOnScreen, Point2 screenMin, Point2 screenMax) { return pointOnScreen.x <= screenMax.x && pointOnScreen.y <= screenMax.y && pointOnScreen.x >= screenMin.x && pointOnScreen.y >= screenMin.y; } // Determines if a point in the world is within the bounds on the screen. bool contains(Point3 pointInWorld, Camera camera, Point2 screenMin, Point2 screenMax) { // Project a point in the world to the screen. This gives a 3D // vector in pixels, with an added z depth. Point3 pointOnScreen = camera.projectToScreen(pointInWorld); return contains(pointOnScreen.xy, screenMin, screenMax) && pointOnScreen.z > 0; } ```
From my understanding of your problem, building a selection marque function, you would follow this approach 1. Project test points p0, p1, ... to viewport space (or some surface) that is facing the camera. 2. Get viewport space (or surface) coordinates of two mouse points. These form the bounding box for selection marquee. 3. Use point-inside-rectangle test to determine if projected points are inside bounding box. The easiest way to test if a 2D point is inside a rectangle is to test if all the 2D cross products are the same sign. If b0, b1, b2, and b3 are the coordinates of your box, and your are testing if p is inside then you check that all the following are true. cross( p - b0, b1 - b0 ) > 0 cross( p - b1, b2 - b1 ) > 0 cross( p - b2, b3 - b2 ) > 0 cross( p - b3, b4 - b3 ) > 0 I hope I understood what you are trying to do. Please correct me if I am wrong.
17,910,866
I've found that when a toplevel widget calls a messagebox dialog (like "showinfo"), the root window is showed up, over the toplevel. Is there a way to set the Toplevel window as the master of the messagebox dialog ? Here is a script to reproduce this : ``` # -*- coding:utf-8 -*- # PYTHON 3 ONLY from tkinter import * from tkinter import messagebox root = Tk() root.title('ROOT WINDOW') Label(root, text = 'Place the toplevel window over the root window\nThen, push the button and you will see that the root window is again over the toplevel').grid() topWindow = Toplevel(root) topWindow.title('TOPLEVEL WINDOW') Label(topWindow, text = 'This button will open a messagebox but will\ndo a "focus_force()" thing on the root window').grid() Button(topWindow, text = '[Push me !]', command = lambda: messagebox.showinfo('foo', 'bar!')).grid() # -- root.mainloop() ```
2013/07/28
[ "https://Stackoverflow.com/questions/17910866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2455658/" ]
This may address more current versions. ``` #TEST AREA forcommands/methods/options/attributes #standard set up header code 2 from tkinter import * from tkinter import messagebox root = Tk() root.attributes('-fullscreen', True) root.configure(background='white') scrW = root.winfo_screenwidth() scrH = root.winfo_screenheight() workwindow = str(1024) + "x" + str(768)+ "+" +str(int((scrW-1024)/2)) + "+" +str(int((scrH-768)/2)) top1 = Toplevel(root, bg="light blue") top1.geometry(workwindow) top1.title("Top 1 - Workwindow") top1.attributes("-topmost", 1) # make sure top1 is on top to start root.update() # but don't leave it locked in place top1.attributes("-topmost", 0) # in case you use lower or lift #exit button - note: uses grid b3=Button(root, text="Egress", command=root.destroy) b3.grid(row=0,column=0,ipadx=10, ipady=10, pady=5, padx=5, sticky = W+N) #____________________________ root.withdraw() mb1=messagebox.askquestion(top1, "Pay attention: \nThis is the message?") messagebox.showinfo("Say Hello", "Hello World") root.deiconify() top1.lift(aboveThis=None) #____________________________ root.mainloop() ```
add `topWindow.attributes("-topmost", 1)` after defining the Toplevel, and this should fix the problem
66,000,070
Could someone please explain what is wrong? and how to fix it. **Class 'Result' has no instance getter 'length'. Receiver: Instance of 'Result' Tried calling: length** i have fetched some data from an API successfully. when i passed this data to promotions\_page.dart i get this error i know i am doing something wrong but i can't figure it out. can i get some help please? ``` **promotions_page.dart** class _PromotionsPageState extends State<PromotionsPage> { Future<Result> _promotionsResultsData; @override void initState() { _promotionsResultsData = PromotionApi().fetchPromotions(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( body: Container( margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0), child: ListView( physics: PageScrollPhysics(), children: [ Column( children: [ Container( child: FutureBuilder( future: _promotionsResultsData, builder: (context, snapshot) { if (snapshot.hasData) { print('we have got something'); return GridView.builder( padding: EdgeInsets.zero, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( childAspectRatio: (45 / 35), crossAxisCount: 1, ), shrinkWrap: true, physics: ScrollPhysics(), itemCount: snapshot.data.length, // this line was throwing the error TO fix this it has to be this snapshot.data.result.length itemBuilder: (BuildContext context, int index) => PromotionCard( id: snapshot.data[index]['id'], title: snapshot.data[index]['title'], description: snapshot.data[index]['description'], image: snapshot.data[index]['image'], ), ); } else {} return Center( child: Text( "Loading ...", style: TextStyle( fontWeight: FontWeight.w900, fontSize: 30.0), ), ); }, ), ), ], ), ], ), ), ); } } **promotion-api.dart** import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:project_dev_1/models/promotions_model.dart'; class PromotionApi { static const key = { 'APP-X-RESTAPI-KEY': "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", }; static const API = 'http://111.111.11.1/projectrest'; Future<Result> fetchPromotions() async { final response = await http.get(API + '/promotion/all', headers: key); var results; if (response.statusCode == 200) { var responseData = response.body; var jsonMap = json.decode(responseData); results = Result.fromJson(jsonMap); } return results; } } **w_promotino_card.dart widget** import 'package:flutter/material.dart'; import 'package:buffet_dev_1/pages/promotion_details.dart'; class PromotionCard extends StatelessWidget { final String id; final String title; final String description; final String image; PromotionCard({this.id, this.title, this.description, this.image}) { print(id + title + image); } @override Widget build(BuildContext context) { return GestureDetector( onTap: () => Navigator.push( context, MaterialPageRoute( builder: (_) => PromotionDetails( promotions: null, ), ), ), child: Container( width: MediaQuery.of(context).size.width, height: 200.0, margin: EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 10.0), padding: EdgeInsets.zero, decoration: BoxDecoration( image: DecorationImage( image: null, alignment: Alignment.topCenter, ), borderRadius: BorderRadius.circular(10.0), border: Border.all( width: 1.5, color: Colors.grey[300], ), ), child: Container( width: MediaQuery.of(context).size.width, margin: EdgeInsets.zero, child: Padding( padding: EdgeInsets.fromLTRB(10, 170.0, 10.0, 10.0), child: Text( title, style: TextStyle( fontSize: 16.0, fontFamily: 'BuffetRegular', ), ), ), ), ), ); } } ```
2021/02/01
[ "https://Stackoverflow.com/questions/66000070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2524657/" ]
read your code out loud. If funcp has class unhidden-pr, add class hidden-pr and if funcp has class hidden-pr add unhidden-pr. So you really should be using an `else if` or just `else`. You also are not removing the class. ```js function bt1Func() { if ($("#funcp").hasClass('unhidden-pr')) { $("#funcp").addClass("hidden-pr").removeClass("unhidden-pr"); } else { $("#funcp").addClass("unhidden-pr").removeClass("hidden-pr"); } } ``` ```css .hidden-pr { display: none; } .unhidden-pr { display: flex; } #funcp { text-align: center; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="bt1Func()" id="bt1" class="activate style-a">Pizza</button> <div class="container-men"> <p id="funcp" class="hidden-pr">hi</p> </div> ``` IN the end you are just reinventing toggle class ```js function bt1Func(){ $("#funcp").toggleClass('hidden-pr unhidden-pr'); } ``` ```css .hidden-pr { display: none; } .unhidden-pr { display: flex; } #funcp { text-align: center; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="bt1Func()" id="bt1" class="activate style-a">Pizza</button> <div class="container-men"> <p id="funcp" class="hidden-pr">hi</p> </div> ``` but you really only need to toggle one class if you write your CSS correctly ```js function bt1Func(){ $("#funcp").toggleClass('active'); } ``` ```css .pr { display: none; } .pr.active { display: flex; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="bt1Func()" id="bt1" class="activate style-a">Pizza</button> <div class="container-men"> <p id="funcp" class="pr">hi</p> </div> ```
You can use if-else , along with add/RemoveClass ``` function bt1Func() { if ($("#funcp").hasClass('unhidden-pr')) { $("#funcp").removeClass("unhidden-pr"); $("#funcp").addClass("hidden-pr"); } else if ($("#funcp").hasClass("hidden-pr")) { $("#funcp").removeClass("hidden-pr"); $("#funcp").addClass("unhidden-pr"); } } ```
3,251
We are in a situation where we need to choose between **ballet classes** and **swimming classes** for our 4-year old girl. Problem is that we cannot afford both of them. We need to choose one. On the other hand, she loves and asks for both. She has been having swimming lessons since the age of 6 months but she hasn't taken any ballet lessons until now (but she loves dancing and listening to ballet music while in the house and she always speaks to me about it). Our baby is a bit of an introvert, so I guess having ballet classes with other children would help her express feelings and emotions among other people and feel more confident about it. On the other hand, swimming is good for physical development and in some way I will feel safer when going on vacations by the sea. I am sure that there are much more skills developed by each activity and I would happy to learn some of them so I can make a more suitable choice. What would you suggest?
2011/10/26
[ "https://parenting.stackexchange.com/questions/3251", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/1666/" ]
In reality I think it's going to be up to you to know for sure what works best for yourself and your child. There are probably alternatives to many of these, but if cost is an issue and you look for cheaper alternatives you do tend to get what you pay for. Some of the things I've heard about ballet (my cousin was a ballet-dad and his daughter teaches at a local ballet company school) is that it's not all that personally expressive after awhile. Higher prestige schools do tend to be competitive, especially if the school participates in a yearly recital, where some students try to get the "prestige parts". Parents add into this but for young kids, my cousins daughter teaches 3-5 year olds, some parents helicopter over their kids and demand attention for their child and others think of it as babysitting time. As in most things, look carefully. For a specific choice you can ask your daughter, if she could only have one what would it be? Sometimes 4 year olds know what they want, most times not, but I like to at least get my kids input and see what they want. Swimming is good full body physical development, although I have seen ballet have good results for poise, posture and other benefits as a full body, aerobic exercise. It's not as good as swimming obviously, but it's no slouch either. If you can't decide, make a list with your child and wife and go over the pros and cons of each and see what you come up with. Involving the child is also a good precursor for helping solve family issues with input, never hurts to start them young.
My youngest also likes both activities, but what decided us was that ballet was so much more expensive than swimming. She now does swimming, and is on the waiting list for Tae Kwondo (this is just because her siblings both compete in TKD so it makes sense to get them all in - less journeys) For us it comes down to cost - how many different activities can we get them into at this age without breaking the bank. Later on they can decide which ones they want to focus on, if any, but we feel we need to give them exposure to a wide range so they can gain some experience of them.
2,601,321
I've got a conjecture:- If $k$ is a natural number, then either $6k+1$ or $6k-1$ is a prime number. Is this true?
2018/01/11
[ "https://math.stackexchange.com/questions/2601321", "https://math.stackexchange.com", "https://math.stackexchange.com/users/517484/" ]
No it is not, say $120+1 = 11 ^2$ and $120-1 = 7\cdot 17$
According to elementary number theory, however, you can represent every prime number in the form $6k\pm1$ so your conjecture I would say is close to true however it does not mean that every number of the form $6k\pm1$ is a prime. This, however, holds true only for all primes $\gt3$. That is $2$ and $3$ are not written in this form.
15,242,241
I have a database in which there is a row containing the images. Now in my code, I want to get images out of the database, but somehow I am unable to do it. Following is my code – kindly help me out –: ``` <?php $qry = mysql_query("SELECT * FROM products ORDER BY products.id DESC LIMIT 0, 1", $con); if (!$qry) { die("Query Failed: ". mysql_error()); } while ($row = mysql_fetch_array($qry)) { echo "<h2>".$row['title']."</h2>"; echo "<img src=".'Image/'.$row['image']." />"; echo "<p>".substr($row['body'],0,200)."<a href=articles.php?id=".$row['id']." > Read more</a></p>"; echo "<p>".$row['price']."</p>"; } ?> ``` If I don't use PHP and just use simply the `<img>` tag, then the path must be `src="Image/passbook.jpg"` and it works fine but it's not working with PHP. I am creating an admin panel so that the client can delete or update the images as he want, so I must not use simple `<img>` tag.
2013/03/06
[ "https://Stackoverflow.com/questions/15242241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try changing, ``` echo "<img src=".'Image/'.$row['image']." />"; ``` to ``` echo "<img src='Image/".$row['image']."' />"; ```
try this ``` while($row=mysql_fetch_array($qry)) { $title = $row['title']; $src = $row['image']; $whatever = $row['body']; echo "$title <br/><img src="$src" alt="my fancy photo" height="" width=""/><br/>$watever"; } ```
56,604,354
i have the domain www.abc.com registered and forwarded via DNS-A-Record to my vServer 111.222.333.444 running CentOS 7. I have a jar-File containing a fully working Spring-Boot Application answering REST Calls on Port 8080. The Problem is, whatever I do, i can't manage to make it work. I want to do this: www.abc.com/status or www.abc.com:8080/status to get a response it works locally with localhost:8080/status but not from outside via my domain. Can you please help me?
2019/06/14
[ "https://Stackoverflow.com/questions/56604354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11649738/" ]
Thanks for this. I tried following the latest instructions. Following the instructions at <https://github.com/apple/tensorflow_macos> In the Terminal on a new Mac M1: ``` /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/apple/tensorflow_macos/master/scripts/download__install.sh)" ``` Confirm y/N? y Installing and upgrading base packages. Then it says TensorFlow and TensorFlow Addons with ML Compute for macOS 11.0 successfully installed. To begin, activate the virtual environment: ``` . "/private/var/folders/6c/56kflzvn7vzcm7vx4kpnw0d00000gn/T/tmp.TNKnwmCZ/tensorflow_macos/tensorflow_macos_venv/bin/activate" ``` Below /private/var/folders/6c/56kflzvn7vzcm7vx4kpnw0d00000gn/T, the next folder, tmp.TNKnwmCZ, does not exist and /private is owned by root, so executing anything inside it, even if it does exist, requires ‘sudo’ Trying the other way of installing Tensorflow given at <https://github.com/apple/tensorflow_macos> ``` curl -fLO https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha2/tensorflow_macos-${VERSION}.tar.gz tar xvzf tensorflow_macos-${VERSION}.tar cd tensorflow_macos ./install_venv.sh --prompt ``` It's not clear what VERSION is supposed to be, and <https://github.com/apple/tensorflow_macos/releases/download/> does not exist, so the first of the above commands fails, whatever you set VERSION to Trying another way: git clone <https://github.com/apple/tensorflow_macos> ``` cd tensorflow_macos/scripts ./download_and_install.sh ``` It tells you to run ``` . "/private/var/folders/6c/56kflzvn7vzcm7vx4kpnw0d00000gn/T/tmp.xVyjLM93/tensorflow_macos/activate" ``` and again, these folders only exist down to T, and they are all owned by root --- So I tried the method recommended above - `conda install tensorflow` I found the conda executable in /opt/homebrew/anaconda3/bin `conda install tensorflow` It failed because * tensorflow -> python[version='2.7.*|3.7.*|3.6.*|3.5.*'] Your python: python=3.8 Apple insists that their tensorflow depends on Python 3.8 <https://github.com/apple/tensorflow_macos>
Emmmm, actually is quite easy, though the tensorflow 2.0 is still in experimental stage. It is better to install the `preview version` in a virtual environment with anaconda, now the following is a Linux example: ``` $ conda create --name tensorflow_2_0 $ conda activate tensorflow_2_0 $ pip install tf-nightly-2.0-preview # tf-nightly-gpu-2.0-preview for GPU version ``` Now let's have a try: ``` $ ipython # or ipython3/python/python3(at least one of which will work) >>> import tensorflow as tf >>> print(tf.__version__) 2.0.0-dev20190129 ``` Done. ----------------2019.10.01 Update--------------- Today, the official tensorflow 2.0.0 is published. You can find how to install it [here](https://www.tensorflow.org/install). Simply, still `activate` your conda virtual environment and upgrade your `pip` first with: ``` pip install --upgrade pip ``` Then upgrade your tensorflow directly to 2.0.0: ``` pip install --upgrade tensorflow # tensorflow-gpu for gpu verison ``` Finally: ``` >>> import tensorflow as tf >>> tf.__version__ '2.0.0' ```
195,459
My patio flooring has a paint-like texture on it that is chipping off. The base is concrete. I have tried scraping, but it's incredibly tedious to get up and is taking hours of work. Is there some sort of chemical or solution I can use to help the paint/texture lift easier?
2020/06/17
[ "https://diy.stackexchange.com/questions/195459", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/118087/" ]
You say "paint-like" texture. Are you sure it's paint? If it's paint, any sort of chemical paint stripper should do the trick. There are quite a number of more "friendly" "citrus" or "orange" based paint strippers that don't have the smell and toxic concerns of paint strippers of the past. I presume a patio is outdoors, so a pressure washer may do the trick. Aim the blast at the currently chipped edges to allow the water to get underneath them and lift. You may need to shoot the water almost horizontally for the more stubborn bits. Aiming at a fairly well covered area is unlikely to get a hole started. If you've got enough pressure to do that, though, you've got a non-zero chance of actually damaging the concrete underneath, too, so turn down the pressure. It's possible that you've got an epoxy coating instead of paint. I'm not certain if the "friendly" strippers will work on that, you'll probably have to get one that's specifically for epoxy coating. Also, the pressure washer may not work so well on epoxy - it tends to grip pretty well. If you're not sure what you've got, try taking a few flakes (the bigger the better) to a local paint store to see if the can ID it for you and make a recommendation.
Your patio flooring has been painted over top of concrete. The problem is, when you do that, the surface tends to become impossibly slick - it's not so bad *bone dry*, but get a drop of oil and some condensation, the oil will spread all over and the water will multiply with it to make the the surface **shockingly slick**. This being a known vulnerability of painted concrete floors, they sell **traction modifiers** for painters to apply to the pant, to create a roughness which makes the surface safe to walk on in all conditions. Paint manufacturers sell traction modifiers compatible withtheir paint. But lots of peoplesay "I ain't paying $13 for a quart of sand", so they use a quart of sand. And it may have compatibility issues with the paint. **Regardless -- you *need* traction modifier**. If you're going to remove it, you will need to repaint, and in that paint coating, include your own traction modifier. A glassy smooth surface is simply not an option from a safety POV.
33,308,674
Error message is: > > '\_djv.Authenticator' does not contain a definition for 'authenticate' > and no extension method 'authenticate' accepting a first argument of > type '\_djv.Authenticator' could be found (are you missing a using > directive or an assembly reference?) my code is below, I have a > console app program and a class called authenticator, both pieces of > code are down there. > > > ``` namespace _Authenticator { public class Authenticator { private Dictionary < string, string > dictionary = new Dictionary < string, string > (); public Authenticator() { dictionary.Add("username1", "password1"); dictionary.Add("username2", "password2"); dictionary.Add("username3", "password3"); dictionary.Add("username4", "password4"); dictionary.Add("username5", "password5"); } public bool authenticate(string username, string password) { bool authenticated = false; if (dictionary.ContainsKey(username) && dictionary[username] == password) { authenticated = true; } else { authenticated = false; } return authenticated; } } } using _Authenticator; namespace _djv { class Authenticator { static void Main(string[] args) { Console.WriteLine("Please enter a username"); var username = Console.ReadLine(); Console.WriteLine("Please enter your password"); var password = Console.ReadLine(); var auth = new Authenticator(); if (auth.authenticate(username, password)) Console.WriteLine("Valid username/password combination"); else Console.WriteLine("Invalid username/password combination"); Console.WriteLine("Press Enter to end"); Console.ReadLine(); } } } ```
2015/10/23
[ "https://Stackoverflow.com/questions/33308674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5475424/" ]
There is a clash of class names. Your `auth` variable refers to the class inside `_djv` namespace. Specify the full name of the class to be able to use it. ``` var auth = new _Authenticator.Authenticator(); ``` Alternatively, you can create an alias for the class. I'd recommend this approach here as it makes writing code less tedious. ``` using Auth = _Authenticator.Authenticator; (...) var auth = new Auth(); ``` Actually, I think the best idea would be to rename one of the classes. Everything will get a lot cleaner and clearer.
You have two classes called `Authenticator`. If you don't specify the namespace explicitly, the class in the current namespace will be used (which is the wrong one in this case). You can solve it either by: 1. Explicitly create an instance of the right class `var auth = new _Authenticator.Authenticator()` 2. Rename your main class to something else, `Main`, for instance. I would strongly recommend option 2, to prevent further confusion.
182,447
I'm writing a code to evaluate if the *Cauchy-Riemann conditions* are satisfied for a given function. For example, for the function `f[z]=Conjugate[E^(z)]` it has to evaluate this expression below ``` Boole[E^x Cos[y] == -E^x Cos[y]] ``` But it doesn't give a zero output. It just holds unevaluated. I don't understand why
2018/09/24
[ "https://mathematica.stackexchange.com/questions/182447", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/58552/" ]
I think the answer is that in general this expression can either be true or false, depending on values of `y`. When `Cos[y]==0`the expression is true. i.e. Try `Boole[Simplify[E^x Cos[y] == -E^x Cos[y], 0 < y < \[Pi]/2]]`
Because it is `SameQ (===)` that guarantees a binary outcome of `True` and `False`, rather than `Equal (==)`. ``` Boole[E^x Cos[y] === -E^x Cos[y]] ``` > > > ``` > 0 > > ``` > >
29,373,833
I'm using v2.0 of the API via the C# dll. **But this problem also happens when I pass a Query String to the v2.0 API** via <https://rally1.rallydev.com/slm/doc/webservice/> I'm querying at the Artifact level because I need both Defects and Stories. I tried to see what kind of query string the Rally front end is using, and it passes custom fields and built-in fields to the artifact query. I am doing the same thing, but am not finding any luck getting it to work. I need to be able to filter out the released items from my query. Furthermore, I also need to sort by the custom c\_ReleaseType field as well as the built-in DragAndDropRank field. I'm guessing this is a problem because those built-in fields are not actually on the Artifact object, but why would the custom fields work? They're not on the Artifact object either. It might just be a problem I'm not able to guess at hidden in the API. If I can query these objects based on custom fields, I would expect the ability would exist to query them by built-in fields as well, even if those fields don't exist on the Ancestor object. For the sake of the example, I am leaving out a bunch of the setup code... and only leaving in the code that causes the issues. ``` var request = new Request("Artifact"); request.Order = "DragAndDropRank"; //"Could not read: could not read all instances of class com.f4tech.slm.domain.Artifact" ``` **When I comment the Order by DragAndDropRank line, it works.** --- ``` var request = new Request("Artifact"); request.Query = (new Query("c_SomeCustomField", Query.Operator.Equals, "somevalue"). And(new Query("Release", Query.Operator.Equals, "null"))); //"Could not read: could not read all instances of class com.f4tech.slm.domain.Artifact" ``` **When I take the Release part out of the query, it works.** --- ``` var request = new Request("Artifact"); request.Query = (((new Query("TypeDefOid", Query.Operator.Equals, "someID"). And(new Query("c_SomeCustomField", Query.Operator.Equals, "somevalue"))). And(new Query("DirectChildrenCount", Query.Operator.Equals, "0")))); //"Could not read: could not read all instances of class com.f4tech.slm.domain.Artifact" ``` **When I take the DirectChildrenCount part out of the query, it works.** --- Here's an example of the problem demonstrated by an API call. <https://rally1.rallydev.com/slm/webservice/v2.0/artifact?query=(c_KanbanState%20%3D%20%22Backlog%22)&order=DragAndDropRank&start=1&pagesize=20> **When I remove the Order by DragAndDropRank querystring, it works.**
2015/03/31
[ "https://Stackoverflow.com/questions/29373833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202963/" ]
In addition to the other two answers, here is a real usecase that calls for such a named inner struct: ``` struct LinkedList { //data members stored once per list struct LinkedListNode { //data members for each entry of the list struct LinkedListNode *next; } *head, *tail; }; ``` Its hard to write a more concise definition for the structure of a linked list. An unnamed inner struct won't do: The code that inserts something into the linked list will likely have to declare local variables with node pointers. And there is no point in declaring the node structure outside of the linked list structure.
Well, this is legal in C: ``` struct BatteryStatus_st { int capacity; int load; }; struct Robot_st { int pos_x; int pos_y; struct BatteryStatus_st battery; }; ``` and, as you pointed out, it is effectively identical to the code you posted (since C doesn't have the namespace/scoping rules introduced in C++). If moving the "inner" type inside doesn't change anything, but may sometimes clarify intent, it would seem odd to prohibit it.
24,164
I was over at a friend's house and her roommate complained of computer troubles. A standard Dell laptop running Vista. When plugged into the internet (no router) both IE and Firefox would refuse to work. However, a simple ``` ping www.google.com ``` worked flawlessly. Any ideas?
2009/08/18
[ "https://superuser.com/questions/24164", "https://superuser.com", "https://superuser.com/users/5657/" ]
Third step after successful pinging a machine and having already checked the proxy settings of the browser (don't forget to check how they are set at the machine where it does work) would be to actually trying to connect on the correct port with telnet. You don't need to understand the protocol, usually it's enough to see whether a connection can be established or not. From the command line, type ``` telnet www.google.com 80 ``` Where 'www.google.com' is the name of the site you want to connect to and '80' is the port - I assume you're trying to access the web interface, so that would be 80. Expect one of: ``` Connecting to www.google.com...Could not open connection to the host, on port 80: Connect failed ``` Means the connection couldn't be made by any reasons: the port might be closed, a firewall might be blocking the request, the host name might not be found, or the remote machine not be reachable. Yeah, rather unspecific, that's why you try the ping first. If the screen blanks (WinXP telnet.exe does this, Linux does not) and it seems like you can enter something (cursor moves), the connection seems to be fine. Don't worry if you don't see your cursor anymore, don't see what you type or some garbagge is printed - just close the window. If the connection doesn't work, look for personal firewalls.
@Zefiro above wrote good solution but it could be a bit better formulated. From above description (ping is working, web browsing is not working), following can be concluded: 1. DNS is working (resolving of www.google.com to 208.117.229.182 or something similar) 2. your PC is connected to internet To reconfirm above, try pinging some other addresses, like `ping superuser.com` If it works, then above two conclusions are correct. Then try @Zefiro's solution from command prompt: `telnet superuser.com 80`, and if you get black screen, that means http is working using telnet - that means your web browsers are blocked somehow, not http protocol with firewall. In that case check proxy settings (you need no proxy if direct telnet connection is working). If that doesn't help, try disabling firewall(s). If above telnet test fails, then you can be pretty sure that problem is with firewall, disable it. Of course, some virus could do something like that but it is unlikely, as viruses mostly tend to not change behaviour of your PC too much to be able to do evil things on your PC as long as possible. With current information nobody can give more detailed answer, as to detail here how to disable 10 or 20 most often used Windows firewalls would be overkill.
1,410,954
I have what I'm sure is a fairly common issue, and I don't want to re-invent the wheel. I have a search form where users can specify search criteria and type of search (AND OR Ext..). The form passes back id's that map to column names and values. Currently, I'm using server side Java to glue the strings together into a where clause. It works in some cases, but it's clunky, error prone and will not scale well. Any suggestions? Thanks, David
2009/09/11
[ "https://Stackoverflow.com/questions/1410954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150598/" ]
I'd use prepare and ? for parameters anyway, if only to avoid injection and other misconversion risks. If your search criteria are limited in size, you can statically list all possible queries to prepare. If not, you can maintain a pool of prepared queries dynamically. This is not as useful for a web app, where you probably won't get to reuse any of the queries you prepare.
The book "Expert SQL Server 2005 Development" by Adam Machanic has some excellent suggestions in chapter 7 concerning dynamic SQL. He dives into all kinds of issues including performance, maintainability, and security. I won't attempt to rewrite his chapter - suffice to say that he believes less is more when it comes to SQL. It's specific to SQL Server but I believe his general approach (huge where clause vs. if/then SQL vs. dynamic) can be applied across the board. **EDIT:** I think it's worthwhile to add... never trust input from the client, always parameterize your input before using it in SQL.
65,044,768
I'm having problems with mobx and radiobox: screen don't update when selected. I think it's a silly mistake, here are my main.dart, teste\_store.dart and pubspec.yaml. The partial file .g was generated with build\_runner and mobx\_codegen. A message appears when I run it: "No observables detected in the build method of Observer". I thought testeStore.selected was an observable and when changes triggers Observer to rebuild. **main.dart** ``` import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:teste_flutter/teste_store.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { TesteStore testeStore = TesteStore(); @override Widget build(BuildContext context) { List<String> options = ["Option 1", "Option 2", "Option 3"]; return Scaffold( appBar: AppBar( title: Text("Test Flutter"), ), body: Center( child: Observer( builder: (_){ return ListView.builder( itemCount: options.length, itemBuilder: (context, index) { return RadioListTile<int>( title: Text(options[index]), value: index, groupValue: testeStore.selected, onChanged: testeStore.changeSelected, ); }, ); } ) ), ); } } ``` **teste\_store.dart** ``` import 'package:mobx/mobx.dart'; part 'teste_store.g.dart'; class TesteStore = _TesteStore with _$TesteStore; abstract class _TesteStore with Store { @observable int selected = 0; @action void changeSelected(int newSelected) { selected = newSelected; } } ``` **pubspec.yaml** ``` name: teste_flutter description: A new Flutter application. publish_to: 'none' version: 1.0.0+1 environment: sdk: ">=2.7.0 <3.0.0" dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.0 mobx: ^1.2.1+2 flutter_mobx: ^1.1.0+2 provider: ^4.3.2+2 dev_dependencies: flutter_test: sdk: flutter build_resolvers: ^1.3.10 mobx_codegen: ^1.1.0+1 build_runner: ^1.10.2 flutter: uses-material-design: true ``` **Edit 1 and 2:** I put the solution I found here and I shouldn't. Writing down in an answer box.
2020/11/27
[ "https://Stackoverflow.com/questions/65044768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14671052/" ]
Cypress command [cy.intercept](https://on.cypress.io/intercept) has the `times` parameter that you can use to create intercepts that only are used N times. In your case it would be ```js cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json', times: 1 }); ... cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json', times: 1 }); ``` See the `cy.intercept` example in the Cypress recipes repo <https://github.com/cypress-io/cypress-example-recipes#network-stubbing-and-spying>
``` const requestsCache = {}; export function reIntercept(type: 'GET' | 'POST' | 'PUT' | 'DELETE', url, options: StaticResponse) { requestsCache[type + url] = options; cy.intercept(type, url, req => req.reply(res => { console.log(url, ' => ', requestsCache[type + url].fixture); return res.send(requestsCache[type + url]); })); } ``` Make sure to clean requestsCache when needed.
32,064,961
I had following code ``` public interface IFoo { void Execute(); } public abstract class FooBar: IFoo { public void Execute() { OnExecute(); } public abstract void OnExecute(); } ``` and following test case to test the `Execute()` method ``` [Fact] public void When_execute_method_called_Expect_executionTime_is_set() { var sutMethod = A.Fake<FooBar>(); A.CallTo(sutMethod). Where(x => x.Method.Name == "OnExecute"). Invokes(x => Thread.Sleep(100))); sutMethod.Execute(); Assert.NotEqual(0, sutMethod.Result.ExecutionTime.Ticks); } ``` `sutMethod.Execute();` call would go to `FooBar.Execute()` later I decided to make the interface into an **abstract class** ``` public abstract class IFoo { public abstract void Execute(); } public abstract class FooBar:IFoo { public override void Execute() { OnExecute(); } public abstract void OnExecute(); } ``` Now `sutMethod.Execute();` call does not invoke `FooBar.Execute()` I thought FakeItEasy would handles interface and abstract classes as equal.What am I missing? **Update** @ Blair Conrad provided the reasoning for the behaviour Is it possible to make minimal changes to the test case to get the original behaviour back? thanks
2015/08/18
[ "https://Stackoverflow.com/questions/32064961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139856/" ]
The difference is due to the overrideability of the method `Execute` on `FooBar`. FakeItEasy [can only override virtual members, abstract members, or interface members](https://fakeiteasy.readthedocs.io/en/stable/what-can-be-faked/#what-members-can-be-overridden). In your original example, when `IFooBar` is an interface and `FooBar` implements it, `Execute` is a concrete method. It's not virtual, nor is it abstract. Thus FakeItEasy can't intercept calls to it, and the original method is executed. Once you change `IFooBar` to an abstract class, you have an abstract `IFooBar.Execute`, which you `override` in `FooBar`. As such, `FooBar.Execute` is now virtual and can be intercepted by FakeItEasy. Which it does, so your implementation is not called.
Following addition help solve the issue ``` A.CallTo(() => sutMethod.Execute()).CallsBaseMethod(); ``` This calls the virtual method `Execute`of `FooBar`
430,241
Like in the title, is it possible. I was thinking about that last year but everybody told me that it's not possible due to controller issues. Today I revisited that idea after seeing awesome vids on youtube running two ssd in raid 0. I'm running 2xhdd in raid 0 and I'm wondering wether to change 2x64gb sdd raid 0 for system and 2xhdd for files.
2012/05/29
[ "https://superuser.com/questions/430241", "https://superuser.com", "https://superuser.com/users/100218/" ]
Under Cygwin, `/var/empty` must be owned **by the user running `sshd`**. (Unless you disable privilege separation!) From [a helpful email to the Cygwin mailing list in 2012 by Corinna Vinschen](https://www.cygwin.com/ml/cygwin/2012-04/msg00525.html) > > Usually sshd tests if /var/empty is owned by uid 0. On Cygwin, where > there's usually no user with uid 0, **the code has been modified to > test if /var/empty is owned by the user running sshd**. So, if you > start sshd on the command line, you have to chown /var/empty to the > current user account. Same goes for the ssh-related files under /etc. > The error message is the vanilla upstream error message. It hasn't > been changed for Cygwin to keep the Cygwin-related upstream patchset > small. > > >
In my case I had a conflict with another service. I installed Bitvise trial to try out hosting a SSH server. When I installed Cygwin OpenSSH, I need to shutdown Bitvise service to be able to start up Cygwin sshd.
1,813,649
How do you know how many developers were involved in a project using a Revision Control System? A friend of mine found this way to look up the answer in git log: ``` git log | grep Author: | sort -u | cut –delimiter=” ” -f2 | sort -u | wc -l ``` Is there a straightforward way in git? How about other Revision Control System like Subversion, Bazaar or Mercurial?
2009/11/28
[ "https://Stackoverflow.com/questions/1813649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157519/" ]
git --- The [`shortlog`](http://www.kernel.org/pub/software/scm/git/docs/git-shortlog.html) command is very useful. This summarizes the typical `git-log` output. ``` $ git shortlog -sn 119 tsaleh 113 Joe Ferris 70 Ryan McGeary 45 Tammer Saleh 45 Dan Croak 19 Matt Jankowski ... ``` Pass to `wc` to see the number of unique usernames: ``` $ git shortlog -sn | wc -l 40 ```
There is stats plugin for Bazaar to get different info about project contributors: <https://launchpad.net/bzr-stats/>
41,851,227
I have a navigation that looks like this: ``` <ul> <li><a href="index.html#open-site">Test</a></li> <li><a href="#open-site">Test</a></li> <li><a href="test.html#open-site">Test</a></li> </ul> ``` When i click on #open-site, a show up. If im on index.html and i click as an example on the second link without the "index.html" everything works fine and the div shows up. but if im on index.html and i click the first link nothing happens. The site wont reload and the click-function isn´t triggered. My jquery code looks like this ``` jQuery('a[href="#open-site"]').click(function () { jQuery('#content').animate({"left": "0px"}); }) ``` What i want is that if im on index.html and i click 'index.html#open-site' is that the page wont reload but the click function is triggered and the div shows up. If im on a other subpage like test.html and i click 'index.html#open-site' , index.html will load and the div immediately shows up.
2017/01/25
[ "https://Stackoverflow.com/questions/41851227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3660653/" ]
Another way of doing it ``` declare @sDate datetime declare @eDate datetime SET @sDate = '2017-01-01' SET @eDate = '2017-01-31' --A recursive CTE for fetching the weeks range ;WITH CTE AS ( SELECT @sDate SDATE , DATEADD(DD,6,@sDate) AS TO_DTE UNION ALL SELECT DATEADD(DD,1,TO_DTE) , CASE WHEN DATEADD(DD, 7, TO_DTE) > @eDate THEN @eDate ELSE DATEADD(DD, 7, TO_DTE) END FROM CTE WHERE DATEADD(DD, 1, TO_DTE) <= @eDate ) /* An Intermediate result of CTE to better understand +-------------------------+-------------------------+ | SDATE | TO_DTE | +-------------------------+-------------------------+ | 2017-01-01 00:00:00.000 | 2017-01-07 00:00:00.000 | | 2017-01-08 00:00:00.000 | 2017-01-14 00:00:00.000 | | 2017-01-15 00:00:00.000 | 2017-01-21 00:00:00.000 | | 2017-01-22 00:00:00.000 | 2017-01-28 00:00:00.000 | | 2017-01-29 00:00:00.000 | 2017-01-31 00:00:00.000 | +-------------------------+-------------------------+ */ SELECT CTE.SDATE ,CTE.TO_DTE ,SUM(CASE WHEN GS.[Status] = 'Open' THEN 1 ELSE 0 END) [rcOpen] ,SUM(CASE WHEN GS.[Status] = 'Closed' THEN 1 ELSE 0 END) [rcClosed] FROM GS JOIN CTE ON GS.[ModifiedDate] > CTE.SDATE AND GS.[ModifiedDate] <= CTE.TO_DTE GROUP BY CTE.SDATE ,CTE.TO_DTE ORDER BY CTE.SDATE ```
Maybe you can use `UNION ALL` instead of just `UNION`.
21,833,537
I'm reading about the new features at: <http://www.javaworld.com/article/2078836/java-se/love-and-hate-for-java-8.html> I saw the example below: **Using Anonymous Class:** ``` button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.out.println("Action Detected"); } }); ``` **With Lambda:** ``` button.addActionListener(e -> { System.out.println("Action Detected"); }); ``` What would someone do with a `MouseListener` if they wanted to implement multiple methods within the anonymous class, e.g.: ``` public void mousePressed(MouseEvent e) { saySomething("Mouse pressed; # of clicks: " + e.getClickCount(), e); } public void mouseReleased(MouseEvent e) { saySomething("Mouse released; # of clicks: " + e.getClickCount(), e); } ``` ... and so on?
2014/02/17
[ "https://Stackoverflow.com/questions/21833537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688441/" ]
You can use multi-method interfaces with lambdas by using helper interfaces. This works with such listener interfaces where the implementations of unwanted methods are trivial (i.e. we can just do what `MouseAdapter` offers too): ``` // note the absence of mouseClicked… interface ClickedListener extends MouseListener { @Override public default void mouseEntered(MouseEvent e) {} @Override public default void mouseExited(MouseEvent e) {} @Override public default void mousePressed(MouseEvent e) {} @Override public default void mouseReleased(MouseEvent e) {} } ``` You need to define such a helper interface only once. Now you can add a listener for click-events on a `Component` `c` like this: ``` c.addMouseListener((ClickedListener)(e)->System.out.println("Clicked !")); ```
I created adapter classes that allow me to write (single-line) lambda-function listeners, even if the original listener interface contains more than one method. Note the InsertOrRemoveUpdate adapter, which collapses 2 events into one. My original class also contained implementations for WindowFocusListener, TableModelListener, TableColumnModelListener and TreeModelListener, but that pushed the code over the SO limit of 30000 characters. ``` import java.awt.event.*; import java.beans.*; import javax.swing.*; import javax.swing.event.*; import org.slf4j.*; public class Adapters { private static final Logger LOGGER = LoggerFactory.getLogger(Adapters.class); @FunctionalInterface public static interface AdapterEventHandler<EVENT> { void handle(EVENT e) throws Exception; default void handleWithRuntimeException(EVENT e) { try { handle(e); } catch(Exception exception) { throw exception instanceof RuntimeException ? (RuntimeException) exception : new RuntimeException(exception); } } } public static void main(String[] args) throws Exception { // ------------------------------------------------------------------------------------------------------------------------------------- // demo usage // ------------------------------------------------------------------------------------------------------------------------------------- JToggleButton toggleButton = new JToggleButton(); JFrame frame = new JFrame(); JTextField textField = new JTextField(); JScrollBar scrollBar = new JScrollBar(); ListSelectionModel listSelectionModel = new DefaultListSelectionModel(); // ActionListener toggleButton.addActionListener(ActionPerformed.handle(e -> LOGGER.info(e.toString()))); // ItemListener toggleButton.addItemListener(ItemStateChanged.handle(e -> LOGGER.info(e.toString()))); // ChangeListener toggleButton.addChangeListener(StateChanged.handle(e -> LOGGER.info(e.toString()))); // MouseListener frame.addMouseListener(MouseClicked.handle(e -> LOGGER.info(e.toString()))); frame.addMouseListener(MousePressed.handle(e -> LOGGER.info(e.toString()))); frame.addMouseListener(MouseReleased.handle(e -> LOGGER.info(e.toString()))); frame.addMouseListener(MouseEntered.handle(e -> LOGGER.info(e.toString()))); frame.addMouseListener(MouseExited.handle(e -> LOGGER.info(e.toString()))); // MouseMotionListener frame.addMouseMotionListener(MouseDragged.handle(e -> LOGGER.info(e.toString()))); frame.addMouseMotionListener(MouseMoved.handle(e -> LOGGER.info(e.toString()))); // MouseWheelListenere frame.addMouseWheelListener(MouseWheelMoved.handle(e -> LOGGER.info(e.toString()))); // KeyListener frame.addKeyListener(KeyTyped.handle(e -> LOGGER.info(e.toString()))); frame.addKeyListener(KeyPressed.handle(e -> LOGGER.info(e.toString()))); frame.addKeyListener(KeyReleased.handle(e -> LOGGER.info(e.toString()))); // FocusListener frame.addFocusListener(FocusGained.handle(e -> LOGGER.info(e.toString()))); frame.addFocusListener(FocusLost.handle(e -> LOGGER.info(e.toString()))); // ComponentListener frame.addComponentListener(ComponentMoved.handle(e -> LOGGER.info(e.toString()))); frame.addComponentListener(ComponentResized.handle(e -> LOGGER.info(e.toString()))); frame.addComponentListener(ComponentShown.handle(e -> LOGGER.info(e.toString()))); frame.addComponentListener(ComponentHidden.handle(e -> LOGGER.info(e.toString()))); // ContainerListener frame.addContainerListener(ComponentAdded.handle(e -> LOGGER.info(e.toString()))); frame.addContainerListener(ComponentRemoved.handle(e -> LOGGER.info(e.toString()))); // HierarchyListener frame.addHierarchyListener(HierarchyChanged.handle(e -> LOGGER.info(e.toString()))); // PropertyChangeListener frame.addPropertyChangeListener(PropertyChange.handle(e -> LOGGER.info(e.toString()))); frame.addPropertyChangeListener("propertyName", PropertyChange.handle(e -> LOGGER.info(e.toString()))); // WindowListener frame.addWindowListener(WindowOpened.handle(e -> LOGGER.info(e.toString()))); frame.addWindowListener(WindowClosing.handle(e -> LOGGER.info(e.toString()))); frame.addWindowListener(WindowClosed.handle(e -> LOGGER.info(e.toString()))); frame.addWindowListener(WindowIconified.handle(e -> LOGGER.info(e.toString()))); frame.addWindowListener(WindowDeiconified.handle(e -> LOGGER.info(e.toString()))); frame.addWindowListener(WindowActivated.handle(e -> LOGGER.info(e.toString()))); frame.addWindowListener(WindowDeactivated.handle(e -> LOGGER.info(e.toString()))); // WindowStateListener frame.addWindowStateListener(WindowStateChanged.handle(e -> LOGGER.info(e.toString()))); // DocumentListener textField.getDocument().addDocumentListener(InsertUpdate.handle(e -> LOGGER.info(e.toString()))); textField.getDocument().addDocumentListener(RemoveUpdate.handle(e -> LOGGER.info(e.toString()))); textField.getDocument().addDocumentListener(InsertOrRemoveUpdate.handle(e -> LOGGER.info(e.toString()))); textField.getDocument().addDocumentListener(ChangedUpdate.handle(e -> LOGGER.info(e.toString()))); // AdjustmentListener scrollBar.addAdjustmentListener(AdjustmentValueChanged.handle(e -> LOGGER.info(e.toString()))); // ListSelectionListener listSelectionModel.addListSelectionListener(ValueChanged.handle(e -> LOGGER.info(e.toString()))); // ... // enhance as needed } // @formatter:off // --------------------------------------------------------------------------------------------------------------------------------------- // ActionListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class ActionPerformed implements ActionListener { private AdapterEventHandler<ActionEvent> m_handler = null; public static ActionPerformed handle(AdapterEventHandler<ActionEvent> handler) { ActionPerformed adapter = new ActionPerformed(); adapter.m_handler = handler; return adapter; } @Override public void actionPerformed(ActionEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // ItemListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class ItemStateChanged implements ItemListener { private AdapterEventHandler<ItemEvent> m_handler = null; public static ItemStateChanged handle(AdapterEventHandler<ItemEvent> handler) { ItemStateChanged adapter = new ItemStateChanged(); adapter.m_handler = handler; return adapter; } @Override public void itemStateChanged(ItemEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // ChangeListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class StateChanged implements ChangeListener { private AdapterEventHandler<ChangeEvent> m_handler = null; public static StateChanged handle(AdapterEventHandler<ChangeEvent> handler) { StateChanged adapter = new StateChanged(); adapter.m_handler = handler; return adapter; } @Override public void stateChanged(ChangeEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // MouseListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class MouseClicked extends MouseAdapter { private AdapterEventHandler<MouseEvent> m_handler = null; public static MouseClicked handle(AdapterEventHandler<MouseEvent> handler) { MouseClicked adapter = new MouseClicked(); adapter.m_handler = handler; return adapter; } @Override public void mouseClicked(MouseEvent e) { m_handler.handleWithRuntimeException(e); } } public static class MousePressed extends MouseAdapter { private AdapterEventHandler<MouseEvent> m_handler = null; public static MousePressed handle(AdapterEventHandler<MouseEvent> handler) { MousePressed adapter = new MousePressed(); adapter.m_handler = handler; return adapter; } @Override public void mousePressed(MouseEvent e) { m_handler.handleWithRuntimeException(e); } } public static class MouseReleased extends MouseAdapter { private AdapterEventHandler<MouseEvent> m_handler = null; public static MouseReleased handle(AdapterEventHandler<MouseEvent> handler) { MouseReleased adapter = new MouseReleased(); adapter.m_handler = handler; return adapter; } @Override public void mouseReleased(MouseEvent e) { m_handler.handleWithRuntimeException(e); } } public static class MouseEntered extends MouseAdapter { private AdapterEventHandler<MouseEvent> m_handler = null; public static MouseEntered handle(AdapterEventHandler<MouseEvent> handler) { MouseEntered adapter = new MouseEntered(); adapter.m_handler = handler; return adapter; } @Override public void mouseEntered(MouseEvent e) { m_handler.handleWithRuntimeException(e); } } public static class MouseExited extends MouseAdapter { private AdapterEventHandler<MouseEvent> m_handler = null; public static MouseExited handle(AdapterEventHandler<MouseEvent> handler) { MouseExited adapter = new MouseExited(); adapter.m_handler = handler; return adapter; } @Override public void mouseExited(MouseEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // MouseMotionListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class MouseDragged extends MouseAdapter { private AdapterEventHandler<MouseEvent> m_handler = null; public static MouseDragged handle(AdapterEventHandler<MouseEvent> handler) { MouseDragged adapter = new MouseDragged(); adapter.m_handler = handler; return adapter; } @Override public void mouseDragged(MouseEvent e) { m_handler.handleWithRuntimeException(e); } } public static class MouseMoved extends MouseAdapter { private AdapterEventHandler<MouseEvent> m_handler = null; public static MouseMoved handle(AdapterEventHandler<MouseEvent> handler) { MouseMoved adapter = new MouseMoved(); adapter.m_handler = handler; return adapter; } @Override public void mouseMoved(MouseEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // MouseWheelListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class MouseWheelMoved extends MouseAdapter { private AdapterEventHandler<MouseWheelEvent> m_handler = null; public static MouseWheelMoved handle(AdapterEventHandler<MouseWheelEvent> handler) { MouseWheelMoved adapter = new MouseWheelMoved(); adapter.m_handler = handler; return adapter; } @Override public void mouseWheelMoved(MouseWheelEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // KeyListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class KeyTyped extends KeyAdapter { private AdapterEventHandler<KeyEvent> m_handler = null; public static KeyTyped handle(AdapterEventHandler<KeyEvent> handler) { KeyTyped adapter = new KeyTyped(); adapter.m_handler = handler; return adapter; } @Override public void keyTyped(KeyEvent e) { m_handler.handleWithRuntimeException(e); } } public static class KeyPressed extends KeyAdapter { private AdapterEventHandler<KeyEvent> m_handler = null; public static KeyPressed handle(AdapterEventHandler<KeyEvent> handler) { KeyPressed adapter = new KeyPressed(); adapter.m_handler = handler; return adapter; } @Override public void keyPressed(KeyEvent e) { m_handler.handleWithRuntimeException(e); } } public static class KeyReleased extends KeyAdapter { private AdapterEventHandler<KeyEvent> m_handler = null; public static KeyReleased handle(AdapterEventHandler<KeyEvent> handler) { KeyReleased adapter = new KeyReleased(); adapter.m_handler = handler; return adapter; } @Override public void keyReleased(KeyEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // FocusListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class FocusGained extends FocusAdapter { private AdapterEventHandler<FocusEvent> m_handler = null; public static FocusGained handle(AdapterEventHandler<FocusEvent> handler) { FocusGained adapter = new FocusGained(); adapter.m_handler = handler; return adapter; } @Override public void focusGained(FocusEvent e) { m_handler.handleWithRuntimeException(e); } } public static class FocusLost extends FocusAdapter { private AdapterEventHandler<FocusEvent> m_handler = null; public static FocusLost handle(AdapterEventHandler<FocusEvent> handler) { FocusLost adapter = new FocusLost(); adapter.m_handler = handler; return adapter; } @Override public void focusLost(FocusEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // ComponentListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class ComponentMoved extends ComponentAdapter { private AdapterEventHandler<ComponentEvent> m_handler = null; public static ComponentMoved handle(AdapterEventHandler<ComponentEvent> handler) { ComponentMoved adapter = new ComponentMoved(); adapter.m_handler = handler; return adapter; } @Override public void componentMoved(ComponentEvent e) { m_handler.handleWithRuntimeException(e); } } public static class ComponentResized extends ComponentAdapter { private AdapterEventHandler<ComponentEvent> m_handler = null; public static ComponentResized handle(AdapterEventHandler<ComponentEvent> handler) { ComponentResized adapter = new ComponentResized(); adapter.m_handler = handler; return adapter; } @Override public void componentResized(ComponentEvent e) { m_handler.handleWithRuntimeException(e); } } public static class ComponentShown extends ComponentAdapter { private AdapterEventHandler<ComponentEvent> m_handler = null; public static ComponentShown handle(AdapterEventHandler<ComponentEvent> handler) { ComponentShown adapter = new ComponentShown(); adapter.m_handler = handler; return adapter; } @Override public void componentShown(ComponentEvent e) { m_handler.handleWithRuntimeException(e); } } public static class ComponentHidden extends ComponentAdapter { private AdapterEventHandler<ComponentEvent> m_handler = null; public static ComponentHidden handle(AdapterEventHandler<ComponentEvent> handler) { ComponentHidden adapter = new ComponentHidden(); adapter.m_handler = handler; return adapter; } @Override public void componentHidden(ComponentEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // ContainerListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class ComponentAdded extends ContainerAdapter { private AdapterEventHandler<ContainerEvent> m_handler = null; public static ComponentAdded handle(AdapterEventHandler<ContainerEvent> handler) { ComponentAdded adapter = new ComponentAdded(); adapter.m_handler = handler; return adapter; } @Override public void componentAdded(ContainerEvent e) { m_handler.handleWithRuntimeException(e); } } public static class ComponentRemoved extends ContainerAdapter { private AdapterEventHandler<ContainerEvent> m_handler = null; public static ComponentRemoved handle(AdapterEventHandler<ContainerEvent> handler) { ComponentRemoved adapter = new ComponentRemoved(); adapter.m_handler = handler; return adapter; } @Override public void componentRemoved(ContainerEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // HierarchyListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class HierarchyChanged implements HierarchyListener { private AdapterEventHandler<HierarchyEvent> m_handler = null; public static HierarchyChanged handle(AdapterEventHandler<HierarchyEvent> handler) { HierarchyChanged adapter = new HierarchyChanged(); adapter.m_handler = handler; return adapter; } @Override public void hierarchyChanged(HierarchyEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // PropertyChangeListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class PropertyChange implements PropertyChangeListener { private AdapterEventHandler<PropertyChangeEvent> m_handler = null; public static PropertyChange handle(AdapterEventHandler<PropertyChangeEvent> handler) { PropertyChange adapter = new PropertyChange(); adapter.m_handler = handler; return adapter; } @Override public void propertyChange(PropertyChangeEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // WindowListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class WindowOpened extends WindowAdapter { private AdapterEventHandler<WindowEvent> m_handler = null; public static WindowOpened handle(AdapterEventHandler<WindowEvent> handler) { WindowOpened adapter = new WindowOpened(); adapter.m_handler = handler; return adapter; } @Override public void windowOpened(WindowEvent e) { m_handler.handleWithRuntimeException(e); } } public static class WindowClosing extends WindowAdapter { private AdapterEventHandler<WindowEvent> m_handler = null; public static WindowClosing handle(AdapterEventHandler<WindowEvent> handler) { WindowClosing adapter = new WindowClosing(); adapter.m_handler = handler; return adapter; } @Override public void windowClosing(WindowEvent e) { m_handler.handleWithRuntimeException(e); } } public static class WindowClosed extends WindowAdapter { private AdapterEventHandler<WindowEvent> m_handler = null; public static WindowClosed handle(AdapterEventHandler<WindowEvent> handler) { WindowClosed adapter = new WindowClosed(); adapter.m_handler = handler; return adapter; } @Override public void windowClosed(WindowEvent e) { m_handler.handleWithRuntimeException(e); } } public static class WindowIconified extends WindowAdapter { private AdapterEventHandler<WindowEvent> m_handler = null; public static WindowIconified handle(AdapterEventHandler<WindowEvent> handler) { WindowIconified adapter = new WindowIconified(); adapter.m_handler = handler; return adapter; } @Override public void windowIconified(WindowEvent e) { m_handler.handleWithRuntimeException(e); } } public static class WindowDeiconified extends WindowAdapter { private AdapterEventHandler<WindowEvent> m_handler = null; public static WindowDeiconified handle(AdapterEventHandler<WindowEvent> handler) { WindowDeiconified adapter = new WindowDeiconified(); adapter.m_handler = handler; return adapter; } @Override public void windowDeiconified(WindowEvent e) { m_handler.handleWithRuntimeException(e); } } public static class WindowActivated extends WindowAdapter { private AdapterEventHandler<WindowEvent> m_handler = null; public static WindowActivated handle(AdapterEventHandler<WindowEvent> handler) { WindowActivated adapter = new WindowActivated(); adapter.m_handler = handler; return adapter; } @Override public void windowActivated(WindowEvent e) { m_handler.handleWithRuntimeException(e); } } public static class WindowDeactivated extends WindowAdapter { private AdapterEventHandler<WindowEvent> m_handler = null; public static WindowDeactivated handle(AdapterEventHandler<WindowEvent> handler) { WindowDeactivated adapter = new WindowDeactivated(); adapter.m_handler = handler; return adapter; } @Override public void windowDeactivated(WindowEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // WindowStateListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class WindowStateChanged extends WindowAdapter { private AdapterEventHandler<WindowEvent> m_handler = null; public static WindowStateChanged handle(AdapterEventHandler<WindowEvent> handler) { WindowStateChanged adapter = new WindowStateChanged(); adapter.m_handler = handler; return adapter; } @Override public void windowStateChanged(WindowEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // DocumentListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class DocumentAdapter implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { /* nothing */ } @Override public void removeUpdate(DocumentEvent e) { /* nothing */ } @Override public void changedUpdate(DocumentEvent e) { /* nothing */ } } public static class InsertUpdate extends DocumentAdapter { private AdapterEventHandler<DocumentEvent> m_handler = null; public static InsertUpdate handle(AdapterEventHandler<DocumentEvent> handler) { InsertUpdate adapter = new InsertUpdate(); adapter.m_handler = handler; return adapter; } @Override public void insertUpdate(DocumentEvent e) { m_handler.handleWithRuntimeException(e); } } public static class RemoveUpdate extends DocumentAdapter { private AdapterEventHandler<DocumentEvent> m_handler = null; public static RemoveUpdate handle(AdapterEventHandler<DocumentEvent> handler) { RemoveUpdate adapter = new RemoveUpdate(); adapter.m_handler = handler; return adapter; } @Override public void removeUpdate(DocumentEvent e) { m_handler.handleWithRuntimeException(e); } } public static class InsertOrRemoveUpdate extends DocumentAdapter { private AdapterEventHandler<DocumentEvent> m_handler = null; public static InsertOrRemoveUpdate handle(AdapterEventHandler<DocumentEvent> handler) { InsertOrRemoveUpdate adapter = new InsertOrRemoveUpdate(); adapter.m_handler = handler; return adapter; } @Override public void insertUpdate(DocumentEvent e) { m_handler.handleWithRuntimeException(e); } @Override public void removeUpdate(DocumentEvent e) { m_handler.handleWithRuntimeException(e); } } public static class ChangedUpdate extends DocumentAdapter { private AdapterEventHandler<DocumentEvent> m_handler = null; public static ChangedUpdate handle(AdapterEventHandler<DocumentEvent> handler) { ChangedUpdate adapter = new ChangedUpdate(); adapter.m_handler = handler; return adapter; } @Override public void changedUpdate(DocumentEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // AdjustmentListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class AdjustmentValueChanged implements AdjustmentListener { private AdapterEventHandler<AdjustmentEvent> m_handler = null; public static AdjustmentValueChanged handle(AdapterEventHandler<AdjustmentEvent> handler) { AdjustmentValueChanged adapter = new AdjustmentValueChanged(); adapter.m_handler = handler; return adapter; } @Override public void adjustmentValueChanged(AdjustmentEvent e) { m_handler.handleWithRuntimeException(e); } } // --------------------------------------------------------------------------------------------------------------------------------------- // ListSelectionListener // --------------------------------------------------------------------------------------------------------------------------------------- public static class ValueChanged implements ListSelectionListener { private AdapterEventHandler<ListSelectionEvent> m_handler = null; public static ValueChanged handle(AdapterEventHandler<ListSelectionEvent> handler) { ValueChanged adapter = new ValueChanged(); adapter.m_handler = handler; return adapter; } @Override public void valueChanged(ListSelectionEvent e) { m_handler.handleWithRuntimeException(e); } } // @formatter:on } ```
11,080,815
I have installed *jdk 1.7* in `C:\jdk1.7.0 directory` and *JCreator* in `C:\Program Files directory`. I set the path of correct jdk path in JCreator. But when I try to execute a java program in this I have shown the following messages: ``` --------------------Configuration: <Default>-------------------- Error : Invalid path, "C:\Program Files\Java\jdk1.7.0_04\bin\javac.exe" -g -classpath C:\Users\USER\Documents -d C:\Users\USER\Documents C:\Users\USER\Documents\A.java ``` What is the reason behind this ? Please tell me in a detail and also way to solve this problem .
2012/06/18
[ "https://Stackoverflow.com/questions/11080815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The error shows up when the following executable does not exist. ``` C:\Program Files\Java\jdk1.7.0_04\bin\javac.exe ``` Make sure that you have the `jdk` executable installed.
``` Error : Invalid path, "C:\Program Files\bin\javac.exe" -g -classpath "C:\Users\HP PAVILION\Desktop\java" -d "C:\Users\HP PAVILION\Desktop\java" "C:\Users\HP PAVILION\Desktop\java\das.java" ``` Process completed. **Error:** Could not find or load main class das Process completed.
16,743,966
Is there any difference between the two following statements. They achieve the same end, correct? Do they compile to the same Java code? Is there any performance difference between them or is it just a matter of preference/readability? ``` for (thing <- things) { doSome(thing) } things.foreach( thing => doSome(thing) ) ```
2013/05/24
[ "https://Stackoverflow.com/questions/16743966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1906491/" ]
`for` comprehensions are defined as simple syntactic translations. That's extremely important, because that allows *any* object to work with `for` comprehensions, it just has to implement the right methods. IOW: the Scala Language Specification says that the first snippet gets translated into the second. So, if there were *any* difference whatsoever between the two snippets, that would be a violation of the spec and thus a very serious compiler bug. Some people have asked for, and even implemented, special treatment of certain objects (e.g. `Range`s), but those patches were always rejected with the argument that special treatment for special types would only benefit those special types, whereas making Scala faster *in general* will benefit everybody. Note that with Macros, it's probably possible to detect, say, iteration over a `Range` purely as a simple C style `for` loop and transform that into a `while` loop or a direct tailrecursive inner function, without having to change the spec or add special casing to the compiler.
Per [scala-lang.org](http://docs.scala-lang.org/overviews/collections/iterators.html): > > As always, for-expressions can be used as an alternate syntax for expressions involving foreach, map, withFilter, and flatMap, so yet another way to print all elements returned by an iterator would be: > > > for (elem <- it) println(elem) > > > "Alternate syntax" would mean identical.
3,812,641
Having just moved from textmate to vim I'm curious. To be able to navigate my project efficiently I've installed command-t and ack.vim. These both seem like relatively new projects in the history of vim. What do people traditionally do to move around a project when they work in vim, do they just use the file explorer or is there some old school trick I don't know about?
2010/09/28
[ "https://Stackoverflow.com/questions/3812641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162337/" ]
I set `path` properly then use `find` for most things. Sometimes I just rely on the tags. The tags allow tab-completion, but find does not. in my vimrc: ``` set path=src/**;c:/work,scripts/**;c:/work ``` then ``` :find foobar.cpp ``` Will turn up foobar.cpp if it exists under a src/ folder somewhere around my current directory (recursing up to find it until c:/work is hit) and then check the scripts hierarchy. ``` :tag FooBar ``` just jumps me right to the definition of that class, as I use ctags to tag my C source code and I also wrote a script to generate tags for an in-house DSL.
What I'm using generally: 1. For opening new files: `:e` with tab-completion, or `:Ex` (open explorer in the directory of current file). 2. For jumping between files in the buffer list (`:ls`): the taglist plugin, or `:b` and its tab-completion. Note that for `:b`, tab-completion works for substrings. For example, if you have two files in buffer list: module.h and module.cpp, you can type `:b cpp` and tab will complete module.cpp. Very handy! For tab-completion I also recommend the must-have wildmenu (`:set wildmenu` `:set wildmode=full`)
12,087,510
In my splash screen, I want to check if the phone has a SDCard. The Boolean statement is beneath: ``` Boolean isSDPresent = android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED ); ``` So, if I have the SDCard in the slot on my phone, this boolean will return true, so far so good. When I go to the "Unmount SDCard" from the settings menu, and removes the SDCard, then kill the app and launching it again, the boolean will also be true.. And if I launches the `Astro File Manager` after unmounting and removing the sdcard, I can still access the `/mnt/sdcard` path, why? How can I manage to accomplish this? Thanks in advance! **EDIT** Testing with the following code: ``` File path = Environment.getExternalStorageDirectory(); String pathS = path.getPath(); ``` When the SDCard is in the slot, the `pathS` contains `mnt/sdcard`, but when I removes the SDCard the `pathS` is still `/mnt/sdcard` ...
2012/08/23
[ "https://Stackoverflow.com/questions/12087510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/835585/" ]
I've found that phones, like the Galaxy phones from Samsung, have `/mnt/sdcard` point to internal memory and not the external SD card as expected. You can know if the path returned by [Environment.getExternalStorageDirectory()](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()) is actually the external SD card with a call to [Environment.isExternalStorageRemovable()](http://developer.android.com/reference/android/os/Environment.html#isExternalStorageRemovable()) Just wanted to add from the docs for getExternalStorageDirectory() this important note: > > Note: don't be confused by the word "external" here. This directory > can better be thought as media/shared storage. It is a filesystem that > can hold a relatively large amount of data and that is shared across > all applications (does not enforce permissions). Traditionally this is > an SD card, but it may also be implemented as built-in storage in a > device that is distinct from the protected internal storage and can be > mounted as a filesystem on a computer. > > >
I modificated that if sd card exists, sets the path there if not sets it at the internal directory ``` Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if(isSDPresent) { path = theAct.getExternalCacheDir().getAbsolutePath() + "/GrammarFolder"; } else { path = theAct.getFilesDir() + "/GrammarFolder"; } ```
193,276
What happens if the load on the electrical generator exceeds its power generation? and why? To be more precise, suppose we have a standard induction generator operating at frequency $\nu=50\:\mathrm{Hz}$ and voltage $V\_0$, and rated to produce a maximum power $P\_0$, and that we connect this to a load $R<V\_0^2/P\_0$, which will try to draw more power than the generator's capacity. Obviously the details will depend on the type of generator, but, generally speaking: what will be the generator's response, and what physical processes are involved?
2015/07/09
[ "https://physics.stackexchange.com/questions/193276", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/44026/" ]
As the current drawn by the load increases the torque opposing the motion of the prime mover on its coils increase. This opposing torque is a result of the force acting on the coil since it's a current carrying conductor moving in a magnetic field. Hence its rpm reduces and so does its voltage output.
If the generator's power source exceeds the generator's capacity, and if a load is placed on the generator that also exceeds the generator's capacity, and if all safety devices are disabled; the generator would heated up to a point where the weakest link would burn out like a fuse and thus remove the electrical load.
31,745,942
I am trying to write to a text document with a specific format. Here's what I have right now. ``` String line = ""; double totalCost = 0; Node curr = summary.head.next; while(curr!=summary.tail) { line += [an assortment of strings and variables] +"\r"; totalCost += PRICELIST.get(curr.itemName)*curr.count; curr = curr.next; } write.printf("%s" + "%n", line); ``` This is what the part adding onto line actually looks like. ``` "Item's name: " + curr.itemName + ", Cost per item: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)) + ", Quantity: " + curr.count + ", Cost: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)*curr.count) + "\r"; ``` I've tried that with a newline character too. Before I had it working when the print statement was inside the loop meaning it only wrote one line at a time. I want to do it this way because I will have multiple threads writing to this file and this way any thread will not hold the lock for as long.
2015/07/31
[ "https://Stackoverflow.com/questions/31745942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3809907/" ]
First of all don't use ``` while(..){ result += newString .. } ``` inside loop. This is very inefficient especially for long texts because each time you call ``` result += newString ``` you are creating new String which needs to copy content of `result` and append to it `newStrint`. So the more text you processed so far, the more it has to copy so it becomes slower. Instead use ``` StringBuilder sb = new StringBuilder(); while(..){ sb.append(newString); } result = sb.toString. ``` which in your case should be something more like ``` sb.append("Item's name: ").append(curr.itemName) .append(", Cost per item: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName))) .append(", Quantity: ").append(curr.count ) .append(", Cost: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName) * curr.count)) .append(System.lineSeparator()); ``` Also instead of ``` write.printf("%s" + "%n", line); ``` you should use simpler version, which is ``` write.println(line); ``` which automatically add line separator based on OS.
You can also try to use `\n\r` in combination. This helped in one of my projects.
61,304,483
I want to change header image every time when I click on the link but my default image comes back every time I have 2 header file one is for `index.php` and one for all other links ``` <script> function _(x){ return document.getElementById(x); } function changeimage(x,imgsrc){ _(x).src= imgsrc; } </script> <?php include ("header.php") ?> Content here <?php include ("footer.php") ?> ``` in header file code is ``` <nav class="nav"> <img class="small-device-logo" src="../images/logo.png" /> <ul> <li><a href="../index.php">Home</a></li> <li><a onclick="changeimage('img1','../images/image2.png');" href="../1.php">4</a></li> <li><a class="cssimg" href="2.php">3</a></li> <li><a class="jsimg" href="3.php">2</a></li> <li><a class="phpimg" href="4.php">1</a></li> </ul> </nav>** <div class="banner"> <img id="img1" src="../images/banner.png" /> </div> ``` if I use the same code on plain `HTML` file it works but here in `PHP`, it's not working properly.
2020/04/19
[ "https://Stackoverflow.com/questions/61304483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8022721/" ]
Your description of the problem looks like `UNION` to me. ``` SELECT ID_Entity, [timestamp], 'Task1' AS Task, [ID_Task1] AS TaskID FROM Task1 WHERE ID_Entity = 1 UNION ALL SELECT ID_Entity, [timestamp], 'Task2' AS Task, [ID_Task2] AS TaskID FROM Task2 WHERE ID_Entity = 1 UNION ALL SELECT ID_Entity, [timestamp], 'Task3' AS Task, [ID_Task3] AS TaskID FROM Task3 WHERE ID_Entity = 1 UNION ALL ... ORDER BY [timestamp]; ```
You should write a recursive query for this
4,694,201
I am tired of writing `x > min && x < max` so i wawnt to write a simple function but I am not sure if I am doing it right... actually I am not cuz I get an error: ``` bool inBetween<T>(T x, T min, T max) where T:IComparable { return (x > min && x < max); } ``` errors: ``` Operator '>' cannot be applied to operands of type 'T' and 'T' Operator '<' cannot be applied to operands of type 'T' and 'T' ``` may I have a bad understanding of the `where` part in the function declaring note: for those who are going to tell me that I will be writing more code than before... think on readability =) any help will be appreciated **EDIT** deleted cuz it was resolved =) **ANOTHER EDIT** so after some headache I came out with this (ummm) thing following @Jay Idea of extreme readability: ``` public static class test { public static comparision Between<T>(this T a,T b) where T : IComparable { var ttt = new comparision(); ttt.init(a); ttt.result = a.CompareTo(b) > 0; return ttt; } public static bool And<T>(this comparision state, T c) where T : IComparable { return state.a.CompareTo(c) < 0 && state.result; } public class comparision { public IComparable a; public bool result; public void init<T>(T ia) where T : IComparable { a = ia; } } } ``` now you can compare anything with extreme readability =) what do you think.. I am no performance guru so any tweaks are welcome
2011/01/14
[ "https://Stackoverflow.com/questions/4694201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/171136/" ]
``` return x.CompareTo(min) > 0 && x.CompareTo(max) < 0; ``` If you're going for maximum readability, you could use an extension method on `IComparable<T>`, and create a syntax like: ``` return 5.IsBetween(10).and(20); ``` or ``` return 5.IsBetween(10.and(20)); ``` Here is an implementation for the second example: ``` public interface IRange<T> { bool ContainsInclusive(T value); bool ContainsExclusive(T value); } public class ComparableRange<T> : IRange<T> where T : IComparable<T> { T min; T max; public ComparableRange(T min, T max) { this.min = min; this.max = max; } public bool ContainsInclusive(T value) { return value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0; } public bool ContainsExclusive(T value) { return value.CompareTo(min) > 0 && value.CompareTo(max) < 0; } } public static class ComparableExtensions { public static IRange<T> and<T>(this T min, T max) where T : IComparable<T> { return new ComparableRange<T>(min, max); } public static bool IsBetween<T>(this T value, IRange<T> range) where T : IComparable<T> { return range.ContainsExclusive(value); } } ```
You can try adding a constraint that T is an IComparable, and then using CompareTo instead of < and >. But this probably won't let you send all the value types you may want to. In that case, just create the overloads you need, without generics.
6,313,217
I am currently trying to write a PHP script to connect to an Oracle database. The reason I am using PHP is because I need to connect the Oracle database with my current CRM system, written in PHP/MySQL. The PHP is hosted on 1&1 hosting, which is an external server. I read that I need to enable the extension php\_oci8.dll to connect using oci\_connect(), but I cannot do so since I do not have root privileges. Did a search, and couldn't find the DLL either. Is there any other way around this? Any help greatly appreciated, please let me know if you need more information. Thanks!
2011/06/11
[ "https://Stackoverflow.com/questions/6313217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/793528/" ]
1) 1&1 will have Linux, so you will have to use linux names for extensions. In this case name of extension will be `php_oci8.so` 2) create the `php.ini` in root directory and put the following line `extension=php_oci8.so` 3) create a simple php script with one line to test if it works: `<?php phpinfo(); ?>` Please note -- 1&1 may physically not have that file available on their server (or some additional libraries that may be required by that extension). If the problem just with absence of .so file, then you can provide your own version of it (upload it and put the correct full path to the extension in php.ini) Useful links: 1) <http://faq.1and1.com/scripting_languages_supported/php/6.html> 2) <http://faq.1and1.com/scripting_languages_supported/php/8.html>
According to your problem. first thing is that linux doesn't support .dll file. You have to install OCI8 extension module in your Apache server. Follow this link to get easy solution. <http://coffeewithcode.com/2012/09/how-to-install-oracle-libraries-for-php5-on-ubuntu-server/>
73,913,635
I have a `<TextBlock x:Key="_tb1"/>` and another `<TextBlock x:Key="_tb2"/>`. How to set visibility of \_tb1 when for exemple `IsMouseOver` of \_tb2 is true ?
2022/09/30
[ "https://Stackoverflow.com/questions/73913635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10220629/" ]
You can use [melt](https://pandas.pydata.org/docs/reference/api/pandas.melt.html) and [merge](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html) for this. If you care about the order of the output, you could add `how='left'` to the merge function. ``` import pandas as pd df1 = pd.DataFrame({'name':['fish','pork','beef','apple','shrimp','orange','shrimp','apple','pork']}) df2 = pd.DataFrame({'seafood':['fish','shrimp'], 'meat':['pork','beef'], 'fruit':['apple','orange']}) output = df1.merge(df2.melt(var_name='Category', value_name='name'), on='name') print(output) ``` Output ``` name Category 0 fish seafood 1 pork meat 2 pork meat 3 beef meat 4 apple fruit 5 apple fruit 6 shrimp seafood 7 shrimp seafood 8 orange fruit ```
Another way you can do with apply-lambda.. with if condition... But chris's way is better one... ``` df1 = pd.DataFrame({"name":["fish","pork","apple"]}) df2 = pd.DataFrame({"seafood":["fish"], "meat":["pork"], "fruit":["apple"]}) df1["category"] = df1["name"].apply(lambda x: "seafood" if x in list(df2["seafood"]) else ("meat" if x in list(df2["meat"]) else ("fruit" if x in list(df2["fruit"]) else np.nan))) ``` Output of df1; ``` name category 0 fish seafood 1 pork meat 2 apple fruit ```
46,239
My city has online billing for utilities. When you set up an account they email your user name and password to you. You can't change your password without them emailing it to you again. Isn't this insecure? Doesn't that mean my user name and password is being sent in the clear and someone can log on to my account?
2013/11/29
[ "https://security.stackexchange.com/questions/46239", "https://security.stackexchange.com", "https://security.stackexchange.com/users/34854/" ]
Yes this is correct. Security principles dictate that you should be able to set your own password.
It is my understanding that, unless they are doing something to securely deliver the email to you, that they are effectively writing your password on a postcard and sending it out for any sniffers to see. Combined with the system having your PII (name, phone, address, ect.) and financial information, I would be concerned. And while it is an assumption, I would guess that other areas of security within this application will not be much better. If you contact the general email asking for tech support help, you may be able to get to a person who will be able to contact the developer, who can then talk to.
42,670,380
I have an ACF Repeater field i'd like to output as an accordion grid, like so: ```html <div class="intro row"> <div class="item item-1">name 1</div> <div class="item item-2">name 2</div> <div class="item item-3">name 3</div> <div class="item item-4">name 4</div> </div> <div class="expanded row"> <div class="expand" id="item-1">expanded info 1</div> <div class="expand" id="item-2">expanded info 2</div> <div class="expand" id="item-3">expanded info 3</div> <div class="expand" id="item-4">expanded info 4</div> </div> <div class="intro row"> <div class="item item-5">name 5</div> <div class="item item-6">name 6</div> <div class="item item-7">name 7</div> <div class="item item-8">name 8</div> </div> <div class="expanded row"> <div class="expand" id="item-5">expanded info 5</div> <div class="expand" id="item-6">expanded info 6</div> <div class="expand" id="item-7">expanded info 7</div> <div class="expand" id="item-8">expanded info 8</div> </div> ``` I can group the initial row fine, it's just the second "expanded" row i'm having trouble with. How can I repeat and group the second row of 4 correctly in the same loop? My current PHP: ```html <?php // check if the repeater field has rows of data if( have_rows('features') ): // loop through the rows of data // add a counter $count = 0; $group = 0; while ( have_rows('features') ) : the_row(); $name = get_sub_field('feature_name'); $expandedInfo = get_sub_field('feature_info'); if ($count % 4 == 0) { $group++; ?> <div class="intro row"> <?php } ?> <div class="item item-<?php echo $count; ?>"> <?php echo $name ?> </div><!-- item--> <?php if ($count % 4 == 3) { ?> </div><!-- intro--> <?php } $count++; endwhile; else : // no rows found endif; ?> ```
2017/03/08
[ "https://Stackoverflow.com/questions/42670380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1746972/" ]
The second 'expanded' row can be done so that you store each count (item-1,item-2) in an array or just traverse through all the count when you close the intro row. ``` <?php if ($count % 4 == 3) { ?> </div><!-- intro--> <div class="expanded row"> <?php $start = $count-3; // if $count is 4, $start will be 1, and the $i will go to 4 // if $count is 8, $start will be 5 for($i=$start;$i<=$count;$i++){ echo '<div class="expand" id="item-' . $i . '"></div>'; } ?> </div> <?php } ``` This is just an example. I would suggest you to store each $count in an array and then use the count($array) to get the number of them. After you have traversed the array, reset it. **The Array Approach** ``` <?php // check if the repeater field has rows of data if( have_rows('features') ): // loop through the rows of data // add a counter $count = 0; $group = 0; // Content Array $content_array = array(); while ( have_rows('features') ) : the_row(); $name = get_sub_field('feature_name'); $expandedInfo = get_sub_field('feature_info'); // Adding the Expanded Info $content_array[ 'item-' . $count ] = $expandedInfo; if ($count % 4 == 0) { $group++; ?> <div class="intro row"> <?php } ?> <div class="item item-<?php echo $count; ?>"> <?php echo $name ?> </div><!-- item--> <?php if ($count % 4 == 3) { ?> </div><!-- intro--> <div class="expanded row"> <?php foreach( $content_array as $item_id => $expanded_info ) { echo '<div class="expanded" id="' . $item_id . '">'; echo $expanded_info; echo '</div>'; } ?> </div> <?php // Resetting the Array $content_array = array(); } $count++; endwhile; else : // no rows found endif; ?> ```
okey, lets see , using variables to store your templates may helps a lot in this context , as follow : ``` $intro = ''; $expanded = ''; while (have_rows('features')) : the_row(); if ($count % 4 == 0) { $group++; $intro .= '<div class="intro row">'; $expanded .= '<div class="expanded row">'; } $intro .= '<div class="item item-' . $count . '"></div><!-- item-->'; $expanded .= '<div class="expand" id="item-' . $count . '"></div>'; if ($count % 4 == 3) { $intro = '</div><!-- intro-->'; $expanded = '</div><!-- intro-->'; } $count++; endwhile; ``` I've made a quick example to explain to show you how using variables may fix your issue : <https://3v4l.org/cKPP4>
16,751,313
I'm using this html below: ``` <input name="t1" class="imgupload" type="file" accept="image/*" capture="camera"> <input type="submit" class="submit" value="Upload"> ``` I'm trying to figure out how to have some alert(); show when the input type="file" is empty ``` $(document).on('click', '.submit', function(e) { var check = $(".imgupload").val(); if(check == 'undefined'){ alert(); } }); ```
2013/05/25
[ "https://Stackoverflow.com/questions/16751313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2391929/" ]
Here's an example <http://jsfiddle.net/aesmA/> HTML ``` <form> <input type="file" /> <input type="submit" /> </form> ``` Javascript (jQuery) ``` $("form").on("submit", function(){ var $file = $(this).find("input[type=file]"); if (!$file.val() || $file.val() == "") { alert("File is missing"); return false; } }); ```
Try something like this. ``` $('form#fl').submit(function(e){ var a = $('input.imgupload').val(); if(a == '' || a == null){ e.preventDefault(); alert('hello'); } }); ```
6,119,667
I want to read in a CSV file whose first line is the variable names and subsequent lines are the contents of those variables. Some of the variables are numeric and some of them are text and some are even empty. ``` file = "path/file.csv" f = file(file,'r') varnames = strsplit(readLines(f,1),",")[[1]] data = strsplit(readLines(f,1),",")[[1]] ``` Now that data contains all the variables, how do I make it so that data can recognise the data type being read in just like if I did `read.csv`. I need to read the data line by line (or *n* lines at a time) as the whole dataset is too big to be read into R.
2011/05/25
[ "https://Stackoverflow.com/questions/6119667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239923/" ]
An alternate strategy that has been discussed here before to deal with very big (say, > 1e7ish cells) CSV files is: 1. Read the CSV file into an SQLite database. 2. Import the data from the database with `read.csv.sql` from the `sqldf` package. The main advantages of this are that it is usually quicker and you can easily filter the contents to only include the columns or rows that you need. See [how to import CSV into sqlite using RSqlite?](https://stackoverflow.com/questions/4332976/how-to-import-csv-into-sqlite-using-rsqlite) for more info.
Just for fun (I'm waiting on a long running computation here :-) ), a version that allows you to use any of the `read.*` kind of functions, and that holds a solution to a tiny error in \Greg's code: ``` read.clump <- function(file, lines, clump, readFunc=read.csv, skip=(lines*(clump-1))+ifelse((header) & (clump>1) & (!inherits(file, "connection")),1,0), nrows=lines,header=TRUE,...){ if(clump > 1){ colnms<-NULL if(header) { colnms<-unlist(readFunc(file, nrows=1, header=FALSE)) print(colnms) } p = readFunc(file, skip = skip, nrows = nrows, header=FALSE,...) if(! is.null(colnms)) { colnames(p) = colnms } } else { p = readFunc(file, skip = skip, nrows = nrows, header=header) } return(p) } ``` Now you can pass the relevant function as parameter readFunc, and pass extra parameters too. Meta programming is fun.
37,695,413
I am using codeigniter email, to send an email to the client who has registerd him self into the system, and after that I echo a json code that syas an email has been sent to you. this proccess is working when i am using web browser, but it is not working in android application. my code is below: ``` $config = Array( 'protocol' => 'smtp', 'smtp_host' => 'smtp.1and1.com', 'smtp_port' => 587, 'smtp_user' => $from_email, 'smtp_pass' => $this->config->item('email_password'), 'mailtype' => 'html', 'charset' => 'iso-8859-1', 'wordwrap' => TRUE ); $this->load->library('email', $config); $this->email->from($from_email, "something"); $this->email->reply_to($from_email, "something"); $this->email->to($to_email); $this->email->subject("Account Verification"); $this->email->set_mailtype("html"); $this->email->message($email_body); if($this->email->send()){ $rsp['error'] = 0; $rsp['data'] = $user; echo json_encode($rsp);}else{do some thing...} ``` but if i remove the `$this->email->send()` from code, then the echo json code works fine, but not emil sendig.
2016/06/08
[ "https://Stackoverflow.com/questions/37695413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3003376/" ]
You can use this implementation of the DateRange : ``` public class DateRange : IEquatable<DateRange> { public DateTime Start { get; set; } public DateTime End { get; set; } public DateRange Intersect(DateRange d) { var s = (d.Start > this.Start) ? d.Start : this.Start; // Later Start var e = (d.End < this.End) ? d.End : this.End; // Earlier ending if (s < e) return new DateRange() { Start = s, End = e }; else return null; } public bool Contains(DateTime d) { return d >= Start && d <= End; } public bool Equals(DateRange obj) { return Start.Equals(obj.Start) && End.Equals(obj.End); } } ``` **EDIT** ``` var d1 =new DateRange() { Start = DateTime.Now, End = DateTime.Now.AddDays(1) }; var d2 =new DateRange() { Start = DateTime.Now.AddDays(-1), End = DateTime.Now }; Console.WriteLine(d1.Intersect(d2)); ``` **EDIT2** ``` public List<DateRange> Intersect2(DateRange d) { var s = (d.Start > this.Start) ? d.Start : this.Start; // Later Start var e = (d.End < this.End) ? d.End : this.End; // Earlier ending if (s < e) return new List<DateRange>() { new DateRange() { Start = new DateTime(Math.Min(Start.Ticks, d.Start.Ticks)), End = s }, new DateRange() { Start = e, End = new DateTime(Math.Max(End.Ticks, d.End.Ticks)) } }; else return null; } ```
In your last statement you have a mistake: present r2start == r1end in all cases. Maybe: 1. r1start < r2end : r2start <**=** r1end 2. r1start <**=** r2end : r2start < r1end ? I solve this problem that condition: ``` return r1Start <= r2Start && r1End >= r2Start || r1Start <= r2Start && r1End >= r2End || r1Start >= r2Start && r1Start < r2Start && r1End <= r2End || r1Start >= r2Start && r1Start <= r2End && r1End <= r2End || r1Start <= r2Start && r1End > r2Start || r1Start >= r2Start && r1Start <= r2End && r1End > r2End; ```
2,079,002
I would like to use a fixed image as the background in a simple grouped table view in my iPhone program. Unfortunately, no matter what I do, the background is always solid white. I have followed several supposed solutions on this site and others to no avail. Here is the relavant code in the viewDidLoad method of the table view controller class (note, this code uses a solid blue color rather than an image for simplicity's sake): ``` self.tableView.opaque = NO; self.tableView.backgroundColor = [UIColor clearColor]; UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; backgroundView.backgroundColor = [UIColor blueColor]; [self.tableView.window addSubview:backgroundView]; [backgroundView release]; ``` I suspect that I am not positioning the backgroundView view in the right place. I have tried sendToBack:, bringToFront:, and others but I always just get a white background. Is it possible to do this from within the UITableViewController? Must I use Interface Builder?
2010/01/16
[ "https://Stackoverflow.com/questions/2079002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/210876/" ]
Use `UITableView`'s `subviews` property to add your background there: ``` [self.tableView addSubview:backgroundView]; [self.tableView sendSubviewToBack:backgroundView]; ``` Also, your cell/header etc. will probably need to be set to transparent for your backgroundView to be visible.
I would simply set the `backgroundColor` property of the UITableView itself. You can use UIColor's `+colorWithPatternImage:` method to convert a UIImage into a UIColor (that will repeat across the entire view, if not big enough): ``` // From within UITableViewController's -viewDidLoad: UIImage *image = [UIImage imageNamed:"yourImage.png"]; self.tableView.backgroundColor = [UIColor colorWithPatternImage:image]; ``` Simply add `yourImage.png` and `yourImage@2x.png` to your application bundle, size it appropriately, and you're all set.
41,252,238
Say I have one column called colors with 1000 cells populated with values. Some of the cells have the word `blue` in it. In another column I have unique identifiers that correspond with the colors column. For example `Blue` can have a value associated to it of 01, 02, 04, or 05. The word `blue` appears 20 times within my name column. What is one way I can find how many unique identifiers are associated with the word `blue`? In the example listed above the answer should return 4. The current method I am using to accomplish this is by using a pivot table. I filter out any value in the name column that doesnt include the word `blue`. Then I count all the unique identifiers that appear in my pivot table. ![](https://i.stack.imgur.com/W80vC.png) EDIT: Notice how `blue` appears 8 times, but it only has the values 1, 2, 3, and 4 associated with it. How can I create a function that finds out how many values are associated with blue?
2016/12/20
[ "https://Stackoverflow.com/questions/41252238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5610247/" ]
Assuming your data is located at `A1:B21` try this: Enter the following headers at `D1:F1` [![enter image description here](https://i.stack.imgur.com/m3GZO.png)](https://i.stack.imgur.com/m3GZO.png) Enter these `ArrayFormulas` *`FormulaArrays` are entered pressing* `CTRL`+`SHIFT`+`ENTER` *simultaneously, you shall see* `{` *and* `}` *around the formula if entered correctly* In `D2` - Returns an unique combined list of `Colors` & `Values`: ``` =IFERROR( INDEX($A$2:$A$21&$B$2:$B$21, MATCH(0,COUNTIF($D$1:$D1,$A$2:$A$21&$B$2:$B$21),0)*1),"") ``` [![enter image description here](https://i.stack.imgur.com/HilA3.png)](https://i.stack.imgur.com/HilA3.png) In `E2` - Returns an unique list of `Colors`: ``` =IFERROR( INDEX($A$2:$A$21, MATCH(0,COUNTIF($E$1:$E1,$A$2:$A$21),0)*1),"") ``` [![enter image description here](https://i.stack.imgur.com/9OSnt.png)](https://i.stack.imgur.com/9OSnt.png) In `F2` - Returns the count of combined `Colors` & `Values` for each `Color`: ``` =COUNTIF($D$2:$D$21,$E2&"*") ``` [![enter image description here](https://i.stack.imgur.com/W4OJK.png)](https://i.stack.imgur.com/W4OJK.png) Then copy the `ArrayFormulas` in `D2:F2` till last row of data (i.e. row 21) *Column `D` could be hidden if required...* [![enter image description here](https://i.stack.imgur.com/VuXlZ.png)](https://i.stack.imgur.com/VuXlZ.png)
In addition to the answer in the first comment, you can filter it with something like this (not tested): ``` = SUMPRODUCT( IFERROR(1 / COUNTIFS(A2:A21, "Blue", B2:B21, B2:B21), 0) ) ```
4,223,150
When CheckBox is unchecked in a ListView i need to get a popup window?
2010/11/19
[ "https://Stackoverflow.com/questions/4223150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68381/" ]
I have make a JS function and just pass id of your list like as ``` OnClientClick="return GetSelectedCheckBoxInGrid('grdCustomer');" function GetSelectedCheckBoxInGrid(obj) { var con = 'ctl00_ContentPlaceHolder1_' + obj var Parent = document.getElementById(con); var TargetChildControl = "chk"; if (Parent==null) { return false; } var items = Parent.getElementsByTagName("input"); for(var n = 0; n < items.length; ++n) if(items[n].type == 'checkbox' && items[n].id.indexOf(TargetChildControl,0) >= 0 && items[n].checked == false) alert('Hi');return false;) } ``` I think this is that
Not too sure about this, but hypothetically, you could give each checkbox a class, eg chkbox, and then have some jquery code to handle a click event: $('chkbox').click(function() { alert("here is where you put your popup code"); }); You could use window.open here
45,689,274
I want to use a smooth scroll for the anchors on the page. Therefore I use the following code: ``` <script> $(document).on('click', 'a', function(event){ event.preventDefault(); $('html, body').animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 500); }); </script> ``` The only problem is that I have a fixed header, with a height of 88px. So when clicking on the anchor, it currently scrolls to far. How can I extent my code so it will work correctly?
2017/08/15
[ "https://Stackoverflow.com/questions/45689274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343043/" ]
If you know that your fixed header will **always** have a height of 88px, you can simply add that value to the final scroll position to make space for that :) ``` $('html, body').animate({ scrollTop: $( $.attr(this, 'href') ).offset().top + 88 }, 500); ``` If the fixed header height might change, you will want to check it's outerHeight and add that to the offset. Assuming that the fixed header's jQuery object is stored as `$fixedHeader`: ``` $('html, body').animate({ scrollTop: $( $.attr(this, 'href') ).offset().top + $fixedHeader.outerHeight() }, 500); ```
CSS ONLY solution ``` html{ scroll-behavior: smooth; } [id] { scroll-margin-top: 88px } ``` This css sets the scroll behavior to smooth and sets all anchors on page to have a scroll-margin-top property, which snaps scrolling to the set position.
2,230,448
I'm using php DOM to build an XML file of data, it works fine but it all outputs on one line, like so: ``` <property><something><somethingelse>dfs</somethingelse></something></property> ``` However in all examples I've found it's outputting properly, like so: ``` <property> <something> <somethingelse> dfs </somethingelse> </something> </property> ``` Now I know I can force a new line with \n and \t for tab but I don't want to do this unless necessary. So, my question: Is my server config (for some reason) forcing it to output on the same line, or is something else happening? All examples of this in use show no new line usage and they show new lines, so I think something is wrong. I am declaring ``` header('Content-Type: text/xml'); ```
2010/02/09
[ "https://Stackoverflow.com/questions/2230448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200518/" ]
use `urlencode` :] <http://php.net/manual/en/function.urlencode.php>
Use [urlencode](http://php.net/manual/en/function.urlencode.php). That will encode all 'url breaking' characters so that they can safely passed in an URL. Also, consider passing the date in some other format, as a regular urlencoded datetime might look a bit ugly. You can use timestamps instead. For example, compare these two URLs which have equal dates: > > <http://www.domain.com/index.php?date=2010-02-09%2018:06:20> > > > <http://www.domain.com/index.php?date=1265731567> > > > Additionally, you can use a custom format, `YYYYMMDDHHIISS` is commonly used, which would result in URLs like this: > > <http://www.domain.com/index.php?date=2010020920180620> > > > The timestamp format is the one that works natively with PHP's date functions without needing any additional parsing, so I'd suggest using that instead.
16,636,007
My default terminal color is gray, and that's fine. My Bash prompt displays a bunch of colors, and this works fine: ``` PS1="${COLOR_RED}\u${COLOR_WHITE}@${COLOR_RED}${COMPUTERNAME} ${COLOR_BLUE}\w${GITPROMPT} ${COLOR_RESET}" ``` But the text I type in, at the end of the prompt, is gray. I want it to be white (ANSI code "[37m"). If I add a COLOR\_WHITE at the end of the prompt, instead of the COLOR\_RESET, then the default terminal color changes to white until it is reset. This makes a weird effect of some gray text, with some white text bleeding through at the top. How can I change the "input text" color of the Bash prompt, to something other than the terminal default color?
2013/05/19
[ "https://Stackoverflow.com/questions/16636007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/447186/" ]
Try this one. It is simpler: ``` export PS1="\e[0;32m\t \e[32;1m\u@\h:\e[0;36m\w\e[0m$ " ```
I would suggest changing your terminal emulator's settings. It appears you are using [iTerm2](https://en.wikipedia.org/wiki/ITerm2) (if you are on iTerm, I suggest looking at iTerm2), so: *Settings* → *Profiles* → *Your Profile* → *Color*. Under 'basic colors', adjust 'foreground'. For just changing the color of the input text, in Z shell (`zsh`) you could use a ``` preexec () { echo -ne "\e[0m" } ``` [Source 1](https://stackoverflow.com/questions/9268836/zsh-change-prompt-input-color) I have found a hack-ish way to try this with Bash: > > Not natively, but it can be hacked up using the DEBUG trap. [This code](http://www.twistedmatrix.com/users/glyph/preexec.bash.txt) sets up preexec and `precmd` functions similar to zsh. The command line is passed as a single argument to preexec. > > > Here is a simplified version of the code to set up a precmd function that is executed before running each command. > > > ``` preexec () { :; } preexec_invoke_exec () { [ -n "$COMP_LINE" ] && return # do nothing if completing local this_command=$(history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g"); preexec "$this_command" } ``` > > trap 'preexec\_invoke\_exec' DEBUG > > This trick is due to [Glyph Lefkowitz](http://glyf.livejournal.com/63106.html); thanks to [bcat] for locating the original author. > > > http://www.macosxhints.com/dlfiles/preexec.bash.txt > > > [Source 2](https://superuser.com/questions/175799/does-bash-have-a-hook-that-is-run-before-executing-a-command)