qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
40,493
The title really says it all, but when I use the @ character to ignore escapes in a string literal @"Like This\", the \" is interpreted as a quote character belonging to the string rather than the terminating quote.
2010/02/25
[ "https://meta.stackexchange.com/questions/40493", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/135806/" ]
That's an issue with [google-code-prettify](http://code.google.com/p/google-code-prettify/), which Stack Overflow uses, and is not something the Stack Overflow team are likely to remedy. That said, google-code-prettify is open-source - so feel free to go fix it!
Testing ``` string test1 = @"Like This\"; string test2 = "Like This\\"; ```
4,619,481
I'd like to return to college, which I had to leave due to money constraints, but now I'm preparing myself for real analysis. In my exercise book, there is a problem for showing an inequality: $\forall x,x\_1,...,x\_n \in \mathbb{R}; n \in \mathbb{N}: |x+x\_1+...+x\_n| \geq |x|-(|x\_1|+...+|x\_n|)$ I have spent yesterday's evening, trying to somehow come up with an elegant solution, using the following inequalities I know to be true: $-|x|\leq x \leq |x|$; $|x+y| \leq |x| + |y|$; $|x-y| \geq ||x|-|y||$. My latest strategy has been to show that $|x|-|x\_1|\leq |x-x\_1|$ and subsequently $|x-x\_1| \leq |x+x\_1|$, the following $x\_2, ..., x\_n$ would then be easy to prove. However, the second inequality doesn't even hold and I'm stuck.
2023/01/16
[ "https://math.stackexchange.com/questions/4619481", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1139309/" ]
**Hint**. If $y = x\_1+x\_2+\dots+x\_n$, we have $$|x+y| \geqslant |x| - |y|$$ $$|x\_1|+|x\_2|+\dots+|x\_n| \geqslant |y|$$ both by triangle inequality.
You go by induction. First prove that for $x,x\_1$ it holds $|x+x\_1| \geq |x|- |x\_1|$, and this is simply the triangle inequality (or reversed triangle inequality if you like). Then consider $x, x\_1, \dots,x\_n, x\_{n+1}$ assuming you have the thesis for $n$ numbers instead of $n+1$. Consider $x, x\_1, \dots, x\_{n}+x\_{n+1}$. Now apply the inductive hypothesis to get $$ |x+x\_1 + x\_2 + \dots x\_{n+1}| \geq |x|- (|x\_1| + \dots + |x\_n + x\_{n+1}|) \geq\\ \geq |x|- (|x\_1| + \dots + |x\_n| + |x\_{n+1}|)$$ by the triangle inequality applied to $|x\_n + x\_{n+1}|$. Good luck with your comeback!
67,176,650
I am attempting to filter rows in a BigQuery table with a repeated string field. I want to filter based on rows that have at least one value from one predefined list, but does not contain any values from a second predefined list. This is my query: ```sql SELECT em.asin, em.category FROM `my_proj.amazon_data.electronics_meta` as em, UNNEST(em.category) as sub_cat WHERE sub_cat IN ('Television & Video', 'Televisions', 'Television & Video') AND sub_cat NOT IN ( 'DVD Players & Recorders', 'Projection Screens', 'VCRs', 'Blu-ray Players', 'Blu-ray Players & Recorders' ) ``` This is the result that I get: [![query_results](https://i.stack.imgur.com/FOLwT.png)](https://i.stack.imgur.com/FOLwT.png) I would expect that the first row does not appear because it contains 'VCRs' in the `category` field. I have also tried ```sql AND LOWER(TRIM(sub_cat)) NOT IN ( 'dvd players & recorders', 'projection screens', 'vcrs', 'blu-ray players', 'blu-ray players & recorders' ) ``` and ```sql AND NOT (sub_cat IN ( 'DVD Players & Recorders', 'Projection Screens', 'VCRs', 'VCRs', 'Blu-ray Players', 'Blu-ray Players & Recorders' )) ``` But this does not change the result. **Additional Info:** This is the schema for the table: [![table schema](https://i.stack.imgur.com/9j4Fp.png)](https://i.stack.imgur.com/9j4Fp.png)
2021/04/20
[ "https://Stackoverflow.com/questions/67176650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3623641/" ]
you can filter rows with `Online`, remove it by `replace` and filter out this rows in [`Series.isin`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html) (solution not working per groups): ``` vals = df.loc[df['name'].str.contains(' Online'), 'name'].str.replace(' Online','') df = df[~df['name'].isin(vals)] print (df) name code 3 Big J Online 323 4 Big J Online 323 5 Big J Online 323 6 Code Base 476 7 Code Base 476 ``` Same solution per groups: ``` m = df['name'].str.contains('Online') f = lambda x: x['name'].isin(x['new']) df = df[~df.assign(new = df.loc[m, 'name'].str.replace(' Online','')) .groupby('code', group_keys=False) .apply(f)] print (df) name code 3 Big J Online 323 4 Big J Online 323 5 Big J Online 323 6 Code Base 476 7 Code Base 476 ```
One possible way to solve it is to create a temporary column that checks if 'online' exists in any of the values in `name` per `code`, then filter out those rows: ``` (df.assign(online = df['name'].str.contains('Online'), checker = lambda df: df.groupby('code').online.transform('sum')) .loc[lambda df: ~((df.online.eq(0)) & (df.checker.gt(0))), df.columns] ) name code 3 Big J Online 323 4 Big J Online 323 5 Big J Online 323 6 Code Base 476 7 Code Base 476 ```
5,760,419
I'm building dynamic filters which I pass by GET to a queryset filter: ``` for k, v in request.GET.iteritems(): kwargs[str(k)] = str(v) students = models.Student.objects.filter( **kwargs ) ``` and it's working for almost all the queries I'm throwing at it. However, I have a related model with a manytomany relationship, Group. So a student can be a member of many groups. I'm able to filter students who belong to a given group using the following: '`groups__in='+str(group.id)` e.g. - //example.com/students/?groups\_\_in=1 But I can't figure out how to filter for students who don't belong to any group. I've tried the following without success: ``` groups__in=None # students == [] groups__exact=None # students == [] groups__iexact=None # FAIL not that I really expected this to work groups__isnull=True # students == [] ``` The last version was what I was hoping to have actually work. I'm sure I could get this to work by modifying the top code to something like ``` if request.GET['something']: students = models.Student.objects.exclude(groups__isnull=False) else: students = models.Student.objects.filter( **kwargs ) ``` So I guess the question becomes, how can i create ``` students = models.Student.objects.exclude(groups__isnull=False) ``` using .filter()?
2011/04/22
[ "https://Stackoverflow.com/questions/5760419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335084/" ]
Maybe I don't understand the question. But I see: ``` list(MyMod.objects.exclude(foo__isnull=False) ) == list(MyMod.objects.filter(foo__isnull=True)) ```
I think `models.Student.objects.filter(groups__isnull=True)` should do what you want. As skyl pointed out, this is the same as `models.Student.objects.exclude(groups__isnull=False)`. What's the problem with this solution? Could it be in your data? As a sanity check you could try ``` from django.db.models import Count models.Student.objects.annotate(gcount=Count('groups').filter(gcount__gt=0) ``` which should yield the same results. And: If you take untrustworthy data from the client and feed them unchecked into your query, you should double check that you don't open a security hole that way (or that security is not a concern with your data).
5,760,419
I'm building dynamic filters which I pass by GET to a queryset filter: ``` for k, v in request.GET.iteritems(): kwargs[str(k)] = str(v) students = models.Student.objects.filter( **kwargs ) ``` and it's working for almost all the queries I'm throwing at it. However, I have a related model with a manytomany relationship, Group. So a student can be a member of many groups. I'm able to filter students who belong to a given group using the following: '`groups__in='+str(group.id)` e.g. - //example.com/students/?groups\_\_in=1 But I can't figure out how to filter for students who don't belong to any group. I've tried the following without success: ``` groups__in=None # students == [] groups__exact=None # students == [] groups__iexact=None # FAIL not that I really expected this to work groups__isnull=True # students == [] ``` The last version was what I was hoping to have actually work. I'm sure I could get this to work by modifying the top code to something like ``` if request.GET['something']: students = models.Student.objects.exclude(groups__isnull=False) else: students = models.Student.objects.filter( **kwargs ) ``` So I guess the question becomes, how can i create ``` students = models.Student.objects.exclude(groups__isnull=False) ``` using .filter()?
2011/04/22
[ "https://Stackoverflow.com/questions/5760419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335084/" ]
Maybe I don't understand the question. But I see: ``` list(MyMod.objects.exclude(foo__isnull=False) ) == list(MyMod.objects.filter(foo__isnull=True)) ```
``` students = models.Student.objects.filter(groups=None) ``` Here is an example from some code i have lying around: ``` # add collaborator with no organizations >>> john = Collaborator(first_name='John', last_name='Doe') >>> john.save() >>> john.organizations.all() [] # add another collaborator with no organizations >>> jane = Collaborator(first_name='Jane', last_name='Doe') >>> jane.save() >>> jane.organizations.all() [] # filter for collaborators with no collaborators >>> collabs_with_no_orgs = Collaborator.objects.filter(organizations=None) >>> collabs_with_no_orgs [<Collaborator: John Doe>, <Collaborator: Jane Doe>] # add organization to collaborator >>> jane.organizations = [Organization.objects.all()[0]] >>> jane.save() >>> jane.organizations.all() [<Organization: organization 1>] # filter for collaborators with no organizations >>> collabs_with_no_orgs = Collaborator.objects.filter(organizations=None) >>> collabs_with_no_orgs [<Collaborator: John Doe>] ```
30,697,666
I have two tables players and scores. On the player table I have two fields, name and id (PK) On the scores I have several fields [id\_score(PK),winner and looser are foreign key to the id of the player] id tournament and id match. ``` Players id_players | name ------------+----------- 41 | Antonia 42 | Roberto 43 | Luis 44 | Pedro 45 | Fernando 46 | Alejandra 47 | Rene 48 | Julieta Scores id_score | id_matches | winner | looser | id_tournament | round ----------+------------+--------+--------+---------------+------- 19 | 22 | 41 | 42 | 21 | 1 20 | 23 | 43 | 44 | 21 | 1 21 | 24 | 45 | 46 | 21 | 1 22 | 25 | 47 | 48 | 21 | 1 23 | 26 | 43 | 41 | 21 | 2 24 | 27 | 45 | 47 | 21 | 2 25 | 28 | 42 | 44 | 21 | 2 26 | 29 | 48 | 46 | 21 | 2 27 | 30 | 43 | 45 | 21 | 3 28 | 31 | 42 | 48 | 21 | 3 29 | 32 | 41 | 47 | 21 | 3 30 | 33 | 46 | 44 | 21 | 3 ``` I'm trying to get a query that contains the following: id of the player name of the player number of wins total games Currently I have these query. It kind of works. When I do the order by, it's not returning items on the correct orders ``` select p.id_players,p.name,count (s.winner) as wins, max(s.round) from players p left join scores s on s.winner = p.id_players group by id_players, s.winner order by s.winner desc; id_players | name | wins | max ------------+-----------+------+----- 41 | Antonia | 2 | 3 42 | Roberto | 2 | 3 43 | Luis | 3 | 3 45 | Fernando | 2 | 2 46 | Alejandra | 1 | 3 47 | Rene | 1 | 1 48 | Julieta | 1 | 2 44 | Pedro | 0 | ```
2015/06/07
[ "https://Stackoverflow.com/questions/30697666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1876345/" ]
The ordering works as it should. The problem is you are asking it to order by `s.winner` which refers to the ID of the winning player. If you want to order them based on most wins, you need to use `ORDER BY wins DESC`, maybe with a secondary order clause for ties. Then the rows would start with the player with maximum number of wins. A bit more logical query would be ``` SELECT s.winner, p.name, count(s.winner) as wins, max(s.round) FROM players p LEFT JOIN scores s ON s.winner = p.id_players GROUP BY s.winner ORDER BY wins DESC; ``` This way you don't need two `GROUP BY`s since `s.winner` is the same as `p.id_players` anyway.
Sometimes, it is easier to use subqueries: ``` select p.*, (select count(*) from scores s where p.id_players in (s.winner, s.loser) ) as GamesPlayed, (select count(*) from scores s where p.id_players in (s.winner) ) as GamesWon from players p order by GamesWon desc; ``` If the maximum of the round is the number of games played, then similar logic will get that.
35,171,310
This question was asked in similar ways multiple times, for example at [stackoverflow](https://stackoverflow.com/questions/33544120/memory-violation-sigsegv-and-cant-find-linker-symbol-for-virtual-table) or [forum.qt.io](http://forum.qt.io/topic/4457/can-t-find-linker-symbol-for-virtual-table/12) or [qtcentre.org](http://www.qtcentre.org/threads/50592-can-t-find-linker-symbol-for-virtual-table-for-QString-Data-value). The problem is that this error message is so vague that one solution cannot be applied to another scenario. Most of the threads are dead in the middle of the discussion though :-( So the complete error message that I get in my Qt application is: **can't find linker symbol for virtual table for "OneOfMyClasses" value found "QString::shared\_null" instead** The *OneOfMyClasses* changes depending on various things, the *QString::shared\_null* stays the same for all errors that I get. Here is a screenshot of my logging console: [![enter image description here](https://i.stack.imgur.com/0wyZQ.png)](https://i.stack.imgur.com/0wyZQ.png) 1. Why is the font color pink, so who is printing this message? 2. Why do I only see this message when I set a breakpoint and step through my code? This message does not appear when simply running the application. The point where it happens is in this function in the source line right before the current position (yellow arrow): [![enter image description here](https://i.stack.imgur.com/DYUbo.png)](https://i.stack.imgur.com/DYUbo.png) So according to the message I stepped into `m_pStateWidget->insertNavLabel(...)` and the error message is printed somewhere in the constructors inside Qt related to the QString class. So I tried the following, which moves the problem away from this code location: [![enter image description here](https://i.stack.imgur.com/kRObG.png)](https://i.stack.imgur.com/kRObG.png) When doing this I get the same error message a few code lines below with another class name in the message, note that the *QString::shared\_null* stays the same. It appears to me that I have some sort of corrupted memory. 3. How should I start investigating this issue? I'm afraid to change the code because this might hide the problem as described above. 4. What's up with the QString::shared\_null? I have found that others often see the same in their error messages. Thank you for any hint or help! :-) **Edit**: It's becoming really interesting now. I have stepped into every single function just right before the message is printed and I ended up with these error messages: [![enter image description here](https://i.stack.imgur.com/LTyW8.png)](https://i.stack.imgur.com/LTyW8.png) at this location: [![enter image description here](https://i.stack.imgur.com/MCl2N.png)](https://i.stack.imgur.com/MCl2N.png) When I navigate through the call stack in QtCreator the error is printed again and again everytime I select another function in the stack. 5. Does this mean that the debugger is printing the message and that it is simply too stupid to resolve some sort of vtable stuff for me or does this mean that I have serious trouble going on?
2016/02/03
[ "https://Stackoverflow.com/questions/35171310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2104425/" ]
You can save the index to a session variable and then read it back on post back like this: To save: ``` Session["index"] = index.ToString(); ``` Read it on page load like this: ``` Index = Session["index"]; ``` You will need the session variable to maintain state per user session. If you want to maintain state for the application then you have to use the application variable.
Hi add the following code in your page\_load event. ``` if(!Page.IsPostBack) { multiview.ActiveViewIndex=0; } ```
35,171,310
This question was asked in similar ways multiple times, for example at [stackoverflow](https://stackoverflow.com/questions/33544120/memory-violation-sigsegv-and-cant-find-linker-symbol-for-virtual-table) or [forum.qt.io](http://forum.qt.io/topic/4457/can-t-find-linker-symbol-for-virtual-table/12) or [qtcentre.org](http://www.qtcentre.org/threads/50592-can-t-find-linker-symbol-for-virtual-table-for-QString-Data-value). The problem is that this error message is so vague that one solution cannot be applied to another scenario. Most of the threads are dead in the middle of the discussion though :-( So the complete error message that I get in my Qt application is: **can't find linker symbol for virtual table for "OneOfMyClasses" value found "QString::shared\_null" instead** The *OneOfMyClasses* changes depending on various things, the *QString::shared\_null* stays the same for all errors that I get. Here is a screenshot of my logging console: [![enter image description here](https://i.stack.imgur.com/0wyZQ.png)](https://i.stack.imgur.com/0wyZQ.png) 1. Why is the font color pink, so who is printing this message? 2. Why do I only see this message when I set a breakpoint and step through my code? This message does not appear when simply running the application. The point where it happens is in this function in the source line right before the current position (yellow arrow): [![enter image description here](https://i.stack.imgur.com/DYUbo.png)](https://i.stack.imgur.com/DYUbo.png) So according to the message I stepped into `m_pStateWidget->insertNavLabel(...)` and the error message is printed somewhere in the constructors inside Qt related to the QString class. So I tried the following, which moves the problem away from this code location: [![enter image description here](https://i.stack.imgur.com/kRObG.png)](https://i.stack.imgur.com/kRObG.png) When doing this I get the same error message a few code lines below with another class name in the message, note that the *QString::shared\_null* stays the same. It appears to me that I have some sort of corrupted memory. 3. How should I start investigating this issue? I'm afraid to change the code because this might hide the problem as described above. 4. What's up with the QString::shared\_null? I have found that others often see the same in their error messages. Thank you for any hint or help! :-) **Edit**: It's becoming really interesting now. I have stepped into every single function just right before the message is printed and I ended up with these error messages: [![enter image description here](https://i.stack.imgur.com/LTyW8.png)](https://i.stack.imgur.com/LTyW8.png) at this location: [![enter image description here](https://i.stack.imgur.com/MCl2N.png)](https://i.stack.imgur.com/MCl2N.png) When I navigate through the call stack in QtCreator the error is printed again and again everytime I select another function in the stack. 5. Does this mean that the debugger is printing the message and that it is simply too stupid to resolve some sort of vtable stuff for me or does this mean that I have serious trouble going on?
2016/02/03
[ "https://Stackoverflow.com/questions/35171310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2104425/" ]
You can save the index to a session variable and then read it back on post back like this: To save: ``` Session["index"] = index.ToString(); ``` Read it on page load like this: ``` Index = Session["index"]; ``` You will need the session variable to maintain state per user session. If you want to maintain state for the application then you have to use the application variable.
i think you are setting the multiview's active index to zero on every post back like follows ``` protected void Page_Load(object sender, EventArgs e) { multiview.ActiveViewIndex=0; } ``` this will cause the multiview to set active index as 0 on every post back.To avoid this you have to set it as follows ``` protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { multiview.ActiveViewIndex=0; } } ```
43,802,591
I'm not sure if I may ask questions like this here, but I'll try. I have multiple files. The file name has the following pattern: `Lorem_Ipsum1054.html` The `Lorem_Ipsum` isn't fixed in length. Using [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) I want to change the file name as follows: `1054.html`. Means: I need to match everything except of the trailing number. This number may vary in length. Means: I need to match ever everything that is not a trailing number to replace it with [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) with nothing. Who can help me?
2017/05/05
[ "https://Stackoverflow.com/questions/43802591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use the following steps: 1. Use `File.ReadAllLines()` to get a `string[]`, where each element represents one line of the file. 2. For each line, use `string.Split()` and chop your line into individual words. Use both space and parentheses as your delimiters. This will give you an array of words. Call it `arr`. 3. Now create an object of your class and assign like this: ``` string a = arr[0]; int b = int.Parse(arr[1]); string c = string.Join(" ", arr.Skip(4).Take(arr.Length - 6)); Date d = DateTime.Parse(arr[arr.Length - 2]); Date e = DateTime.Parse(arr[arr.Length - 1]); ``` The only tricky stuff is `string c` above. Logic here is that from element no. 4 up to the 3rd last element, all of these elements form your **phrase** part, so we use linq to extract those elements and join them together to get back your phrase. This would obviously require that the phrase itself doesn't contain any parentheses itself, but that shouldn't normally be the case I assume.
You have to use Regex, you may have a look [here](https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx) as a starting point. so for example to get the first word you may use this ``` string data = "Example 2323 Second This is a Phrase 2017-01-01 2019-01-03"; string firstword = new Regex(@"\b[A-Za-z]+\b").Matches(data )[0] ```
43,802,591
I'm not sure if I may ask questions like this here, but I'll try. I have multiple files. The file name has the following pattern: `Lorem_Ipsum1054.html` The `Lorem_Ipsum` isn't fixed in length. Using [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) I want to change the file name as follows: `1054.html`. Means: I need to match everything except of the trailing number. This number may vary in length. Means: I need to match ever everything that is not a trailing number to replace it with [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) with nothing. Who can help me?
2017/05/05
[ "https://Stackoverflow.com/questions/43802591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You need a loop and `string`- and `TryParse`-methods: ``` var list = new List<ClassName>(); foreach (string line in File.ReadLines(path).Where(l => !string.IsNullOrEmpty(l))) { string[] fields = line.Trim().Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries); if (fields.Length < 5) continue; var obj = new ClassName(); list.Add(obj); obj.FirstWord = fields[0]; int number; int index = fields[1].IndexOf('('); if (index > 0 && int.TryParse(fields[1].Remove(index), out number)) obj.Number = number; int phraseStartIndex = fields[2].IndexOf('('); int phraseEndIndex = fields[2].LastIndexOf(')'); if (phraseStartIndex != phraseEndIndex) { obj.Phrase = fields[2].Substring(++phraseStartIndex, phraseEndIndex - phraseStartIndex); } DateTime dt1; if(DateTime.TryParse(fields[3], out dt1)) obj.Date1 = dt1; DateTime dt2; if (DateTime.TryParse(fields[3], out dt2)) obj.Date2 = dt2; } ```
You have to use Regex, you may have a look [here](https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx) as a starting point. so for example to get the first word you may use this ``` string data = "Example 2323 Second This is a Phrase 2017-01-01 2019-01-03"; string firstword = new Regex(@"\b[A-Za-z]+\b").Matches(data )[0] ```
43,802,591
I'm not sure if I may ask questions like this here, but I'll try. I have multiple files. The file name has the following pattern: `Lorem_Ipsum1054.html` The `Lorem_Ipsum` isn't fixed in length. Using [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) I want to change the file name as follows: `1054.html`. Means: I need to match everything except of the trailing number. This number may vary in length. Means: I need to match ever everything that is not a trailing number to replace it with [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) with nothing. Who can help me?
2017/05/05
[ "https://Stackoverflow.com/questions/43802591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The following regular expression seems to cover what I imagine you would need - at least a good start. ``` ^(?<firstWord>[\w\s]*)\s+(?<secondWord>\d+)\s+(?<thirdWord>[\w\s_-]+)\s+(?<date>\d{4}-\d{2}-\d{2})\s+(?<time>\d{2}:\d{2}:\d{2})$ ``` This captures 5 named groups * `firstWord` is any alphanumeric or whitespace * `secondWord` is any numeric entry * `thirdWord` any alphanumeric, space underscore or hyphen * `date` is any iso formatted date (date not validated) * `time` any time (time not validated) Any amount of whitespace is used as the delimiter - but you will have to `Trim()` any group captures. It makes a *hell* of a lot of assumptions about your format (dates are ISO formatted, times are hh:mm:ss). You could use it like this: ``` Regex regex = new Regex( @"(?<firstWord>[\w\s]*)\s+(?<secondWord>\d+)\s+(?<thirdWord>[\w\s_-]+)\s+(?<date>\d{4}-\d{2}-\d{2})\s+(?<time>\d{2}:\d{2}:\d{2})$", RegexOptions.IgnoreCase ); var match = regex.Match("this is the first word 123 hello_world 2017-01-01 10:00:00"); if(match.Success){ Console.WriteLine("{0}\r\n{1}\r\n{2}\r\n{3}\r\n{4}",match.Groups["firstWord"].Value.Trim(),match.Groups["secondWord"].Value,match.Groups["thirdWord"].Value,match.Groups["date"].Value,match.Groups["time"].Value); } ``` <http://rextester.com/LGM52187>
You have to use Regex, you may have a look [here](https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx) as a starting point. so for example to get the first word you may use this ``` string data = "Example 2323 Second This is a Phrase 2017-01-01 2019-01-03"; string firstword = new Regex(@"\b[A-Za-z]+\b").Matches(data )[0] ```
43,802,591
I'm not sure if I may ask questions like this here, but I'll try. I have multiple files. The file name has the following pattern: `Lorem_Ipsum1054.html` The `Lorem_Ipsum` isn't fixed in length. Using [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) I want to change the file name as follows: `1054.html`. Means: I need to match everything except of the trailing number. This number may vary in length. Means: I need to match ever everything that is not a trailing number to replace it with [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) with nothing. Who can help me?
2017/05/05
[ "https://Stackoverflow.com/questions/43802591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use the following steps: 1. Use `File.ReadAllLines()` to get a `string[]`, where each element represents one line of the file. 2. For each line, use `string.Split()` and chop your line into individual words. Use both space and parentheses as your delimiters. This will give you an array of words. Call it `arr`. 3. Now create an object of your class and assign like this: ``` string a = arr[0]; int b = int.Parse(arr[1]); string c = string.Join(" ", arr.Skip(4).Take(arr.Length - 6)); Date d = DateTime.Parse(arr[arr.Length - 2]); Date e = DateTime.Parse(arr[arr.Length - 1]); ``` The only tricky stuff is `string c` above. Logic here is that from element no. 4 up to the 3rd last element, all of these elements form your **phrase** part, so we use linq to extract those elements and join them together to get back your phrase. This would obviously require that the phrase itself doesn't contain any parentheses itself, but that shouldn't normally be the case I assume.
You need a loop and `string`- and `TryParse`-methods: ``` var list = new List<ClassName>(); foreach (string line in File.ReadLines(path).Where(l => !string.IsNullOrEmpty(l))) { string[] fields = line.Trim().Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries); if (fields.Length < 5) continue; var obj = new ClassName(); list.Add(obj); obj.FirstWord = fields[0]; int number; int index = fields[1].IndexOf('('); if (index > 0 && int.TryParse(fields[1].Remove(index), out number)) obj.Number = number; int phraseStartIndex = fields[2].IndexOf('('); int phraseEndIndex = fields[2].LastIndexOf(')'); if (phraseStartIndex != phraseEndIndex) { obj.Phrase = fields[2].Substring(++phraseStartIndex, phraseEndIndex - phraseStartIndex); } DateTime dt1; if(DateTime.TryParse(fields[3], out dt1)) obj.Date1 = dt1; DateTime dt2; if (DateTime.TryParse(fields[3], out dt2)) obj.Date2 = dt2; } ```
43,802,591
I'm not sure if I may ask questions like this here, but I'll try. I have multiple files. The file name has the following pattern: `Lorem_Ipsum1054.html` The `Lorem_Ipsum` isn't fixed in length. Using [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) I want to change the file name as follows: `1054.html`. Means: I need to match everything except of the trailing number. This number may vary in length. Means: I need to match ever everything that is not a trailing number to replace it with [Better Rename 10](https://itunes.apple.com/app/better-rename-10/id1063663640?mt=12) with nothing. Who can help me?
2017/05/05
[ "https://Stackoverflow.com/questions/43802591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use the following steps: 1. Use `File.ReadAllLines()` to get a `string[]`, where each element represents one line of the file. 2. For each line, use `string.Split()` and chop your line into individual words. Use both space and parentheses as your delimiters. This will give you an array of words. Call it `arr`. 3. Now create an object of your class and assign like this: ``` string a = arr[0]; int b = int.Parse(arr[1]); string c = string.Join(" ", arr.Skip(4).Take(arr.Length - 6)); Date d = DateTime.Parse(arr[arr.Length - 2]); Date e = DateTime.Parse(arr[arr.Length - 1]); ``` The only tricky stuff is `string c` above. Logic here is that from element no. 4 up to the 3rd last element, all of these elements form your **phrase** part, so we use linq to extract those elements and join them together to get back your phrase. This would obviously require that the phrase itself doesn't contain any parentheses itself, but that shouldn't normally be the case I assume.
The following regular expression seems to cover what I imagine you would need - at least a good start. ``` ^(?<firstWord>[\w\s]*)\s+(?<secondWord>\d+)\s+(?<thirdWord>[\w\s_-]+)\s+(?<date>\d{4}-\d{2}-\d{2})\s+(?<time>\d{2}:\d{2}:\d{2})$ ``` This captures 5 named groups * `firstWord` is any alphanumeric or whitespace * `secondWord` is any numeric entry * `thirdWord` any alphanumeric, space underscore or hyphen * `date` is any iso formatted date (date not validated) * `time` any time (time not validated) Any amount of whitespace is used as the delimiter - but you will have to `Trim()` any group captures. It makes a *hell* of a lot of assumptions about your format (dates are ISO formatted, times are hh:mm:ss). You could use it like this: ``` Regex regex = new Regex( @"(?<firstWord>[\w\s]*)\s+(?<secondWord>\d+)\s+(?<thirdWord>[\w\s_-]+)\s+(?<date>\d{4}-\d{2}-\d{2})\s+(?<time>\d{2}:\d{2}:\d{2})$", RegexOptions.IgnoreCase ); var match = regex.Match("this is the first word 123 hello_world 2017-01-01 10:00:00"); if(match.Success){ Console.WriteLine("{0}\r\n{1}\r\n{2}\r\n{3}\r\n{4}",match.Groups["firstWord"].Value.Trim(),match.Groups["secondWord"].Value,match.Groups["thirdWord"].Value,match.Groups["date"].Value,match.Groups["time"].Value); } ``` <http://rextester.com/LGM52187>
9,516
It seems to be common on the web to provide users with some visual element on the page to either print or bookmark a page. This is all well and good (and probably doesn't hurt for the most part), but I question its effectiveness at causing the intended behavior. Is there any evidence to suggest that this causes an increase in bookmarking/printing behavior? Similarly, is there any evidence that users will use this method *rather than* the browser's default interface for the functions? I am really looking for user research with actual results, rather than anecdotes to answer this question. Thanks, Joseph Mastey
2011/02/21
[ "https://webmasters.stackexchange.com/questions/9516", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/639/" ]
I don't think you're going to find any actual hard data on this as there is no way to tell if anyone uses these links without actually looking over their shoulder (or installing spyware on all of your users' computers). I don't know if they increase in bookmarking or printing but I don't think that matters. What it boils down to is usability. Does it make your site more usable? If yes then it's a good thing to do even if it doesn't mean more people do it but more people have a better experience on your site or while using your software.
Of course they are used. The user may intend to print the page anyway, but you have made it easier for him. If you intend to implement it make sure to track everything. Use GA for event tracking to track the clicks on "Add to Favorites" or "print this". Use GA to track the links by adding tags to your links, then view the number of visits it generates under the source/medium report in GA see here: <http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55578> Here is an example (Note: window.external.AddFavorite only works in IE): ``` <a href="#" onclick="_gaq.push(['_trackEvent','share', 'favorites', 'page name']);window.external.AddFavorite('http://www.example.com?utm_source=share&utm_medium=favorites&utm_campaign=bookmark', 'Website Name'); return false;">Bookmark this Site/page</a> ```
55,685,115
I have a list of UI Buttons and Vector2 for positions. I am using random.range to place buttons randomly every time i load them. But it never shows all 5 buttons at different positions. instead overlapping some of them. Can anyone please help me with this? ``` [SerializeField] List<Button> answersButtons = new List<Button>(); [SerializeField] List<Vector2> positions = new List<Vector2>(); void ShuffleAnswersList() { for (int i = 0; i < answersButtons.Count; i++) { Vector2 tempPosition = answersButtons[i].GetComponent<RectTransform>().position; int randomIndex = Random.Range(0, positions.Count); answersButtons[i].transform.position = positions[randomIndex]; answersButtons[randomIndex].GetComponent<RectTransform>().position = tempPosition; Debug.Log(randomIndex); } } // shuffle positions public void Shuffle() { for (int i = 0; i < positions.Count; i++) { int rnd = Random.Range(0, positions.Count); Vector2 tempGO = positions[rnd]; positions[rnd] = positions[i]; positions[i] = tempGO; } } ```
2019/04/15
[ "https://Stackoverflow.com/questions/55685115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10760576/" ]
You are setting the `window.onclick` property twice, so you are overwriting the first one. That's why when you open the first menu and then the second, the first one stays open - because the first `window.onclick` doesn't exist anymore. My advise is to refactor the code, so that you have only one `window.onclick` handler that works universally for both menus. Also it's a bad idea to overwrite this even handler, better use `document.addEventListener()`.
* Avoid **[on-event attribute](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers)** > > `<button` ~~onclick="namedFunction()"~~ `></button>` > > > * use on-event property or `.addEventListener()` > > `document.querySelector("button").onclick = namedFunction` > `document.querySelector("button").addEventListener("click", namedFunction)` > > > * I there's multiple targets that are identical (HTML layout, CSS styles, JavaScript behavior, etc.), + use class avoid id. + find an ancestor element that all targets have in common. Although Window and Document can be considered as a common ancestor, try finding the closest to target. Referencing Window or Document is commonly used when listening for key events. + Once an ancestor is found, register it to the event. The ancestor will not only listen for registered events for itself -- it will listen for events triggered on any of its descendant elements as well. No need to register each element to one event and the amount of descendants that's covered is virtually limitless. + To determine and isolate the element that was actually clicked, changed, hovered over, etc -- use the Event property **[`event.target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target)**. The programming pattern described is the main part of **[Event Delegation](https://javascript.info/event-delegation)**. ```js const main = document.querySelector('main'); main.onclick = ddAccordion; function ddAccordion(e) { const clicked = e.target; const triggers = document.querySelectorAll('.trigger'); if (clicked.matches('.trigger')) { if (clicked.matches('.show')) { for (let t of triggers) { t.classList.remove('show'); } } else { for (let t of triggers) { t.classList.remove('show'); } clicked.classList.add('show'); } } return false; } ``` ```css body { overflow-y: scroll; overflow-x: hidden; } .trigger { background-color: #3498DB; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; width: 100%; } .trigger:hover, .trigger:focus { background-color: #2980B9; outline: 0; } .dropdown { width: 100%; } .content { background-color: #f1f1f1; max-height: 0px; overflow: hidden; transition: max-height 0.75s ease 0s; } .show+.content { max-height: 500px; height: auto; overflow: auto; transition: max-height 1.15s ease 0s; } .content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .content a:hover { background-color: #ddd; } ``` ```html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style></style> </head> <body> <main> <section class="dropdown"> <button class="trigger">Dropdown 1</button> <address class="content"> <a href="#home">Home</a> <a href="#about">About</a> <a href="#contact">Contact</a> </address> </section> <section class="dropdown"> <button class="trigger">Dropdown 2</button> <address class="content"> <a href="#home">Home</a> <a href="#about">About</a> <a href="#contact">Contact</a> </address> </section> <section class="dropdown"> <button class="trigger">Dropdown 3</button> <address class="content"> <a href="#home">Home</a> <a href="#about">About</a> <a href="#contact">Contact</a> </address> </section> </main> <script></script> </body> </html> ```
7,332,951
I need to prepare ASP.NET site with form, fill form in code behind and then submit form to external site. For example: user open www.myshop.com/pay.aspx, he does not have to fill anything because I fill form values in code behind and then user is automatically redirected to external site www.onlinepayments.com (with form data sent in POST). I am able to make it work with regular hidden form and javascript that submits form but I dont like this way (user can see html). So I use WebRequest class in code behind like in this answer: [How do you programmatically fill in a form and 'POST' a web page?](https://stackoverflow.com/questions/26857/how-do-you-programmatically-fill-in-a-form-and-post-a-web-page/26881#26881) However in this answer Response is string (target site html). What can I do with this string? I want my user see target site (conent and URL) like it would happen with regular html POST.
2011/09/07
[ "https://Stackoverflow.com/questions/7332951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159057/" ]
please take a look at this [post](http://www.silverlighthack.com/post/2010/10/08/Windows-Phone-7-RTM-Charting-using-the-Silverlight-Control-Toolkit.aspx). windows phone mango uses Siverlight 3, so you should still be able to use the charts from the silverlight toolkit.
Have a look at [Silverlight toolkit examples.](http://www.silverlight.net/content/samples/sl4/toolkitcontrolsamples/run/default.html) You can try port it to WP7 <http://silverlight.codeplex.com/>
54,041,428
From the shell, I need to list the size of all child directories. I am currently using: ``` du -hs * | sort -hr ``` However, this only gets one level down and does not traverse the directory tree.
2019/01/04
[ "https://Stackoverflow.com/questions/54041428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152965/" ]
You can use `**/*` ``` shopt -s globstar du -hs **/* | sort -hr shopt -u globstar ```
Wildcards are nice, but they'll also list FILES and not just directories. The below will return the sizes of all directories and only the directories: `find . -type d -exec du -sh {} \; | sort -hr`
54,041,428
From the shell, I need to list the size of all child directories. I am currently using: ``` du -hs * | sort -hr ``` However, this only gets one level down and does not traverse the directory tree.
2019/01/04
[ "https://Stackoverflow.com/questions/54041428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152965/" ]
You can use `**/*` ``` shopt -s globstar du -hs **/* | sort -hr shopt -u globstar ```
The `maxdepth` feature should solve your issue, but for some strange reason, it seems not to work: ``` find ./ -maxdepth 1 -type d -exec du -k {} \; ``` Maybe somebody can explain why the `maxdepth` is not taken into account?
54,041,428
From the shell, I need to list the size of all child directories. I am currently using: ``` du -hs * | sort -hr ``` However, this only gets one level down and does not traverse the directory tree.
2019/01/04
[ "https://Stackoverflow.com/questions/54041428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152965/" ]
The simplest is: ``` du -h --max-depth=1 parent ``` This will show all sizes of the children of `parent` If you also want the grandchildren, you can do ``` du -h --max-depth=2 parent ``` If you want the whole family ``` du -h parent ``` All these will just summarize the total directory size of each subdirectory up to a given level (except the last, it will give for all) If you don't want the content of the subdirectories, add the `-S` flag.
You can use `**/*` ``` shopt -s globstar du -hs **/* | sort -hr shopt -u globstar ```
54,041,428
From the shell, I need to list the size of all child directories. I am currently using: ``` du -hs * | sort -hr ``` However, this only gets one level down and does not traverse the directory tree.
2019/01/04
[ "https://Stackoverflow.com/questions/54041428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152965/" ]
The simplest is: ``` du -h --max-depth=1 parent ``` This will show all sizes of the children of `parent` If you also want the grandchildren, you can do ``` du -h --max-depth=2 parent ``` If you want the whole family ``` du -h parent ``` All these will just summarize the total directory size of each subdirectory up to a given level (except the last, it will give for all) If you don't want the content of the subdirectories, add the `-S` flag.
Wildcards are nice, but they'll also list FILES and not just directories. The below will return the sizes of all directories and only the directories: `find . -type d -exec du -sh {} \; | sort -hr`
54,041,428
From the shell, I need to list the size of all child directories. I am currently using: ``` du -hs * | sort -hr ``` However, this only gets one level down and does not traverse the directory tree.
2019/01/04
[ "https://Stackoverflow.com/questions/54041428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152965/" ]
If sorting you will likely want a consistent output instead of having some in GB, some in MB, some in KB.... And if I read the OP correctly, it isn't getting the directory tree, and that's a *problem*, right? It isn't listing subdirs because of the -s. Take that out (again, sorry if I'm misreading.) ``` du -b | sort -n ``` This lists all sizes in bytes, so you only need `-n` for `sort`.
Wildcards are nice, but they'll also list FILES and not just directories. The below will return the sizes of all directories and only the directories: `find . -type d -exec du -sh {} \; | sort -hr`
54,041,428
From the shell, I need to list the size of all child directories. I am currently using: ``` du -hs * | sort -hr ``` However, this only gets one level down and does not traverse the directory tree.
2019/01/04
[ "https://Stackoverflow.com/questions/54041428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152965/" ]
The simplest is: ``` du -h --max-depth=1 parent ``` This will show all sizes of the children of `parent` If you also want the grandchildren, you can do ``` du -h --max-depth=2 parent ``` If you want the whole family ``` du -h parent ``` All these will just summarize the total directory size of each subdirectory up to a given level (except the last, it will give for all) If you don't want the content of the subdirectories, add the `-S` flag.
The `maxdepth` feature should solve your issue, but for some strange reason, it seems not to work: ``` find ./ -maxdepth 1 -type d -exec du -k {} \; ``` Maybe somebody can explain why the `maxdepth` is not taken into account?
54,041,428
From the shell, I need to list the size of all child directories. I am currently using: ``` du -hs * | sort -hr ``` However, this only gets one level down and does not traverse the directory tree.
2019/01/04
[ "https://Stackoverflow.com/questions/54041428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152965/" ]
If sorting you will likely want a consistent output instead of having some in GB, some in MB, some in KB.... And if I read the OP correctly, it isn't getting the directory tree, and that's a *problem*, right? It isn't listing subdirs because of the -s. Take that out (again, sorry if I'm misreading.) ``` du -b | sort -n ``` This lists all sizes in bytes, so you only need `-n` for `sort`.
The `maxdepth` feature should solve your issue, but for some strange reason, it seems not to work: ``` find ./ -maxdepth 1 -type d -exec du -k {} \; ``` Maybe somebody can explain why the `maxdepth` is not taken into account?
54,041,428
From the shell, I need to list the size of all child directories. I am currently using: ``` du -hs * | sort -hr ``` However, this only gets one level down and does not traverse the directory tree.
2019/01/04
[ "https://Stackoverflow.com/questions/54041428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152965/" ]
The simplest is: ``` du -h --max-depth=1 parent ``` This will show all sizes of the children of `parent` If you also want the grandchildren, you can do ``` du -h --max-depth=2 parent ``` If you want the whole family ``` du -h parent ``` All these will just summarize the total directory size of each subdirectory up to a given level (except the last, it will give for all) If you don't want the content of the subdirectories, add the `-S` flag.
If sorting you will likely want a consistent output instead of having some in GB, some in MB, some in KB.... And if I read the OP correctly, it isn't getting the directory tree, and that's a *problem*, right? It isn't listing subdirs because of the -s. Take that out (again, sorry if I'm misreading.) ``` du -b | sort -n ``` This lists all sizes in bytes, so you only need `-n` for `sort`.
41,616,949
In Win32 Console Application (Visual C++) I have a array of objects and each object contains some other objects and variables, ex. (Owner and Equipment are structs, TimeInfo is class): ``` class Order { public: Order(); ~Order(); Owner owner; Equipment equipment; char *problem; TimeInfo timeinfo; void write(); int order_number; }; ``` Next I have class OrderManager, that contains the array of this object: ``` items = (Order*)(malloc(100 * sizeof(Order))); ``` In program, I add and remove items, but what is the best way to free memory at the end of program? I have free(manager.items);, but this doesn't work.
2017/01/12
[ "https://Stackoverflow.com/questions/41616949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6315663/" ]
As people have already pointed out, you should avoid using malloc in this situation. If you want to allocate 100 instances of Order, you could try something like this: ``` Order* items = new Order[100]; ``` In this case the default constructor of Order is called for every instance. When you want to free up the memory, you do: ``` delete[] items; // note the "[]" ``` Presumably, you want to handle the Orders within an OrderManager, so a typical place for the new/delete would be in the construtor/destructor of the OrderManager. When using new and delete, the con- and destructors will be called. It is important that the con- and destructors are called, since they are typically used to set up and initialize things on construction and release things on destruction. With malloc and free, all that happens is the allocation of memory on the heap. In your question you mentioned that ``` free(manager.items); ``` does not work. Shouldn't you be freeing the pointer items in stead of manager.items?
I would use a destructor to manage freeing memory allocated in the OrderManager class. You should be using C++ new and delete to allocate/deallocate memory and also should be using containers to store collections of an object. Refer to this link for a list of options on how you can initialize the vector: <https://stackoverflow.com/a/6143009/3817744> ``` class OrderManager { private: std::vector<Order> items; public: OrderManager() { // Refer to the link above } ~OrderManager() { items.clear(); } } ``` Here is a link to an interesting post about C++'s new operator by David Mazières. <http://www.scs.stanford.edu/~dm/home/papers/c++-new.html>
464,328
I want to save the result of `find` into the file with an Ansible play. ``` - name: Find / -name "postgresql" find: paths: /var/log patterns: 'postgresql' ``` The result of above will be saved into a file. Simply, the command is `find / -name "postgresql" > text.txt` in shell. How do I make that command in Ansible?
2018/08/23
[ "https://unix.stackexchange.com/questions/464328", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/273477/" ]
An Ansible way of doing this with the [find module](https://docs.ansible.com/ansible/latest/modules/find_module.html#find-return-a-list-of-files-based-on-specific-criteria) could be (I am using `/var/log/secure` as an example since I don't run postgres): ``` --- - hosts: all tasks: - name: "Find file /var/log/secure" find: paths: /var/log patterns: secure register: result - name: "Save find results to file" copy: content: "{{ result.files }}" dest: "/tmp/find_result.txt" ``` Content of `/tmp/find_result.txt`: ``` # cat /tmp/find_result.txt [{"uid": 0, "woth": false, "mtime": 1535012977.8429773, "inode": 9013905, "isgid": false, "size": 6867, "wgrp": false, "isuid": false, "isreg": true, "gid": 0, "ischr": false, "wusr": true, "xoth": false, "islnk": false, "nlink": 1, "issock": false, "rgrp": false, "path": "/var/log/secure", "xusr": false, "atime": 1534925281.706685, "isdir": false, "ctime": 1535012977.8429773, "isblk": false, "xgrp": false, "dev": 64768, "roth": false, "isfifo": false, "mode": "0600", "rusr": true}] ``` By registering the result, and checking the return value in `files`, you get access to a ton of metadata that might be useful. If you want less output, use on of the other return values as documented [here](https://docs.ansible.com/ansible/latest/modules/find_module.html#return-values).
You should use the [Ansible shell module](https://docs.ansible.com/ansible/2.5/modules/shell_module.html) in this case. Here's an example: ``` - name: Find / -name "postgresql" shell: find / -name "postgresql" > /tmp/text.txt ```
40,981,795
Using the wizard, I created a DbContext from an existing database and only selected one table to be pulled in. However now I need to add additional tables from that database to the Entity Model. What is the easiest way to add more tables from an existing database to a context that I have already created and to also generate the respective models for those tables?
2016/12/05
[ "https://Stackoverflow.com/questions/40981795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3447158/" ]
Easiest way is: 1) Open your .edmx database 2) Right click and choose "Update model from database..." 3) check the tables you want and click finish 4) EF will create all your entity classes for you
I think **EntityFramework Reverse Poco Generator** is what you're searching for. It's an extension for VS which allows to populate a TT file, then creating POCO entities for you. It is downloadable here: [EntityFramework Reverse Poco Generator](https://marketplace.visualstudio.com/items?itemName=SimonHughes.EntityFrameworkReversePOCOGenerator) I've wrote a very brief guide you could refer to, in order to setupt the extension and use it for your means. Check it here: [Introduction to EntityFramework Reverse POCO Generator for Visual Studio](http://social.technet.microsoft.com/wiki/contents/articles/36179.introduction-to-entityframework-reverse-poco-generator-for-visual-studio.aspx)
40,981,795
Using the wizard, I created a DbContext from an existing database and only selected one table to be pulled in. However now I need to add additional tables from that database to the Entity Model. What is the easiest way to add more tables from an existing database to a context that I have already created and to also generate the respective models for those tables?
2016/12/05
[ "https://Stackoverflow.com/questions/40981795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3447158/" ]
If you want to add the tables manually to your DbContext, you can do so by adding properties of type DbSet to the DbContext. For ex: ``` public DbSet<CarColor> CarColors { get; set; } ```
I think **EntityFramework Reverse Poco Generator** is what you're searching for. It's an extension for VS which allows to populate a TT file, then creating POCO entities for you. It is downloadable here: [EntityFramework Reverse Poco Generator](https://marketplace.visualstudio.com/items?itemName=SimonHughes.EntityFrameworkReversePOCOGenerator) I've wrote a very brief guide you could refer to, in order to setupt the extension and use it for your means. Check it here: [Introduction to EntityFramework Reverse POCO Generator for Visual Studio](http://social.technet.microsoft.com/wiki/contents/articles/36179.introduction-to-entityframework-reverse-poco-generator-for-visual-studio.aspx)
2,480,974
I am new to Haskell and this mixture of Infix and Prefix notation is confusing me. What is the difference between an operator like '+' and a function like head? How do I write an operator 'c' which does this 1 c 1 = 2? I found this definition a ! b = True. How does Haskell know that I am defining ! and not a function a?
2010/03/19
[ "https://Stackoverflow.com/questions/2480974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82368/" ]
In Haskell, to create an operator you must use the following "operator symbols": ! # $ % \* + . / < = > ? \ ^ | : - ~ So, for example ``` ($$$) a b = a+b ``` Defines an operator $$$ which can be used in the expression 1 $$$ 1 to yield a value of 2. Conceptually, there is no difference between an operator and a function, and you can use backticks or parens to make one work like the other. **EDIT:** Just so it is 100% clear, let me demonstrate turning a function into an operator and vice versa: For the operator '+', the following two expressions are equivalent: ``` 1+1 (+) 1 1 ``` Similarly, for a function, the following two expressions are equivalent: ``` foo 1 2 1 `foo` 2 ```
Haskell knows you aren't defining a function called `a` because the `!` wouldn't be valid in a function argument list. In order to use the `!` not as an operator but just as a normal identifier, you need to enclose it in parentheses. If you wrote instead `a (!) b = True`, then it would define the function `a :: t -> t1 -> Bool`. This is the entire difference between operators and normal identifiers in Haskell — there are special syntax rules for operators that allow them to be used infix without backticks. Otherwise, they're just functions.
2,480,974
I am new to Haskell and this mixture of Infix and Prefix notation is confusing me. What is the difference between an operator like '+' and a function like head? How do I write an operator 'c' which does this 1 c 1 = 2? I found this definition a ! b = True. How does Haskell know that I am defining ! and not a function a?
2010/03/19
[ "https://Stackoverflow.com/questions/2480974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82368/" ]
In Haskell, to create an operator you must use the following "operator symbols": ! # $ % \* + . / < = > ? \ ^ | : - ~ So, for example ``` ($$$) a b = a+b ``` Defines an operator $$$ which can be used in the expression 1 $$$ 1 to yield a value of 2. Conceptually, there is no difference between an operator and a function, and you can use backticks or parens to make one work like the other. **EDIT:** Just so it is 100% clear, let me demonstrate turning a function into an operator and vice versa: For the operator '+', the following two expressions are equivalent: ``` 1+1 (+) 1 1 ``` Similarly, for a function, the following two expressions are equivalent: ``` foo 1 2 1 `foo` 2 ```
Really, the only difference is syntax. Function names begin with a lower-case letter, followed by a series of alpha-numeric characters. Operators are some unique sequence of the typical operator characters (+ - / \* < > etc.). Functions can be used as operators (in-fix) by enclosing the function name in ` characters. For example: ``` b = x `elem` xs -- b is True if x is an element in xs. ``` Operators can be used as functions (pre-fix) by enclosing the operator in parens. For example: ``` n = (+) 2 5 -- n = 2 + 5, or 7. ```
23,801,935
I'm opening the default mail client with a pre filled form (to, subject, body). Everything works fine except for one thing. I can't figure out out to add a linebreak to the body text. I tried to encode the `<br>` Tag but it didn't work. The result was that in the body only showed the first line while the second line was gone. **Example:** ``` private void openMail(URI uri) { if (Desktop.isDesktopSupported() && (Desktop.getDesktop()).isSupported(Desktop.Action.MAIL)) { try { try { String address = "[email protected]"; String subject = "Custom_Subject"; String html_br = "&lt;br&gt;"; String body = "First%20Line" + html_br + "Second%20Line"; String mailToString = "mailto:" + address + "?subject=" + subject + "&body=" + body; URI mailto = new URI(mailToString); Desktop.getDesktop().mail(mailto); } catch (URISyntaxException e) { e.printStackTrace(); } } catch (IOException e) { } } else { } } ```
2014/05/22
[ "https://Stackoverflow.com/questions/23801935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1065366/" ]
Try `%0D%0A` (as carrage return linefeed)
If the format is HTML newline characters will be ignored and you'd need to insert HTML breaks `<br />`. ``` StringBuilder body = new StringBuilder(); body.append("First Line<br />"); body.append("Second Line<br />"); String mailToString = "mailto:" + address + "?subject=" + subject + "&body=" + body.toString(); ```
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
You don't have to detect it manually to achieve that effect. One Mach-O executable file can contain both binaries for 32 bit and 64 bit intel machines, and the kernel runs the most appropriate ones automatically. If you're using XCode, there's a setting in the project inspector where you can set the architectures (ppc, i386, x86\_64) you want to have in a single universal binary. Also, remember that on OS X, running a 64-bit kernel (with Snow Leopard) and being able to run a 64-bit user land app are two orthogonal concepts. If you have a machine with 64 bit cpu, you can run a user-land program in a 64-bit mode even when the kernel is running in the 32 bit mode (with Leopard or Snow Leopard), as long as all of the libraries you link with are available with 64 bit. So it's not that useful to check if the OS is 64-bit capable.
The standard way of checking the os version (and hence whether its snow leopard, a 64-bit os) is detailed [here](http://www.cocoadev.com/index.pl?DeterminingOSVersion).
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
There is a super-easy way. Compile two versions of the executable, one for 32-bit and one for 64-bit and combine them with lipo. That way, the right version will always get executed. ``` gcc -lobjc somefile.m -o somefile -m32 -march=i686 gcc -lobjc somefile.m -o somefile2 -m64 -march=x86_64 lipo -create -arch i686 somefile -arch x86_64 somefile2 -output somefileUniversal ``` Edit: or just compile a universal binary in the first place with `gcc -arch i686 -arch x86_64` In response to OP's comment: ``` if(sizeof(int*) == 4) //system is 32-bit else if(sizeof(int*) == 8) //system is 64-bit ``` EDIT: D'oh! I didn't realise you'd need runtime checking... Going through the output of `sysctl -A`, two variables look potentially useful. Try parsing the output of `sysctl hw.optional.x86_64` and `sysctl hw.cpu64bit_capable` . I don't have a 32-bit Mac around to test this, but both these are set to 1 in Snow Leopard on a Core2Duo Mac.
To programmatically get a string with the CPU architecture name: ``` #include <sys/types.h> #include <sys/sysctl.h> // Determine the machine name, e.g. "x86_64". size_t size; sysctlbyname("hw.machine", NULL, &size, NULL, 0); // Get size of data to be returned. char *name = malloc(size); sysctlbyname("hw.machine", name, &size, NULL, 0); // Do stuff... free(name); ``` To do the same thing in a shell script: ``` set name=`sysctl -n hw.machine` ```
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
If you are on Snow Leopard use NSRunningApplication's executableArchitecture. Otherwise, I would do the following: ``` -(BOOL) is64Bit { #if __LP64__ return YES; #else return NO; #endif } ```
The standard way of checking the os version (and hence whether its snow leopard, a 64-bit os) is detailed [here](http://www.cocoadev.com/index.pl?DeterminingOSVersion).
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
Use `[[NSRunningApplication currentApplication] executableArchitecture]` which returns one of the following constants: * `NSBundleExecutableArchitectureI386` * `NSBundleExecutableArchitectureX86_64` * `NSBundleExecutableArchitecturePPC` * `NSBundleExecutableArchitecturePPC64` For example: ``` switch ([[NSRunningApplication currentApplication] executableArchitecture]) { case NSBundleExecutableArchitectureI386: // TODO: i386 break; case NSBundleExecutableArchitectureX86_64: // TODO: x86_64 break; case NSBundleExecutableArchitecturePPC: // TODO: ppc break; case NSBundleExecutableArchitecturePPC64: // TODO: ppc64 break; default: // TODO: unknown arch break; } ```
The standard way of checking the os version (and hence whether its snow leopard, a 64-bit os) is detailed [here](http://www.cocoadev.com/index.pl?DeterminingOSVersion).
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
You don't have to detect it manually to achieve that effect. One Mach-O executable file can contain both binaries for 32 bit and 64 bit intel machines, and the kernel runs the most appropriate ones automatically. If you're using XCode, there's a setting in the project inspector where you can set the architectures (ppc, i386, x86\_64) you want to have in a single universal binary. Also, remember that on OS X, running a 64-bit kernel (with Snow Leopard) and being able to run a 64-bit user land app are two orthogonal concepts. If you have a machine with 64 bit cpu, you can run a user-land program in a 64-bit mode even when the kernel is running in the 32 bit mode (with Leopard or Snow Leopard), as long as all of the libraries you link with are available with 64 bit. So it's not that useful to check if the OS is 64-bit capable.
To programmatically get a string with the CPU architecture name: ``` #include <sys/types.h> #include <sys/sysctl.h> // Determine the machine name, e.g. "x86_64". size_t size; sysctlbyname("hw.machine", NULL, &size, NULL, 0); // Get size of data to be returned. char *name = malloc(size); sysctlbyname("hw.machine", name, &size, NULL, 0); // Do stuff... free(name); ``` To do the same thing in a shell script: ``` set name=`sysctl -n hw.machine` ```
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
If you are on Snow Leopard use NSRunningApplication's executableArchitecture. Otherwise, I would do the following: ``` -(BOOL) is64Bit { #if __LP64__ return YES; #else return NO; #endif } ```
To programmatically get a string with the CPU architecture name: ``` #include <sys/types.h> #include <sys/sysctl.h> // Determine the machine name, e.g. "x86_64". size_t size; sysctlbyname("hw.machine", NULL, &size, NULL, 0); // Get size of data to be returned. char *name = malloc(size); sysctlbyname("hw.machine", name, &size, NULL, 0); // Do stuff... free(name); ``` To do the same thing in a shell script: ``` set name=`sysctl -n hw.machine` ```
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
There is a super-easy way. Compile two versions of the executable, one for 32-bit and one for 64-bit and combine them with lipo. That way, the right version will always get executed. ``` gcc -lobjc somefile.m -o somefile -m32 -march=i686 gcc -lobjc somefile.m -o somefile2 -m64 -march=x86_64 lipo -create -arch i686 somefile -arch x86_64 somefile2 -output somefileUniversal ``` Edit: or just compile a universal binary in the first place with `gcc -arch i686 -arch x86_64` In response to OP's comment: ``` if(sizeof(int*) == 4) //system is 32-bit else if(sizeof(int*) == 8) //system is 64-bit ``` EDIT: D'oh! I didn't realise you'd need runtime checking... Going through the output of `sysctl -A`, two variables look potentially useful. Try parsing the output of `sysctl hw.optional.x86_64` and `sysctl hw.cpu64bit_capable` . I don't have a 32-bit Mac around to test this, but both these are set to 1 in Snow Leopard on a Core2Duo Mac.
Usually, you shouldn't need to be able to check at runtime whether you're on 64 or 32 bits. If your host application (that's what I'd call the app that launches the 64 or 32 bit tools) is a fat binary, the compile-time check is enough. Since it will get compiled twice (once for the 32-bit part of the fat binary, once for the 64-bit part), and the right one will be launched by the system, you'll compile in the right launch code by just writing sth. like ``` #if __LP64__ NSString *vExecutablePath = [[NSBundle mainBundle] pathForResource: @"tool64" ofType: @""]; #else NSString *vExecutablePath = [[NSBundle mainBundle] pathForResource: @"tool32" ofType: @""]; #endif [NSTask launchedTaskWithLaunchPath: vExecutableName ...]; ``` If the user somehow explicitly launches your app in 32 bits on a 64 bit Mac, trust them that they know what they're doing. It's an edge case anyway, and why break things for power users out of a wrong sense of perfection. You may even be happy yourself if you discover a 64-bit-only bug if you can tell users the workaround is launching as 32 bits. You only need a real runtime check if your app itself is only 32 bits (e.g. Carbon GUI with command-line helper). In that case, host\_processor\_info or sysctl or similar are probably your only route if for some weird reason you can't just lipo the two executables together.
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
There is a super-easy way. Compile two versions of the executable, one for 32-bit and one for 64-bit and combine them with lipo. That way, the right version will always get executed. ``` gcc -lobjc somefile.m -o somefile -m32 -march=i686 gcc -lobjc somefile.m -o somefile2 -m64 -march=x86_64 lipo -create -arch i686 somefile -arch x86_64 somefile2 -output somefileUniversal ``` Edit: or just compile a universal binary in the first place with `gcc -arch i686 -arch x86_64` In response to OP's comment: ``` if(sizeof(int*) == 4) //system is 32-bit else if(sizeof(int*) == 8) //system is 64-bit ``` EDIT: D'oh! I didn't realise you'd need runtime checking... Going through the output of `sysctl -A`, two variables look potentially useful. Try parsing the output of `sysctl hw.optional.x86_64` and `sysctl hw.cpu64bit_capable` . I don't have a 32-bit Mac around to test this, but both these are set to 1 in Snow Leopard on a Core2Duo Mac.
Use `[[NSRunningApplication currentApplication] executableArchitecture]` which returns one of the following constants: * `NSBundleExecutableArchitectureI386` * `NSBundleExecutableArchitectureX86_64` * `NSBundleExecutableArchitecturePPC` * `NSBundleExecutableArchitecturePPC64` For example: ``` switch ([[NSRunningApplication currentApplication] executableArchitecture]) { case NSBundleExecutableArchitectureI386: // TODO: i386 break; case NSBundleExecutableArchitectureX86_64: // TODO: x86_64 break; case NSBundleExecutableArchitecturePPC: // TODO: ppc break; case NSBundleExecutableArchitecturePPC64: // TODO: ppc64 break; default: // TODO: unknown arch break; } ```
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
Usually, you shouldn't need to be able to check at runtime whether you're on 64 or 32 bits. If your host application (that's what I'd call the app that launches the 64 or 32 bit tools) is a fat binary, the compile-time check is enough. Since it will get compiled twice (once for the 32-bit part of the fat binary, once for the 64-bit part), and the right one will be launched by the system, you'll compile in the right launch code by just writing sth. like ``` #if __LP64__ NSString *vExecutablePath = [[NSBundle mainBundle] pathForResource: @"tool64" ofType: @""]; #else NSString *vExecutablePath = [[NSBundle mainBundle] pathForResource: @"tool32" ofType: @""]; #endif [NSTask launchedTaskWithLaunchPath: vExecutableName ...]; ``` If the user somehow explicitly launches your app in 32 bits on a 64 bit Mac, trust them that they know what they're doing. It's an edge case anyway, and why break things for power users out of a wrong sense of perfection. You may even be happy yourself if you discover a 64-bit-only bug if you can tell users the workaround is launching as 32 bits. You only need a real runtime check if your app itself is only 32 bits (e.g. Carbon GUI with command-line helper). In that case, host\_processor\_info or sysctl or similar are probably your only route if for some weird reason you can't just lipo the two executables together.
The standard way of checking the os version (and hence whether its snow leopard, a 64-bit os) is detailed [here](http://www.cocoadev.com/index.pl?DeterminingOSVersion).
1,988,996
I'm currently wring a [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application. So in short: how do I detect if the application is running on a 64 bit OS? Edit: I know about the [Mach-O](http://en.wikipedia.org/wiki/Mach-O) fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for [x86](http://en.wikipedia.org/wiki/X86) and one for [x64](http://en.wikipedia.org/wiki/X86-64).
2010/01/01
[ "https://Stackoverflow.com/questions/1988996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241978/" ]
Use `[[NSRunningApplication currentApplication] executableArchitecture]` which returns one of the following constants: * `NSBundleExecutableArchitectureI386` * `NSBundleExecutableArchitectureX86_64` * `NSBundleExecutableArchitecturePPC` * `NSBundleExecutableArchitecturePPC64` For example: ``` switch ([[NSRunningApplication currentApplication] executableArchitecture]) { case NSBundleExecutableArchitectureI386: // TODO: i386 break; case NSBundleExecutableArchitectureX86_64: // TODO: x86_64 break; case NSBundleExecutableArchitecturePPC: // TODO: ppc break; case NSBundleExecutableArchitecturePPC64: // TODO: ppc64 break; default: // TODO: unknown arch break; } ```
You don't have to detect it manually to achieve that effect. One Mach-O executable file can contain both binaries for 32 bit and 64 bit intel machines, and the kernel runs the most appropriate ones automatically. If you're using XCode, there's a setting in the project inspector where you can set the architectures (ppc, i386, x86\_64) you want to have in a single universal binary. Also, remember that on OS X, running a 64-bit kernel (with Snow Leopard) and being able to run a 64-bit user land app are two orthogonal concepts. If you have a machine with 64 bit cpu, you can run a user-land program in a 64-bit mode even when the kernel is running in the 32 bit mode (with Leopard or Snow Leopard), as long as all of the libraries you link with are available with 64 bit. So it's not that useful to check if the OS is 64-bit capable.
23,185,649
I am stuck on making a regular expression that matches numbers from 01 to 56, with a space between them but not a space a the end. Strings samples look like these ones: ``` "33 44 51 52 53 54" "01 05 09 14 25 36" ``` To achieve that, i am using the following expression (and testing it at <http://regexpal.com/>): ``` ([0-5][0-9] +){6} ``` It works fine, but the problem is that it only matches those strings only if there is a space at the end: ``` "01 05 09 14 25 36 " ``` How do i fix this? How do i limit it to match until 56 and not 59? and to start from 01 and not from 00?
2014/04/20
[ "https://Stackoverflow.com/questions/23185649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1883256/" ]
It's easier than you think. But this still matches everything from 00 to 59. So I have not answered the 2nd question. ``` ([0-5][0-9] +){5}[0-5][0-9] ```
Separate matches for numbers starting with 5 and 0: ``` ^((0[1-9]|[1-4][0-9]|5[0-6])( +|$)){6}(?<! )$ ``` `(?<! )` a negative look behind to check the last space ***Explanations***: ``` ^ # Start of string ( # 1st optional capturing group ( #2nd optional capturing group 0[1-9] # Match two-digit numbers start with 0 and not 00 | # Or [0-4][0-9] # Match two-digit numbers start with 0 through 4 | # Or 5[0-6] # Match 50 through 56 ) # 0 or more spaces ( +|$) # 1 or more spaces after digits but not the last ){6} # For 6 times (?<! ) # No space at the end $ # End of string ``` [**Live demo**](http://regex101.com/r/iA8sY2) *Notice that the first line has an space at the end*
23,185,649
I am stuck on making a regular expression that matches numbers from 01 to 56, with a space between them but not a space a the end. Strings samples look like these ones: ``` "33 44 51 52 53 54" "01 05 09 14 25 36" ``` To achieve that, i am using the following expression (and testing it at <http://regexpal.com/>): ``` ([0-5][0-9] +){6} ``` It works fine, but the problem is that it only matches those strings only if there is a space at the end: ``` "01 05 09 14 25 36 " ``` How do i fix this? How do i limit it to match until 56 and not 59? and to start from 01 and not from 00?
2014/04/20
[ "https://Stackoverflow.com/questions/23185649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1883256/" ]
Try this: ``` ^((0[1-9]|[1-4][0-9]|5[0-6]) ){5}(0[1-9]|[1-4][0-9]|5[0-6])$ ``` This will match any number from 01 to 56, where each number is followed either by a space, repeated 5 times, followed by another number from 01 to 56. The start (`^`) and end (`$`) anchors ensure that no other characters are allowed before or after the matched string. However, depending on your language / platform of choice, for something like this, it's probably better to simply split the string by spaces and parse each substring as an integer, and validate that the number is in the appropriate range.
It's easier than you think. But this still matches everything from 00 to 59. So I have not answered the 2nd question. ``` ([0-5][0-9] +){5}[0-5][0-9] ```
23,185,649
I am stuck on making a regular expression that matches numbers from 01 to 56, with a space between them but not a space a the end. Strings samples look like these ones: ``` "33 44 51 52 53 54" "01 05 09 14 25 36" ``` To achieve that, i am using the following expression (and testing it at <http://regexpal.com/>): ``` ([0-5][0-9] +){6} ``` It works fine, but the problem is that it only matches those strings only if there is a space at the end: ``` "01 05 09 14 25 36 " ``` How do i fix this? How do i limit it to match until 56 and not 59? and to start from 01 and not from 00?
2014/04/20
[ "https://Stackoverflow.com/questions/23185649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1883256/" ]
Try this: ``` ^((0[1-9]|[1-4][0-9]|5[0-6]) ){5}(0[1-9]|[1-4][0-9]|5[0-6])$ ``` This will match any number from 01 to 56, where each number is followed either by a space, repeated 5 times, followed by another number from 01 to 56. The start (`^`) and end (`$`) anchors ensure that no other characters are allowed before or after the matched string. However, depending on your language / platform of choice, for something like this, it's probably better to simply split the string by spaces and parse each substring as an integer, and validate that the number is in the appropriate range.
Separate matches for numbers starting with 5 and 0: ``` ^((0[1-9]|[1-4][0-9]|5[0-6])( +|$)){6}(?<! )$ ``` `(?<! )` a negative look behind to check the last space ***Explanations***: ``` ^ # Start of string ( # 1st optional capturing group ( #2nd optional capturing group 0[1-9] # Match two-digit numbers start with 0 and not 00 | # Or [0-4][0-9] # Match two-digit numbers start with 0 through 4 | # Or 5[0-6] # Match 50 through 56 ) # 0 or more spaces ( +|$) # 1 or more spaces after digits but not the last ){6} # For 6 times (?<! ) # No space at the end $ # End of string ``` [**Live demo**](http://regex101.com/r/iA8sY2) *Notice that the first line has an space at the end*
30,067,935
I've embed a bootstrap datepicker from <http://www.malot.fr/bootstrap-datetimepicker/demo.php> I want only the date and month and year to be displayed. But in this plugin I've date,month,year, and time. How do I remove only the time selection from this datepicker?
2015/05/06
[ "https://Stackoverflow.com/questions/30067935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4548891/" ]
Use [DatePicker](https://bootstrap-datepicker.readthedocs.org/en/latest/) instead of DateTimePicker.
I use a different datetime picker, and have had great success with it. [Bootstrap 3 Date/Time Picker](https://github.com/Eonasdan/bootstrap-datetimepicker). It uses [Moment.js](http://momentjs.com/) and allows for all sorts of date/time formatting options. It is also more accessible, and allows for scrolling through the calendar and time option using a keyboard. Using the plugin I suggested, the format for just the date would be: ``` $('.formDate').datetimepicker({ format: 'MM/DD/YYYY' }); ```
42,090,369
I need a macro to split my data from one Excel file to few others. It looks like this: ``` UserList.xls User Role Location DDAVIS XX WW DDAVIS XS WW GROBERT XW WP SJOBS XX AA SJOBS XS AA SJOBS XW AA ``` I need, to copy data like this: ``` WW_DDAVIS.xls User Role DDAVIS XX DDAVIS XS WP_GROBERT.xls User Role GROBERT XW AA_SJOBS.xls User Role SJOBS XX SJOBS XS SJOBS XW ``` I need every user, to have his own file. The problem appeared when I was told that the files need to be filled using template (template.xls). Looks the same, but data in the source file starts in cell A2, and in the template file from cell A8. To copy data without template I used this code: ``` Public Sub SplitToFiles() ' MACRO SplitToFiles ' Last update: 2012-03-04 ' Author: mtone ' Version 1.1 ' Description: ' Loops through a specified column, and split each distinct values into a separate file by making a copy and deleting rows below and above ' ' Note: Values in the column should be unique or sorted. ' ' The following cells are ignored when delimiting sections: ' - blank cells, or containing spaces only ' - same value repeated ' - cells containing "total" ' ' Files are saved in a "Split" subfolder from the location of the source workbook, and named after the section name. Dim osh As Worksheet ' Original sheet Dim iRow As Long ' Cursors Dim iCol As Long Dim iFirstRow As Long ' Constant Dim iTotalRows As Long ' Constant Dim iStartRow As Long ' Section delimiters Dim iStopRow As Long Dim sSectionName As String ' Section name (and filename) Dim rCell As Range ' current cell Dim owb As Workbook ' Original workbook Dim sFilePath As String ' Constant Dim iCount As Integer ' # of documents created iCol = Application.InputBox("Enter the column number used for splitting", "Select column", 2, , , , , 1) iRow = Application.InputBox("Enter the starting row number (to skip header)", "Select row", 5, , , , , 1) iFirstRow = iRow Set osh = Application.ActiveSheet Set owb = Application.ActiveWorkbook iTotalRows = osh.UsedRange.Rows.Count sFilePath = Application.ActiveWorkbook.Path If Dir(sFilePath + "\Split", vbDirectory) = "" Then MkDir sFilePath + "\Split" End If 'Turn Off Screen Updating Events Application.EnableEvents = False Application.ScreenUpdating = False Do ' Get cell at cursor Set rCell = osh.Cells(iRow, iCol) sCell = Replace(rCell.Text, " ", "") If sCell = "" Or (rCell.Text = sSectionName And iStartRow <> 0) Or InStr(1, rCell.Text, "total", vbTextCompare) <> 0 Then ' Skip condition met Else ' Found new section If iStartRow = 0 Then ' StartRow delimiter not set, meaning beginning a new section sSectionName = rCell.Text iStartRow = iRow Else ' StartRow delimiter set, meaning we reached the end of a section iStopRow = iRow - 1 ' Pass variables to a separate sub to create and save the new worksheet CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat iCount = iCount + 1 ' Reset section delimiters iStartRow = 0 iStopRow = 0 ' Ready to continue loop iRow = iRow - 1 End If End If ' Continue until last row is reached If iRow < iTotalRows Then iRow = iRow + 1 Else ' Finished. Save the last section iStopRow = iRow CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat iCount = iCount + 1 ' Exit Exit Do End If Loop 'Turn On Screen Updating Events Application.ScreenUpdating = True Application.EnableEvents = True MsgBox Str(iCount) + " documents saved in " + sFilePath End Sub Public Sub DeleteRows(targetSheet As Worksheet, RowFrom As Long, RowTo As Long) Dim rngRange As Range Set rngRange = Range(targetSheet.Cells(RowFrom, 1), targetSheet.Cells(RowTo, 1)).EntireRow rngRange.Select rngRange.Delete End Sub Public Sub CopySheet(osh As Worksheet, iFirstRow As Long, iStartRow As Long, iStopRow As Long, iTotalRows As Long, sFilePath As String, sSectionName As String, fileFormat As XlFileFormat) Dim ash As Worksheet ' Copied sheet Dim awb As Workbook ' New workbook ' Copy book osh.Copy Set ash = Application.ActiveSheet ' Delete Rows after section If iTotalRows > iStopRow Then DeleteRows ash, iStopRow + 1, iTotalRows End If ' Delete Rows before section If iStartRow > iFirstRow Then DeleteRows ash, iFirstRow, iStartRow - 1 End If ' Select left-topmost cell ash.Cells(1, 1).Select ' Clean up a few characters to prevent invalid filename sSectionName = Replace(sSectionName, "/", " ") sSectionName = Replace(sSectionName, "\", " ") sSectionName = Replace(sSectionName, ":", " ") sSectionName = Replace(sSectionName, "=", " ") sSectionName = Replace(sSectionName, "*", " ") sSectionName = Replace(sSectionName, ".", " ") sSectionName = Replace(sSectionName, "?", " ") ' Save in same format as original workbook ash.SaveAs sFilePath + "\Split\" + sSectionName, fileFormat ' Close Set awb = ash.Parent awb.Close SaveChanges:=False End Sub ``` The problem in this one, is that I have no idea how to make name not DDAVIS.xls, but using WW\_DDAVIS.xls (location\_user.xls). Second problem - Use template. This code just copies whole workbook and erases all wrong data. All I need, is to copy value of the right data to this template. Unfortunately I didn't find working code and I'm not so fluent in VBA to make it alone. I tried other one, that worked only in half. It copied the template to every file and name it properly, but I couldn't figure out how to copy cells to the right files. ``` Option Explicit Sub copyTemplate() Dim lRow, x As Integer Dim wbName As String Dim fso As Variant Dim dic As Variant Dim colA As String Dim colB As String Dim colSep As String Dim copyFile As String Dim copyTo As String Set dic = CreateObject("Scripting.Dictionary") 'dictionary to ensure that duplicates are not created Set fso = CreateObject("Scripting.FileSystemObject") 'file scripting object for fiile system manipulation colSep = "_" 'separater between values of col A and col B for file name dic.Add colSep, vbNullString ' ensuring that we never create a file when both columns are blank in between 'get last used row in col A lRow = Range("A" & Rows.Count).End(xlUp).Row x = 1 copyFile = "c:\location\Template.xls" 'template file to copy copyTo = "C:\location\List\" 'location where copied files need to be copied Do x = x + 1 colA = Range("G" & x).Value 'col a value colB = Range("A" & x).Value ' col b value wbName = colA & colSep & colB ' create new file name If (Not dic.Exists(wbName)) Then 'ensure that we have not created this file name before fso.copyFile copyFile, copyTo & wbName & ".xls" 'copy the file dic.Add wbName, vbNullString 'add to dictionary that we have created this file End If Loop Until x = lRow Set dic = Nothing ' clean up Set fso = Nothing ' clean up End Sub ```
2017/02/07
[ "https://Stackoverflow.com/questions/42090369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7528685/" ]
In Python `|` and `&` are bitwise operators, they do bit calculations. On the other hand `and` and `or` are logical (boolean) operators.
| is a bitwise operators and in python script do bit calculations Use this ``` i = 200 j = 201 if i == 200 or j == 201: print "Hi" else: print "No" ```
42,090,369
I need a macro to split my data from one Excel file to few others. It looks like this: ``` UserList.xls User Role Location DDAVIS XX WW DDAVIS XS WW GROBERT XW WP SJOBS XX AA SJOBS XS AA SJOBS XW AA ``` I need, to copy data like this: ``` WW_DDAVIS.xls User Role DDAVIS XX DDAVIS XS WP_GROBERT.xls User Role GROBERT XW AA_SJOBS.xls User Role SJOBS XX SJOBS XS SJOBS XW ``` I need every user, to have his own file. The problem appeared when I was told that the files need to be filled using template (template.xls). Looks the same, but data in the source file starts in cell A2, and in the template file from cell A8. To copy data without template I used this code: ``` Public Sub SplitToFiles() ' MACRO SplitToFiles ' Last update: 2012-03-04 ' Author: mtone ' Version 1.1 ' Description: ' Loops through a specified column, and split each distinct values into a separate file by making a copy and deleting rows below and above ' ' Note: Values in the column should be unique or sorted. ' ' The following cells are ignored when delimiting sections: ' - blank cells, or containing spaces only ' - same value repeated ' - cells containing "total" ' ' Files are saved in a "Split" subfolder from the location of the source workbook, and named after the section name. Dim osh As Worksheet ' Original sheet Dim iRow As Long ' Cursors Dim iCol As Long Dim iFirstRow As Long ' Constant Dim iTotalRows As Long ' Constant Dim iStartRow As Long ' Section delimiters Dim iStopRow As Long Dim sSectionName As String ' Section name (and filename) Dim rCell As Range ' current cell Dim owb As Workbook ' Original workbook Dim sFilePath As String ' Constant Dim iCount As Integer ' # of documents created iCol = Application.InputBox("Enter the column number used for splitting", "Select column", 2, , , , , 1) iRow = Application.InputBox("Enter the starting row number (to skip header)", "Select row", 5, , , , , 1) iFirstRow = iRow Set osh = Application.ActiveSheet Set owb = Application.ActiveWorkbook iTotalRows = osh.UsedRange.Rows.Count sFilePath = Application.ActiveWorkbook.Path If Dir(sFilePath + "\Split", vbDirectory) = "" Then MkDir sFilePath + "\Split" End If 'Turn Off Screen Updating Events Application.EnableEvents = False Application.ScreenUpdating = False Do ' Get cell at cursor Set rCell = osh.Cells(iRow, iCol) sCell = Replace(rCell.Text, " ", "") If sCell = "" Or (rCell.Text = sSectionName And iStartRow <> 0) Or InStr(1, rCell.Text, "total", vbTextCompare) <> 0 Then ' Skip condition met Else ' Found new section If iStartRow = 0 Then ' StartRow delimiter not set, meaning beginning a new section sSectionName = rCell.Text iStartRow = iRow Else ' StartRow delimiter set, meaning we reached the end of a section iStopRow = iRow - 1 ' Pass variables to a separate sub to create and save the new worksheet CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat iCount = iCount + 1 ' Reset section delimiters iStartRow = 0 iStopRow = 0 ' Ready to continue loop iRow = iRow - 1 End If End If ' Continue until last row is reached If iRow < iTotalRows Then iRow = iRow + 1 Else ' Finished. Save the last section iStopRow = iRow CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat iCount = iCount + 1 ' Exit Exit Do End If Loop 'Turn On Screen Updating Events Application.ScreenUpdating = True Application.EnableEvents = True MsgBox Str(iCount) + " documents saved in " + sFilePath End Sub Public Sub DeleteRows(targetSheet As Worksheet, RowFrom As Long, RowTo As Long) Dim rngRange As Range Set rngRange = Range(targetSheet.Cells(RowFrom, 1), targetSheet.Cells(RowTo, 1)).EntireRow rngRange.Select rngRange.Delete End Sub Public Sub CopySheet(osh As Worksheet, iFirstRow As Long, iStartRow As Long, iStopRow As Long, iTotalRows As Long, sFilePath As String, sSectionName As String, fileFormat As XlFileFormat) Dim ash As Worksheet ' Copied sheet Dim awb As Workbook ' New workbook ' Copy book osh.Copy Set ash = Application.ActiveSheet ' Delete Rows after section If iTotalRows > iStopRow Then DeleteRows ash, iStopRow + 1, iTotalRows End If ' Delete Rows before section If iStartRow > iFirstRow Then DeleteRows ash, iFirstRow, iStartRow - 1 End If ' Select left-topmost cell ash.Cells(1, 1).Select ' Clean up a few characters to prevent invalid filename sSectionName = Replace(sSectionName, "/", " ") sSectionName = Replace(sSectionName, "\", " ") sSectionName = Replace(sSectionName, ":", " ") sSectionName = Replace(sSectionName, "=", " ") sSectionName = Replace(sSectionName, "*", " ") sSectionName = Replace(sSectionName, ".", " ") sSectionName = Replace(sSectionName, "?", " ") ' Save in same format as original workbook ash.SaveAs sFilePath + "\Split\" + sSectionName, fileFormat ' Close Set awb = ash.Parent awb.Close SaveChanges:=False End Sub ``` The problem in this one, is that I have no idea how to make name not DDAVIS.xls, but using WW\_DDAVIS.xls (location\_user.xls). Second problem - Use template. This code just copies whole workbook and erases all wrong data. All I need, is to copy value of the right data to this template. Unfortunately I didn't find working code and I'm not so fluent in VBA to make it alone. I tried other one, that worked only in half. It copied the template to every file and name it properly, but I couldn't figure out how to copy cells to the right files. ``` Option Explicit Sub copyTemplate() Dim lRow, x As Integer Dim wbName As String Dim fso As Variant Dim dic As Variant Dim colA As String Dim colB As String Dim colSep As String Dim copyFile As String Dim copyTo As String Set dic = CreateObject("Scripting.Dictionary") 'dictionary to ensure that duplicates are not created Set fso = CreateObject("Scripting.FileSystemObject") 'file scripting object for fiile system manipulation colSep = "_" 'separater between values of col A and col B for file name dic.Add colSep, vbNullString ' ensuring that we never create a file when both columns are blank in between 'get last used row in col A lRow = Range("A" & Rows.Count).End(xlUp).Row x = 1 copyFile = "c:\location\Template.xls" 'template file to copy copyTo = "C:\location\List\" 'location where copied files need to be copied Do x = x + 1 colA = Range("G" & x).Value 'col a value colB = Range("A" & x).Value ' col b value wbName = colA & colSep & colB ' create new file name If (Not dic.Exists(wbName)) Then 'ensure that we have not created this file name before fso.copyFile copyFile, copyTo & wbName & ".xls" 'copy the file dic.Add wbName, vbNullString 'add to dictionary that we have created this file End If Loop Until x = lRow Set dic = Nothing ' clean up Set fso = Nothing ' clean up End Sub ```
2017/02/07
[ "https://Stackoverflow.com/questions/42090369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7528685/" ]
The problem here is actually one of **operator precedence**, not specifically of using a bitwise `|` rather than the logical `or`; `True | True` and `True or True` give the same result. Per the [Python docs](https://docs.python.org/2/reference/expressions.html#operator-precedence) the comparison `==` has lower precedence than bitwise `|`, so your conditional expression is evaluating to: ``` i == (200 | j) == 201 ``` which is false. If you added parentheses to clarify: ``` (i == 200) | (j == 201) ``` you would get the behaviour you expected. --- However, the correct thing to do is use `or`. Using `or` works because without parentheses because the boolean operators have lower precedence than comparisons. Additionally: * it is more readable, as it is natural language to express what you mean * it short circuits, so if the left-hand side is truthy the right-hand side doesn't need to be evaluated * it works in a wider range of scenarios, where a bitwise operation would be a `TypeError`
In Python `|` and `&` are bitwise operators, they do bit calculations. On the other hand `and` and `or` are logical (boolean) operators.
42,090,369
I need a macro to split my data from one Excel file to few others. It looks like this: ``` UserList.xls User Role Location DDAVIS XX WW DDAVIS XS WW GROBERT XW WP SJOBS XX AA SJOBS XS AA SJOBS XW AA ``` I need, to copy data like this: ``` WW_DDAVIS.xls User Role DDAVIS XX DDAVIS XS WP_GROBERT.xls User Role GROBERT XW AA_SJOBS.xls User Role SJOBS XX SJOBS XS SJOBS XW ``` I need every user, to have his own file. The problem appeared when I was told that the files need to be filled using template (template.xls). Looks the same, but data in the source file starts in cell A2, and in the template file from cell A8. To copy data without template I used this code: ``` Public Sub SplitToFiles() ' MACRO SplitToFiles ' Last update: 2012-03-04 ' Author: mtone ' Version 1.1 ' Description: ' Loops through a specified column, and split each distinct values into a separate file by making a copy and deleting rows below and above ' ' Note: Values in the column should be unique or sorted. ' ' The following cells are ignored when delimiting sections: ' - blank cells, or containing spaces only ' - same value repeated ' - cells containing "total" ' ' Files are saved in a "Split" subfolder from the location of the source workbook, and named after the section name. Dim osh As Worksheet ' Original sheet Dim iRow As Long ' Cursors Dim iCol As Long Dim iFirstRow As Long ' Constant Dim iTotalRows As Long ' Constant Dim iStartRow As Long ' Section delimiters Dim iStopRow As Long Dim sSectionName As String ' Section name (and filename) Dim rCell As Range ' current cell Dim owb As Workbook ' Original workbook Dim sFilePath As String ' Constant Dim iCount As Integer ' # of documents created iCol = Application.InputBox("Enter the column number used for splitting", "Select column", 2, , , , , 1) iRow = Application.InputBox("Enter the starting row number (to skip header)", "Select row", 5, , , , , 1) iFirstRow = iRow Set osh = Application.ActiveSheet Set owb = Application.ActiveWorkbook iTotalRows = osh.UsedRange.Rows.Count sFilePath = Application.ActiveWorkbook.Path If Dir(sFilePath + "\Split", vbDirectory) = "" Then MkDir sFilePath + "\Split" End If 'Turn Off Screen Updating Events Application.EnableEvents = False Application.ScreenUpdating = False Do ' Get cell at cursor Set rCell = osh.Cells(iRow, iCol) sCell = Replace(rCell.Text, " ", "") If sCell = "" Or (rCell.Text = sSectionName And iStartRow <> 0) Or InStr(1, rCell.Text, "total", vbTextCompare) <> 0 Then ' Skip condition met Else ' Found new section If iStartRow = 0 Then ' StartRow delimiter not set, meaning beginning a new section sSectionName = rCell.Text iStartRow = iRow Else ' StartRow delimiter set, meaning we reached the end of a section iStopRow = iRow - 1 ' Pass variables to a separate sub to create and save the new worksheet CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat iCount = iCount + 1 ' Reset section delimiters iStartRow = 0 iStopRow = 0 ' Ready to continue loop iRow = iRow - 1 End If End If ' Continue until last row is reached If iRow < iTotalRows Then iRow = iRow + 1 Else ' Finished. Save the last section iStopRow = iRow CopySheet osh, iFirstRow, iStartRow, iStopRow, iTotalRows, sFilePath, sSectionName, owb.fileFormat iCount = iCount + 1 ' Exit Exit Do End If Loop 'Turn On Screen Updating Events Application.ScreenUpdating = True Application.EnableEvents = True MsgBox Str(iCount) + " documents saved in " + sFilePath End Sub Public Sub DeleteRows(targetSheet As Worksheet, RowFrom As Long, RowTo As Long) Dim rngRange As Range Set rngRange = Range(targetSheet.Cells(RowFrom, 1), targetSheet.Cells(RowTo, 1)).EntireRow rngRange.Select rngRange.Delete End Sub Public Sub CopySheet(osh As Worksheet, iFirstRow As Long, iStartRow As Long, iStopRow As Long, iTotalRows As Long, sFilePath As String, sSectionName As String, fileFormat As XlFileFormat) Dim ash As Worksheet ' Copied sheet Dim awb As Workbook ' New workbook ' Copy book osh.Copy Set ash = Application.ActiveSheet ' Delete Rows after section If iTotalRows > iStopRow Then DeleteRows ash, iStopRow + 1, iTotalRows End If ' Delete Rows before section If iStartRow > iFirstRow Then DeleteRows ash, iFirstRow, iStartRow - 1 End If ' Select left-topmost cell ash.Cells(1, 1).Select ' Clean up a few characters to prevent invalid filename sSectionName = Replace(sSectionName, "/", " ") sSectionName = Replace(sSectionName, "\", " ") sSectionName = Replace(sSectionName, ":", " ") sSectionName = Replace(sSectionName, "=", " ") sSectionName = Replace(sSectionName, "*", " ") sSectionName = Replace(sSectionName, ".", " ") sSectionName = Replace(sSectionName, "?", " ") ' Save in same format as original workbook ash.SaveAs sFilePath + "\Split\" + sSectionName, fileFormat ' Close Set awb = ash.Parent awb.Close SaveChanges:=False End Sub ``` The problem in this one, is that I have no idea how to make name not DDAVIS.xls, but using WW\_DDAVIS.xls (location\_user.xls). Second problem - Use template. This code just copies whole workbook and erases all wrong data. All I need, is to copy value of the right data to this template. Unfortunately I didn't find working code and I'm not so fluent in VBA to make it alone. I tried other one, that worked only in half. It copied the template to every file and name it properly, but I couldn't figure out how to copy cells to the right files. ``` Option Explicit Sub copyTemplate() Dim lRow, x As Integer Dim wbName As String Dim fso As Variant Dim dic As Variant Dim colA As String Dim colB As String Dim colSep As String Dim copyFile As String Dim copyTo As String Set dic = CreateObject("Scripting.Dictionary") 'dictionary to ensure that duplicates are not created Set fso = CreateObject("Scripting.FileSystemObject") 'file scripting object for fiile system manipulation colSep = "_" 'separater between values of col A and col B for file name dic.Add colSep, vbNullString ' ensuring that we never create a file when both columns are blank in between 'get last used row in col A lRow = Range("A" & Rows.Count).End(xlUp).Row x = 1 copyFile = "c:\location\Template.xls" 'template file to copy copyTo = "C:\location\List\" 'location where copied files need to be copied Do x = x + 1 colA = Range("G" & x).Value 'col a value colB = Range("A" & x).Value ' col b value wbName = colA & colSep & colB ' create new file name If (Not dic.Exists(wbName)) Then 'ensure that we have not created this file name before fso.copyFile copyFile, copyTo & wbName & ".xls" 'copy the file dic.Add wbName, vbNullString 'add to dictionary that we have created this file End If Loop Until x = lRow Set dic = Nothing ' clean up Set fso = Nothing ' clean up End Sub ```
2017/02/07
[ "https://Stackoverflow.com/questions/42090369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7528685/" ]
The problem here is actually one of **operator precedence**, not specifically of using a bitwise `|` rather than the logical `or`; `True | True` and `True or True` give the same result. Per the [Python docs](https://docs.python.org/2/reference/expressions.html#operator-precedence) the comparison `==` has lower precedence than bitwise `|`, so your conditional expression is evaluating to: ``` i == (200 | j) == 201 ``` which is false. If you added parentheses to clarify: ``` (i == 200) | (j == 201) ``` you would get the behaviour you expected. --- However, the correct thing to do is use `or`. Using `or` works because without parentheses because the boolean operators have lower precedence than comparisons. Additionally: * it is more readable, as it is natural language to express what you mean * it short circuits, so if the left-hand side is truthy the right-hand side doesn't need to be evaluated * it works in a wider range of scenarios, where a bitwise operation would be a `TypeError`
| is a bitwise operators and in python script do bit calculations Use this ``` i = 200 j = 201 if i == 200 or j == 201: print "Hi" else: print "No" ```
30,532,236
If I want to refer to a range within the active workbook in Excel VBA, I can say "With Range("Myrange")". I don't need a sheet name. Sometimes I want to refer to a range in another workbook. "With MyWorkbook.Range("Myrange")" doesn't work because I have to specify the sheet that the range is in. Is there any way of referring to the range in a workbook without having to say which sheet the range is in?
2015/05/29
[ "https://Stackoverflow.com/questions/30532236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3674157/" ]
If you create a named range and scope it to the Workbook you can use the following to get a named range in any workbook. You obviously get an error if the name can't be found. ``` wb.Names("Myrange").RefersToRange ```
Yes, create a Named Range (ex: `MyRangeName`) within your workbook. Then in your code use `Range("MyRangeName")` and it will refer to those cells on that sheet no matter what workbook you're looking at.
14,211,843
I am uploading a file in JSF. I am using Tomahawk's `<t:inputFileUpload>` for this, but the same question is applicable on e.g. PrimeFaces `<p:fileUpload>` and JSF 2.2 `<h:inputFile>`. I have the below backing bean code: ``` private UploadedFile uploadedFile; // +getter+setter public String save() throws IOException { String name = uploadedFile.getName(); System.out.println("File name: " + name); String type = uploadedFile.getContentType(); System.out.println("File type: " + type); long size = uploadedFile.getSize(); System.out.println("File size: " + size); InputStream stream = uploadedFile.getInputStream(); byte[] buffer = new byte[(int) size]; stream.read(buffer, 0, (int) size); stream.close(); } ``` I am able to get the file name, type and size, but I am unable to save this file at a specific path. I can't figure out the proper way to save the uploaded file. How can I achieve this?
2013/01/08
[ "https://Stackoverflow.com/questions/14211843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473193/" ]
The `getInputStream()` method of the uploaded file represents the file content. ``` InputStream input = uploadedFile.getInputStream(); ``` You need to copy it to a file. You should first prepare a folder on the local disk file system where the uploaded files should be stored. For example, `/path/to/uploads` (on Windows, that would be on the same disk as where the server runs). Note that you should **absolutely not** store the files in expanded WAR folder or even the IDE project's folder by using a hardcoded path or a web-relative path or `getRealPath()` for the reasons mentioned here [Uploaded image only available after refreshing the page](https://stackoverflow.com/questions/8885201/uploaded-image-only-available-after-refreshing-the-page). Then, you need to autogenerate the filename. Otherwise, when someone else uploads a file with coincidentally the same name later, it would be overwritten. You could use [`Files#createTempFile()`](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#createTempFile-java.nio.file.Path-java.lang.String-java.lang.String-java.nio.file.attribute.FileAttribute...-) facility to get an autogenerated filename. ``` Path folder = Paths.get("/path/to/uploads"); String filename = FilenameUtils.getBaseName(uploadedFile.getName()); String extension = FilenameUtils.getExtension(uploadedFile.getName()); Path file = Files.createTempFile(folder, filename + "-", "." + extension); ``` The path to uploads could if necessary be parameterized based on one of several ways shown in this Q&A: [Recommended way to save uploaded files in a servlet application](https://stackoverflow.com/questions/18664579/recommended-way-to-save-uploaded-files-in-a-servlet-application). The `FilenameUtils` is part of Apache Commons IO which you should already have in your classpath as it's a dependency of the Tomahawk file upload component. Finally, just stream the uploaded file to that file (assuming Java 7): ``` try (InputStream input = uploadedFile.getInputStream()) { Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING); } System.out.println("Uploaded file successfully saved in " + file); ``` Then, to download it back, easiest would be to register `/path/to/uploads` as a new webapp context or a virtual host so that all those files are available by an URL. See also [Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag](https://stackoverflow.com/questions/4543936/load-the-image-from-outside-of-webcontext-in-jsf).
PrimeFaces uses two file upload decoder for uploading content of p:fileupload 1. NativeFileUploadDecoder 2. CommonsFileUploadDecoder NativeFileUploadDecoder is the default upload decoder and it requires servlet container 3.0. So if your servlet container is less than 3 then it will not work with you. Also some application servers make a restriction on using multi-part content So if you have a problem with the native upload decoder for any reason you have to use the other decoder which is "CommonsFileUploadDecoder" CommonsFileUploadDecoder depends on Apache common lib so you have to put the **commons-fileupload and commons-io jars** in your class-path the version depends on your primefaces version but 1.3 and 2.2 respectively works for me. to use CommonsFileUploadDecoder you have to use filter ``` <filter> <filter-name>PrimeFaces FileUpload Filter</filter-name> <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class> </filter> <filter-mapping> <filter-name>PrimeFaces FileUpload Filter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> ``` **wait the filter only will not work** because inside the filter it checks about the uploader if its not provided and it detect at least JSF 2.2 so it will bypass the request to the default decoder "Native" and then it will not work for your also to force the filter to use the common decoder you have to put the following context param in your web.xml ``` <context-param> <param-name>primefaces.UPLOADER</param-name> <param-value>commons</param-value> </context-param> ```
40,942,592
I have request for updating page. When adding new page request is like: ``` 'title'=>'required|max:70|unique:pages', ``` but when I'm updating page title must be unique but need to check all other titles except one already entered. I searched Google for all possible solutions but nothing works. I tried: ``` 'title'=>"required|max:70|unique:pages, title,{$this->id}", 'title'=>'required|max:70|unique:pages, title,'.$this->id, 'title'=>'required|max:70|unique:pages, title,'.$this->input('id'), ``` rule is inside rules method ``` public function rules() { return [ 'title'=>'required|max:70|unique:pages, title,'.$this->id, ... ] ``` I'm getting this error: ``` SQLSTATE[42S22]: Column not found: 1054 Unknown column ' title' in 'where clause' (SQL: select count(*) as aggregate from `pages` where ` title` = test and `id` <> ) ``` In my mysql I have id (lowercase) column that is primary key and title column (also lowercase).
2016/12/02
[ "https://Stackoverflow.com/questions/40942592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5092259/" ]
You have a bug here: ``` public function rules() { This space is causing trouble | return [ 'title'=>'required|max:70|unique:pages, title,'.$this->id, ... ] ``` Should be ``` public function rules() { Space removed | return [ 'title'=>'required|max:70|unique:pages,title,'.$this->id, ... ] ```
``` SQLSTATE[42S22]: Column not found: 1054 Unknown column ' title' ``` It seems that it's searching for a column named " title", it may be stupid but double check that the column name is sent without a space at the beggining.
66,373,644
I know are many ways to get what I searching, actually I found the solution here on the forum, but the problem is that I don't really know why is not working, this is my try: ``` select * From ModeloBI.CORP.T_LOGI_RN_Planeacion_Entregas Where ModeloBI.CORP.T_LOGI_RN_Planeacion_Entregas.Fecha_de_modificacion >= dateadd (day, -7, GetDate()); ``` (where *Fecha\_de\_Modificacion* is the field with the date of the record) When I execute this query I get next error: **"Column 'day' does not exist"** Do you know guys, who is this happening? or if there are other method to get what I want? Thanks by the way, have a nice day,
2021/02/25
[ "https://Stackoverflow.com/questions/66373644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14963549/" ]
First of all, your css are looking for elements inside the class `.item`. Your HTML doesn't have that class. Second, if you want to style only the first element inside a class you need to use the pseudo-class "first-child". ```css #GerenciarEpsOvas .infos > * { padding: 1px; color: red; } #GerenciarEpsOvas .infos > p:first-child { padding: 1px; color: blue; } #GerenciarEpsOvas .infos .name { text-overflow: ellipsis; white-space:nowrap; overflow: hidden; } ``` ```html <div id="GerenciarEpsOvas"> <div class="infos"> <p class="nome">Anime: <font color="#bbb">Test</font></p> <p>Ova: <font color="#bbb">Test 1</font></p> <p>Episódio: <font color="#d47b33">Test 2</font></p> </div> </div> ```
I think you want to select everything that is a child of GerenciarEpsOvas, .item or .infos. To achieve that (selecting multiple) separate them with commas. I set the passing to 100px to make it more obvious: ```css #GerenciarEpsOvas, .item, .infos > * { padding: 100px; } #GerenciarEpsOvas, .item, .infos, .name { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } ``` ```html <div class="infos"> <p class="nome">Anime: <font color="#bbb">Test</font> </p> <p>Ova: <font color="#bbb">Test 1</font> </p> <p>Episódio: <font color="#d47b33">Test 2</font> </p> </div> ``` In your example your selecting decendants. [Read here](https://css-tricks.com/child-and-sibling-selectors/)
22,261,631
Im looking to create a 2 or more ul class with li content from a foreach loop if the values count more than 5. ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); echo '<ul class="row1">'; foreach($data as $value){ echo '<li>' . $value . '</li>'; } echo '</ul>' ``` the result will be: ``` <ul class="row1"> <li>Barcelona</li> ... ... </ul> ``` What i want is after 5 towns create a new ul class like ``` <ul class="row1"> <li>Barcelona</li> ... ... ... ... </ul> <ul class="row2"> <li>Madrid</li> ... ... ... ... </ul> ``` Is there a way to do this? Any help is appreciated.
2014/03/07
[ "https://Stackoverflow.com/questions/22261631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091123/" ]
``` <?php $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); $cur = 0; $rowNum = 1; foreach($data as $value){ if($cur == 0) { echo '<ul class="row' . $rowNum . '">'; } echo ' <li>' . $value . '</li>'; if($cur == 4) { echo '</ul>'; $cur = 0; $rowNum++; } else { $cur++; } } ?> ```
You can do this by counting how many you did already. This can be achieved by either get a variable and increment it inside the `foreach()` or directly use a `for()`. ``` $amount = count($data); $no_of_ul = 1; for ($i=0; $i<$amount; $i++) { if ($i % 5 == 0) { if ($i > 0) { echo '</ul>'; } echo '<ul class="row'.$no_of_ul.'">'; $no_of_ul++; } echo '<li>'.$data[$i].'</li>'; } ``` `$i % 5 == 0` means "if `$i` divided by `5` has the rest `0`" which is true for `$i = 0, 5, 10, ...`. With this you'll only need to close the last `<ul>` manually.
22,261,631
Im looking to create a 2 or more ul class with li content from a foreach loop if the values count more than 5. ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); echo '<ul class="row1">'; foreach($data as $value){ echo '<li>' . $value . '</li>'; } echo '</ul>' ``` the result will be: ``` <ul class="row1"> <li>Barcelona</li> ... ... </ul> ``` What i want is after 5 towns create a new ul class like ``` <ul class="row1"> <li>Barcelona</li> ... ... ... ... </ul> <ul class="row2"> <li>Madrid</li> ... ... ... ... </ul> ``` Is there a way to do this? Any help is appreciated.
2014/03/07
[ "https://Stackoverflow.com/questions/22261631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091123/" ]
Keep it simple. The [`array_chunk()`](http://php.net/array_chunk) function sounds exactly what you are looking for. In this example there will be 3 items in each list. ``` $lists = array_chunk($data, 3); $number = 1; foreach ($lists as $items) { echo '<ul class="row', $number++, '">'; foreach ($items as $item) { echo '<li>', $item, '</li>'; } echo '</ul>'; } ``` You can also do it a little more surgically (which probably will consume quite a lot less memory). If you know how many items you have, `A`, and how many items should fit in a list, `B`, then you can figure out how many lists you would need, `ceil(A / B)`: ``` $itemsCount = count($data); $itemsPerList = 3; $listsNeeded = ceil($itemsCount / $itemsPerList); for ($i = 0; $i < $listsNeeded; $i++) { echo '<ul class="row', ($i + 1), '">'; for ($j = 0; $j < $itemsPerList; $j++) { $index = (($i * $itemsPerList) + $j); if (isset($data[$index])) { echo '<li>', $data[$index], '</li>'; } else { break; } } echo '</ul>'; } ```
You can do this by counting how many you did already. This can be achieved by either get a variable and increment it inside the `foreach()` or directly use a `for()`. ``` $amount = count($data); $no_of_ul = 1; for ($i=0; $i<$amount; $i++) { if ($i % 5 == 0) { if ($i > 0) { echo '</ul>'; } echo '<ul class="row'.$no_of_ul.'">'; $no_of_ul++; } echo '<li>'.$data[$i].'</li>'; } ``` `$i % 5 == 0` means "if `$i` divided by `5` has the rest `0`" which is true for `$i = 0, 5, 10, ...`. With this you'll only need to close the last `<ul>` manually.
22,261,631
Im looking to create a 2 or more ul class with li content from a foreach loop if the values count more than 5. ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); echo '<ul class="row1">'; foreach($data as $value){ echo '<li>' . $value . '</li>'; } echo '</ul>' ``` the result will be: ``` <ul class="row1"> <li>Barcelona</li> ... ... </ul> ``` What i want is after 5 towns create a new ul class like ``` <ul class="row1"> <li>Barcelona</li> ... ... ... ... </ul> <ul class="row2"> <li>Madrid</li> ... ... ... ... </ul> ``` Is there a way to do this? Any help is appreciated.
2014/03/07
[ "https://Stackoverflow.com/questions/22261631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091123/" ]
``` <?php $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); $cur = 0; $rowNum = 1; foreach($data as $value){ if($cur == 0) { echo '<ul class="row' . $rowNum . '">'; } echo ' <li>' . $value . '</li>'; if($cur == 4) { echo '</ul>'; $cur = 0; $rowNum++; } else { $cur++; } } ?> ```
Does it helps ? ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); $count = 1 ; $len = sizeof($data); $row = 1; foreach($data as $value){ if($count == 1 ){ echo '<ul class="row'.$row.'">'; $row++; } echo '<li>' . $value . '</li>'; if($count !=1 && $count%5 == 0){ echo '</ul>'; if($len-1 != $count){ echo '<ul class="row'.$row.'">'; $row++; } } $count++; } ```
22,261,631
Im looking to create a 2 or more ul class with li content from a foreach loop if the values count more than 5. ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); echo '<ul class="row1">'; foreach($data as $value){ echo '<li>' . $value . '</li>'; } echo '</ul>' ``` the result will be: ``` <ul class="row1"> <li>Barcelona</li> ... ... </ul> ``` What i want is after 5 towns create a new ul class like ``` <ul class="row1"> <li>Barcelona</li> ... ... ... ... </ul> <ul class="row2"> <li>Madrid</li> ... ... ... ... </ul> ``` Is there a way to do this? Any help is appreciated.
2014/03/07
[ "https://Stackoverflow.com/questions/22261631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091123/" ]
``` <?php $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); $cur = 0; $rowNum = 1; foreach($data as $value){ if($cur == 0) { echo '<ul class="row' . $rowNum . '">'; } echo ' <li>' . $value . '</li>'; if($cur == 4) { echo '</ul>'; $cur = 0; $rowNum++; } else { $cur++; } } ?> ```
Keep it simple. The [`array_chunk()`](http://php.net/array_chunk) function sounds exactly what you are looking for. In this example there will be 3 items in each list. ``` $lists = array_chunk($data, 3); $number = 1; foreach ($lists as $items) { echo '<ul class="row', $number++, '">'; foreach ($items as $item) { echo '<li>', $item, '</li>'; } echo '</ul>'; } ``` You can also do it a little more surgically (which probably will consume quite a lot less memory). If you know how many items you have, `A`, and how many items should fit in a list, `B`, then you can figure out how many lists you would need, `ceil(A / B)`: ``` $itemsCount = count($data); $itemsPerList = 3; $listsNeeded = ceil($itemsCount / $itemsPerList); for ($i = 0; $i < $listsNeeded; $i++) { echo '<ul class="row', ($i + 1), '">'; for ($j = 0; $j < $itemsPerList; $j++) { $index = (($i * $itemsPerList) + $j); if (isset($data[$index])) { echo '<li>', $data[$index], '</li>'; } else { break; } } echo '</ul>'; } ```
22,261,631
Im looking to create a 2 or more ul class with li content from a foreach loop if the values count more than 5. ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); echo '<ul class="row1">'; foreach($data as $value){ echo '<li>' . $value . '</li>'; } echo '</ul>' ``` the result will be: ``` <ul class="row1"> <li>Barcelona</li> ... ... </ul> ``` What i want is after 5 towns create a new ul class like ``` <ul class="row1"> <li>Barcelona</li> ... ... ... ... </ul> <ul class="row2"> <li>Madrid</li> ... ... ... ... </ul> ``` Is there a way to do this? Any help is appreciated.
2014/03/07
[ "https://Stackoverflow.com/questions/22261631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091123/" ]
``` <?php $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); $cur = 0; $rowNum = 1; foreach($data as $value){ if($cur == 0) { echo '<ul class="row' . $rowNum . '">'; } echo ' <li>' . $value . '</li>'; if($cur == 4) { echo '</ul>'; $cur = 0; $rowNum++; } else { $cur++; } } ?> ```
I know this is a bit of an older post but I thought I would contribute. I have a wp project where I had to display lot of title / permalink lists throughout the site. Sverri M. Olsen's answer really made the job much quicker, easier to read, and universal... ``` function display_title_link_lists($args, $chunk_size) { $query = new WP_Query( $args ); $title_link = []; while ( $query->have_posts() ) : $query->the_post(); $title_link[get_the_title()] = get_the_permalink(); endwhile; $output_title_link = array_chunk($title_link, $chunk_size, true); foreach ($output_title_link as $tierOne) { echo "<div class='col-sm col-md'><ul>"; foreach($tierOne as $key => $value) { echo "<li><a href='$value'>$key</a></li>"; } echo "</ul></div>"; } wp_reset_postdata(); ``` I was able to modify it and use it as another utility in other projects.
22,261,631
Im looking to create a 2 or more ul class with li content from a foreach loop if the values count more than 5. ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); echo '<ul class="row1">'; foreach($data as $value){ echo '<li>' . $value . '</li>'; } echo '</ul>' ``` the result will be: ``` <ul class="row1"> <li>Barcelona</li> ... ... </ul> ``` What i want is after 5 towns create a new ul class like ``` <ul class="row1"> <li>Barcelona</li> ... ... ... ... </ul> <ul class="row2"> <li>Madrid</li> ... ... ... ... </ul> ``` Is there a way to do this? Any help is appreciated.
2014/03/07
[ "https://Stackoverflow.com/questions/22261631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091123/" ]
Keep it simple. The [`array_chunk()`](http://php.net/array_chunk) function sounds exactly what you are looking for. In this example there will be 3 items in each list. ``` $lists = array_chunk($data, 3); $number = 1; foreach ($lists as $items) { echo '<ul class="row', $number++, '">'; foreach ($items as $item) { echo '<li>', $item, '</li>'; } echo '</ul>'; } ``` You can also do it a little more surgically (which probably will consume quite a lot less memory). If you know how many items you have, `A`, and how many items should fit in a list, `B`, then you can figure out how many lists you would need, `ceil(A / B)`: ``` $itemsCount = count($data); $itemsPerList = 3; $listsNeeded = ceil($itemsCount / $itemsPerList); for ($i = 0; $i < $listsNeeded; $i++) { echo '<ul class="row', ($i + 1), '">'; for ($j = 0; $j < $itemsPerList; $j++) { $index = (($i * $itemsPerList) + $j); if (isset($data[$index])) { echo '<li>', $data[$index], '</li>'; } else { break; } } echo '</ul>'; } ```
Does it helps ? ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); $count = 1 ; $len = sizeof($data); $row = 1; foreach($data as $value){ if($count == 1 ){ echo '<ul class="row'.$row.'">'; $row++; } echo '<li>' . $value . '</li>'; if($count !=1 && $count%5 == 0){ echo '</ul>'; if($len-1 != $count){ echo '<ul class="row'.$row.'">'; $row++; } } $count++; } ```
22,261,631
Im looking to create a 2 or more ul class with li content from a foreach loop if the values count more than 5. ``` $data = array('Barcelona','Jujuy','Cordoba','Mendoza','Galicia','Madrid','Estonia','New York'); echo '<ul class="row1">'; foreach($data as $value){ echo '<li>' . $value . '</li>'; } echo '</ul>' ``` the result will be: ``` <ul class="row1"> <li>Barcelona</li> ... ... </ul> ``` What i want is after 5 towns create a new ul class like ``` <ul class="row1"> <li>Barcelona</li> ... ... ... ... </ul> <ul class="row2"> <li>Madrid</li> ... ... ... ... </ul> ``` Is there a way to do this? Any help is appreciated.
2014/03/07
[ "https://Stackoverflow.com/questions/22261631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091123/" ]
Keep it simple. The [`array_chunk()`](http://php.net/array_chunk) function sounds exactly what you are looking for. In this example there will be 3 items in each list. ``` $lists = array_chunk($data, 3); $number = 1; foreach ($lists as $items) { echo '<ul class="row', $number++, '">'; foreach ($items as $item) { echo '<li>', $item, '</li>'; } echo '</ul>'; } ``` You can also do it a little more surgically (which probably will consume quite a lot less memory). If you know how many items you have, `A`, and how many items should fit in a list, `B`, then you can figure out how many lists you would need, `ceil(A / B)`: ``` $itemsCount = count($data); $itemsPerList = 3; $listsNeeded = ceil($itemsCount / $itemsPerList); for ($i = 0; $i < $listsNeeded; $i++) { echo '<ul class="row', ($i + 1), '">'; for ($j = 0; $j < $itemsPerList; $j++) { $index = (($i * $itemsPerList) + $j); if (isset($data[$index])) { echo '<li>', $data[$index], '</li>'; } else { break; } } echo '</ul>'; } ```
I know this is a bit of an older post but I thought I would contribute. I have a wp project where I had to display lot of title / permalink lists throughout the site. Sverri M. Olsen's answer really made the job much quicker, easier to read, and universal... ``` function display_title_link_lists($args, $chunk_size) { $query = new WP_Query( $args ); $title_link = []; while ( $query->have_posts() ) : $query->the_post(); $title_link[get_the_title()] = get_the_permalink(); endwhile; $output_title_link = array_chunk($title_link, $chunk_size, true); foreach ($output_title_link as $tierOne) { echo "<div class='col-sm col-md'><ul>"; foreach($tierOne as $key => $value) { echo "<li><a href='$value'>$key</a></li>"; } echo "</ul></div>"; } wp_reset_postdata(); ``` I was able to modify it and use it as another utility in other projects.
166,100
When reading the Harry Potter series, I couldn't help but notice: Harry destroyed Tom Riddle's diary with a basilisk fang, and later in the series we find out that its poison can be conveniently used to destroy Horcruxes, and the diary was conveniently one of those Horcruxes. With example above, I came up with a **possible** chain of logic: Destroy the diary with a fang to make Harry cool -> make diary a Horcrux -> Horcrux can be destroyed with basilisk poison because it was used in a previous book). All above led me to this question: **Is there any information on how was the plot of the Harry Potter series developed?** Did Rowling already make an outline for the plot of the entire story, and was just modifying it as time went on; or was she creating the plot of the next book based on what she wrote before, and then just tied all the knots together?
2017/07/31
[ "https://scifi.stackexchange.com/questions/166100", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/85535/" ]
I'm sure someone can answer this better, but until then... J. K. Rowling took 5 years to develop the world of Harry Potter. I'm not sure if it's confirmed, but it is certainly implied that in this time she planned out the majority of what was going to happen. However, Rowling also confirmed that much of 'the Half-Blood Prince' was originally used in 'the Chamber of Secrets'. This implies that the story naturally progressed as she wrote, but from the offset of writing, she always had a through and thought out plot in her mind.
If you study the writing process, and it is a process, it is iterative. Meaning that you once you "finish" the process, you go back and make adjustments. The first iteration that is commonly used is to write an out line, first of the general and overarching plot lines for the whole series, then for the book you are currently working on. The next iteration is to write the book, as many authors put it, get the bones down, you don't worry about changes you make on the way, you write the complete book. The subsequent iterations, you adjust the book, incorporating changes that you need to, adding detail, removing detail, sometimes cutting material for later use. Why do you need to change things? because, the outline was just an outline, but when writing the prose, you may find that something would work better, then ten or twenty pages later, you change your mind. This is why you write the whole book before changing things, because in the next chapter you may decide that the original concept was better. Once the author is satisfied, they pass the manuscript on to the editing staff. They read the book and suggest changes, as questions that prompt changes, and make general grammar corrections. Again, this may occur multiple times until all parties are satisfied. Even with these iterations, errors and misunderstandings creep in. Jordan, who is noted for doing extensive research, had gotten the uses of quenching agents backwards in his first print of one of his books. This was changed in later printings.
74,677,722
So here is the context. I created an script in python, YOLOv4, OpenCV, CUDA and CUDNN, for object detection and object tracking to count the objects in a video. I intend to use it in real time, but what real time really means? The video I'm using is 1min long and 60FPS originally, but the video after processing is 30FPS on average and takes 3mins to finish. So comparing both videos side by side, one is clearly faster. 30FPS is industry standard for movies and stuff. I'm trying to wrap my head around what real time truly means. Imagine I need to use this information for traffic lights management or use this to lift a bridge for a passing boat, it should be done automatically. It's time sensitive or the chaos would be visible. In these cases, what it trully means to be real time?
2022/12/04
[ "https://Stackoverflow.com/questions/74677722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9633446/" ]
First, learn what "real-time" means. Wikipedia: <https://en.wikipedia.org/wiki/Real-time_computing> Understand the terms **"hard" and "soft"** real-time. Understand which aspects of your environment are soft and which require hard real-time. Understand the **response times** that your environment requires. Understand the **time scales**. This does *not* involve *fuzzy terms* like "quick" or "significant" or "accurate". It involves actual quantifiable time spans that depend on your task and its environment, acceptable error rates, ... You did not share any details about your environment. I find it *unlikely* that you even need 30 fps for any application involving a road intersection. You only need enough frame rate so you don't miss objects of interest, and you have fine enough data to track multiple objects with identity without mistaking them for each other. Example: assume a car moving at 200 km/h. If your camera takes a frame every 1/30 second, the car moves 1.85 meters between frames. * How's your motion blur? What's the camera's exposure time? I'd recommend something on the order of a millisecond or better, giving motion blur of 0.05m * How's your tracking? Can it deal with objects "jumping" that far between frames? Does it generate object identity information that is usable for matching (association)?
Real-time refers to the fact that a system is able to process and respond to data as it is received, without any significant delay. In the context of your object detection and tracking script, real-time would mean that the system is able to process and respond to new frames of the video as they are received, without a significant delay. This would allow the system to accurately count the objects in the video in near-real-time as the video is being played. In the case of traffic lights management or lifting a bridge for a passing boat, real-time would mean that the system is able to quickly and accurately process data from sensors and other sources, and use that information to make decisions and take actions in a timely manner. This is important in these scenarios because any significant delay in processing and responding to data could have serious consequences, such as traffic accidents or collisions. Overall, real-time systems are designed to process and respond to data quickly and accurately, in order to support time-sensitive applications and scenarios.
52,900,947
Is it possible to have VSCode always have a particular folder ("Directory A") open, so the files inside can be searched using Ctrl + P? It seems the standard behaviour is that my current "added folder" (i.e. "Directory A") get removed whenever I open a file from a different location ("Directory B"). Closing VSCode and re-opening it always returns me to the last used file (i.e. opening "Directory B" and NOT "Directory A"). How can I force VSCode to always have a certain folder open please? NB, I've looked into "workspaces" but this doesn't help as whenever opening a file not in the workspace, it seems to close the workspace.
2018/10/19
[ "https://Stackoverflow.com/questions/52900947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863415/" ]
Add Directory A to your workspace using `File > Add Folder to Workspace...` Then rather than opening Directory B when you launch VSCode, open the .vscode-workspace file for the workspace that contains both directories. If there are multiple files in your workspace which match the filename you're searching for using CTRL+P, all the matching files will show up.
The solution, at least on linux, is to create a script with the following content (let's call the script `code-standard-path` ): ```sh #!/bin/bash code /path/to/standardDir-or-standardworkspace "$1" ``` Then from `caja` right click on a file : `open with` -> `other application`. Then select the command `code-standard-path` and check `Remember this application for "..." files`. Now everytime you double-click on the specific file from whatever location, vscode will open in that predefined directory or workspace. You can move a bit further and pass the standard path as first argument to the script (e.g. use `code "$1" "$2"`). So on the `open with` menu you provide each time the script like this: `code-standard-path /path/to/standardDir-or-standardworkspace`. This gives you the ability to open a differrent standard path depending on the file you open (e.g. for `.c`, `.java`, `.html`)
52,900,947
Is it possible to have VSCode always have a particular folder ("Directory A") open, so the files inside can be searched using Ctrl + P? It seems the standard behaviour is that my current "added folder" (i.e. "Directory A") get removed whenever I open a file from a different location ("Directory B"). Closing VSCode and re-opening it always returns me to the last used file (i.e. opening "Directory B" and NOT "Directory A"). How can I force VSCode to always have a certain folder open please? NB, I've looked into "workspaces" but this doesn't help as whenever opening a file not in the workspace, it seems to close the workspace.
2018/10/19
[ "https://Stackoverflow.com/questions/52900947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863415/" ]
Add Directory A to your workspace using `File > Add Folder to Workspace...` Then rather than opening Directory B when you launch VSCode, open the .vscode-workspace file for the workspace that contains both directories. If there are multiple files in your workspace which match the filename you're searching for using CTRL+P, all the matching files will show up.
Had the same issue. But there is an easy fix: On the menu bar go to file **File > Preferences > Settings > Window** and **under Restore Windows select** the option **preserve**. This will ALWAYS reopen the last session, no matter if you start VS from shell, desktop shortcut or by opening a file.
45,033,474
I was playing with this example timer and then wanted to see if I could capture/pass data into the timer so I started with a simple message. If I remove the message to timer it ticks accordingly. I started logging other lifecycle methods but I am curious if this is JS thing which I don't think it is versus something in react life cycle. I forked a JS bin [here with ex](http://jsfiddle.net/4Lhnq7a9/) 'code' ``` var Timer = React.createClass({ getInitialState: function() { return {secondsElapsed: 0}; }, tick: function(msg) { console.log('msg is',msg); this.setState({secondsElapsed: this.state.secondsElapsed + 1}); }, componentDidMount: function() { this.interval = setInterval(this.tick('hi'), 1000); }, componentWillUnmount: function() { clearInterval(this.interval); }, render: function() { return ( <div>Seconds Elapsed: {this.state.secondsElapsed}</div> ); } }); React.render(<Timer />, document.getElementById("content")); ```
2017/07/11
[ "https://Stackoverflow.com/questions/45033474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112665/" ]
All you need to do is to change this bit in your code: ``` this.interval = setInterval(() => this.tick('hi'), 1000); ``` Alternatively, you can also send in `this` to the callback: ``` this.interval = setInterval(function(t) {t.tick('hi')}, 1000, this); ``` See the updated fiddle, [**here**](http://jsfiddle.net/4Lhnq7a9/1/). --- [**`setInterval()`**](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) takes (at least) two parameters, the first one is the callback and needs to be a function. You had provided the code directly; that code must be inside a function. > > > ``` > var intervalID = scope.setInterval(func, delay); > > ``` > > **func** > > > A function to be executed every delay milliseconds. The function is not passed any parameters, and no return value is expected. > > >
Change code to: ``` componentDidMount: function() { this.interval = setInterval(()=>this.tick('hi'), 1000); } ```
22,826,357
I'm trying to build a Java Bittorent client. From what I understand after peers handshake with one another they may start sending messages to each other, often sending messages sporadically. Using a DataInputStream connection I can read messages, but if I call a read and nothing is on the stream the peers holds. Is there a way I can tell if something is being sent over the stream? Or should I create a new thread that reads the stream for messages continuously from each peer until the client shuts them down shut down?
2014/04/03
[ "https://Stackoverflow.com/questions/22826357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308453/" ]
you shall add `$(document).ready()` before use JQuery, here is the [doc](http://api.jquery.com/ready/) this is my code modified from yours, it works ``` $(document).ready(function () { $('#submitForm').click(function () { var userEmail = "email"; var userName = "userName"; var userSubject = "UserSubject"; var userMessage = "UserMesssage"; var dataValues = { 'name': userName, 'email': userEmail, 'subject': userSubject, 'message': userMessage }; dataValues = JSON.stringify(dataValues); $.ajax({ type: "POST", url: "WebForm2.aspx/sendForm", data: dataValues, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert("it worked!" + msg.d); } }); }); }); ```
Your `contentType: "application/json; charset=utf-8"` is expecting `json`, but in C# you are returning string in the function. You should return `json` Here change your code behind function as follows: ``` [WebMethod] public static String sendForm(string name, string email, string subject, string message) { var mydatedata = DateTime.Now.ToString(); return JSON.stringify({ mydate: mydatedata}); } ```
66,520,763
I tried some of the solutions posted earlier in similar questions but none of them seem to work for me. My code is in **Python 3.8** and I am using the **latest version of VSCode**. Thanks.
2021/03/07
[ "https://Stackoverflow.com/questions/66520763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15166885/" ]
When running python code in VS Code, it executes the running command in the VS Code internal terminal ( `TERMINAL` ) by default. It is a terminal that allows user interaction, but "`OUTPUT`" is an output terminal, which cannot receive user input. For how to make the output display in "`OUTPUT`" in VS Code: Please use the "`Code Runner`" extension in VS Code, which uses "`OUTPUT`" by default: [![enter image description here](https://i.stack.imgur.com/E5VRR.png)](https://i.stack.imgur.com/E5VRR.png) In addition, if you want to use relatively clean output, you could also use "`DEBUG CONSOLE`". Please use in "[launch.json](https://code.visualstudio.com/docs/python/debugging#_initialize-configurations)": `"console": "internalConsole",` then click `F5` to debug the code: [![enter image description here](https://i.stack.imgur.com/yjtP2.png)](https://i.stack.imgur.com/yjtP2.png)
Make sure you've the code runner extension installed. If yes then,[enter image description here](https://i.stack.imgur.com/Y2jvo.png) Go to settings , 1.search Terminal 2. scroll to the last line 3. uncheck code run in terminal
66,520,763
I tried some of the solutions posted earlier in similar questions but none of them seem to work for me. My code is in **Python 3.8** and I am using the **latest version of VSCode**. Thanks.
2021/03/07
[ "https://Stackoverflow.com/questions/66520763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15166885/" ]
When running python code in VS Code, it executes the running command in the VS Code internal terminal ( `TERMINAL` ) by default. It is a terminal that allows user interaction, but "`OUTPUT`" is an output terminal, which cannot receive user input. For how to make the output display in "`OUTPUT`" in VS Code: Please use the "`Code Runner`" extension in VS Code, which uses "`OUTPUT`" by default: [![enter image description here](https://i.stack.imgur.com/E5VRR.png)](https://i.stack.imgur.com/E5VRR.png) In addition, if you want to use relatively clean output, you could also use "`DEBUG CONSOLE`". Please use in "[launch.json](https://code.visualstudio.com/docs/python/debugging#_initialize-configurations)": `"console": "internalConsole",` then click `F5` to debug the code: [![enter image description here](https://i.stack.imgur.com/yjtP2.png)](https://i.stack.imgur.com/yjtP2.png)
Install "Code Runner" extension. * VS Code -> Extensions (Ctrl+Shift+X) in the most left panel -> text box "Search Extensions in Marketplace" -> Code Runner -> Install Setting up Code Runner * VS Code -> File -> Preferences -> Settings (Ctrl+,) -> text box "Search settings" -> Code Runner -> ensure that checkbox for "Code-runner: Run In Terminal" is unchecked. Running Python Scripts * Prepare a Python code you want to run -> Press Ctrl+Alt+N to run the code via Code Runner. * If the shortcut Ctrl+Alt+N is already taken e.g. by another software, you can change the shortcut + File -> Preferences -> Keyboard Shortcuts (Ctrl+K Ctrl+S) -> search: Code Runner -> Run Code If you want to clear previous output (from OUTPUT window) -> File -> Preferences -> Settings (Ctrl+,) -> text box "Search settings" -> Code Runner -> ensure that checkbox for "Code-runner: Clear Previous Output" is checked.
66,520,763
I tried some of the solutions posted earlier in similar questions but none of them seem to work for me. My code is in **Python 3.8** and I am using the **latest version of VSCode**. Thanks.
2021/03/07
[ "https://Stackoverflow.com/questions/66520763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15166885/" ]
Make sure you've the code runner extension installed. If yes then,[enter image description here](https://i.stack.imgur.com/Y2jvo.png) Go to settings , 1.search Terminal 2. scroll to the last line 3. uncheck code run in terminal
Install "Code Runner" extension. * VS Code -> Extensions (Ctrl+Shift+X) in the most left panel -> text box "Search Extensions in Marketplace" -> Code Runner -> Install Setting up Code Runner * VS Code -> File -> Preferences -> Settings (Ctrl+,) -> text box "Search settings" -> Code Runner -> ensure that checkbox for "Code-runner: Run In Terminal" is unchecked. Running Python Scripts * Prepare a Python code you want to run -> Press Ctrl+Alt+N to run the code via Code Runner. * If the shortcut Ctrl+Alt+N is already taken e.g. by another software, you can change the shortcut + File -> Preferences -> Keyboard Shortcuts (Ctrl+K Ctrl+S) -> search: Code Runner -> Run Code If you want to clear previous output (from OUTPUT window) -> File -> Preferences -> Settings (Ctrl+,) -> text box "Search settings" -> Code Runner -> ensure that checkbox for "Code-runner: Clear Previous Output" is checked.
14,235
I need some advice on what file system to use for my new 1TB media server hosted on my Linux box. I have a few requirements: 1. Needs to be shareable to a different Windows machine (not dual booting, totally different box). I see that there might at least be options to do this with ext3, and as I think this will be a rather rare scenario, I'm able to live with this. 2. Definitely needs to be able to be accessed via Samba on my Xbox running XBMC (and sharing with an Xbox 360 might be in its future). 3. Needs to allow file size greater than 4GB. 4. Needs to be shareable with any future media servers/front-ends I build (all would be running a Linux variant such as Boxee, XBMC, Myth\*). I'm guessing Fat32 is out due to the file size requirement, and while I've used NTFS before, I'd prefer something native to Linux. I'm open to just about anything, thanks.
2009/05/29
[ "https://serverfault.com/questions/14235", "https://serverfault.com", "https://serverfault.com/users/145754/" ]
Given all access to the filesystem from non-Linux systems will be through an abstraction layer, pick whatever you want! I'd suggest your distro's default (ext3 probably). Media storage has no special needs in terms of speed or reliability, so you'll just add unnecessary complexity picking an exotic filesystem. In terms of the specific use cases you mentioned: * Vista includes an NFS client, and of course you can share the drive via Samba too. If you mean direct physical access to the drive, I would change my recommendation for the filesystem to NTFS, as it has the best cross platform compatibility between Windows and Linux. * Any filesystem works here - Samba abstracts that away from what the client sees. * Just don't pick FAT32! * Any current, non-exotic filesystem will be fine here. Even the 'exotic' filesystems like XFS/JFS will be supported in the kernel for years to come.
Samba should be capable of communicating with your windows boxen and myth frontends, but it does not care what filesystem it's data is stored on as long as it can be read by the kernel. I would pick what ever is the default for distro that you are installing. Ext3 can definately accomodate files > 4GB. If you are going to be storing large files primarily, there are some tuning parameters you can set to make this more efficient.
14,235
I need some advice on what file system to use for my new 1TB media server hosted on my Linux box. I have a few requirements: 1. Needs to be shareable to a different Windows machine (not dual booting, totally different box). I see that there might at least be options to do this with ext3, and as I think this will be a rather rare scenario, I'm able to live with this. 2. Definitely needs to be able to be accessed via Samba on my Xbox running XBMC (and sharing with an Xbox 360 might be in its future). 3. Needs to allow file size greater than 4GB. 4. Needs to be shareable with any future media servers/front-ends I build (all would be running a Linux variant such as Boxee, XBMC, Myth\*). I'm guessing Fat32 is out due to the file size requirement, and while I've used NTFS before, I'd prefer something native to Linux. I'm open to just about anything, thanks.
2009/05/29
[ "https://serverfault.com/questions/14235", "https://serverfault.com", "https://serverfault.com/users/145754/" ]
Samba should be capable of communicating with your windows boxen and myth frontends, but it does not care what filesystem it's data is stored on as long as it can be read by the kernel. I would pick what ever is the default for distro that you are installing. Ext3 can definately accomodate files > 4GB. If you are going to be storing large files primarily, there are some tuning parameters you can set to make this more efficient.
For a filesystem that will have mostly large files, I would recommend using XFS. It has great performance for large file sizes and is very mature. JFS is worth mentioning, as well and has similar performance to XFS and is just as mature. However, depending on your distro, it might do you well to put the filesystem on top of LVM so that you can expand your storage seamlessly. Going one step further, I'd put the filesystem on LVM on top of a RAID array. This way you gain fault tolerance and performance while maintaining your ability to scale. Another option for direct storage (in addition to Alex's NFS recommendation), is to use iSCSI. I export storage to my Windows and Linux boxes via iSCSI using iSCSI Enterprise Target. Failing the need for direct access, samba will do the trick just fine. Just don't export over samba storage that you've imported over NFS; you'll have file locking problems.
14,235
I need some advice on what file system to use for my new 1TB media server hosted on my Linux box. I have a few requirements: 1. Needs to be shareable to a different Windows machine (not dual booting, totally different box). I see that there might at least be options to do this with ext3, and as I think this will be a rather rare scenario, I'm able to live with this. 2. Definitely needs to be able to be accessed via Samba on my Xbox running XBMC (and sharing with an Xbox 360 might be in its future). 3. Needs to allow file size greater than 4GB. 4. Needs to be shareable with any future media servers/front-ends I build (all would be running a Linux variant such as Boxee, XBMC, Myth\*). I'm guessing Fat32 is out due to the file size requirement, and while I've used NTFS before, I'd prefer something native to Linux. I'm open to just about anything, thanks.
2009/05/29
[ "https://serverfault.com/questions/14235", "https://serverfault.com", "https://serverfault.com/users/145754/" ]
Given all access to the filesystem from non-Linux systems will be through an abstraction layer, pick whatever you want! I'd suggest your distro's default (ext3 probably). Media storage has no special needs in terms of speed or reliability, so you'll just add unnecessary complexity picking an exotic filesystem. In terms of the specific use cases you mentioned: * Vista includes an NFS client, and of course you can share the drive via Samba too. If you mean direct physical access to the drive, I would change my recommendation for the filesystem to NTFS, as it has the best cross platform compatibility between Windows and Linux. * Any filesystem works here - Samba abstracts that away from what the client sees. * Just don't pick FAT32! * Any current, non-exotic filesystem will be fine here. Even the 'exotic' filesystems like XFS/JFS will be supported in the kernel for years to come.
For a filesystem that will have mostly large files, I would recommend using XFS. It has great performance for large file sizes and is very mature. JFS is worth mentioning, as well and has similar performance to XFS and is just as mature. However, depending on your distro, it might do you well to put the filesystem on top of LVM so that you can expand your storage seamlessly. Going one step further, I'd put the filesystem on LVM on top of a RAID array. This way you gain fault tolerance and performance while maintaining your ability to scale. Another option for direct storage (in addition to Alex's NFS recommendation), is to use iSCSI. I export storage to my Windows and Linux boxes via iSCSI using iSCSI Enterprise Target. Failing the need for direct access, samba will do the trick just fine. Just don't export over samba storage that you've imported over NFS; you'll have file locking problems.
14,235
I need some advice on what file system to use for my new 1TB media server hosted on my Linux box. I have a few requirements: 1. Needs to be shareable to a different Windows machine (not dual booting, totally different box). I see that there might at least be options to do this with ext3, and as I think this will be a rather rare scenario, I'm able to live with this. 2. Definitely needs to be able to be accessed via Samba on my Xbox running XBMC (and sharing with an Xbox 360 might be in its future). 3. Needs to allow file size greater than 4GB. 4. Needs to be shareable with any future media servers/front-ends I build (all would be running a Linux variant such as Boxee, XBMC, Myth\*). I'm guessing Fat32 is out due to the file size requirement, and while I've used NTFS before, I'd prefer something native to Linux. I'm open to just about anything, thanks.
2009/05/29
[ "https://serverfault.com/questions/14235", "https://serverfault.com", "https://serverfault.com/users/145754/" ]
Given all access to the filesystem from non-Linux systems will be through an abstraction layer, pick whatever you want! I'd suggest your distro's default (ext3 probably). Media storage has no special needs in terms of speed or reliability, so you'll just add unnecessary complexity picking an exotic filesystem. In terms of the specific use cases you mentioned: * Vista includes an NFS client, and of course you can share the drive via Samba too. If you mean direct physical access to the drive, I would change my recommendation for the filesystem to NTFS, as it has the best cross platform compatibility between Windows and Linux. * Any filesystem works here - Samba abstracts that away from what the client sees. * Just don't pick FAT32! * Any current, non-exotic filesystem will be fine here. Even the 'exotic' filesystems like XFS/JFS will be supported in the kernel for years to come.
I use XFS on my MythTV server, and it works very well. I've also shared out certain directories by way of Samba so my Windows workstations can get access to it. I have a script that transcodes shows into a format usable on my iriver clix2, which dumps to a directory I map to from my Windows laptop and transfer to the media player. One of the nicer things about using XFS for a media server is that XFS has a defragger, as keeping those very large files sequential on that undoubtedly SATA drive is a good idea. A suggestion that helped me out, is use the "allocsize=256m" mount option for XFS. This tells the kernel to allocate 256MB hunks of space when writing a file. As SD shows are taking 2.2GB/hour on my rig, this reduces frag significantly. The few HD shows I've managed to record are on the order of 15GB/hour, and my file-system hasn't blinked at it. It'd blink even less if I were running 64-bit. XFS support is relatively new in the land of Linux, but by 2.6.30 it has been in there a long time. I haven't had any corruption problems with it at home or at work. It isn't so hot for massively random I/O on SATA drives, such as the load VMWare Workstation puts on (ahem), but for sequential access it smokes. I'm actively in the planning stages of setting up another media server in the back room to supplement the storage on the encoder box. This will also be XFS, but shared out over NFS to the MythTV box for minimal network overhead. It *might* go ext4, but I haven't done anything with that FS yet.
14,235
I need some advice on what file system to use for my new 1TB media server hosted on my Linux box. I have a few requirements: 1. Needs to be shareable to a different Windows machine (not dual booting, totally different box). I see that there might at least be options to do this with ext3, and as I think this will be a rather rare scenario, I'm able to live with this. 2. Definitely needs to be able to be accessed via Samba on my Xbox running XBMC (and sharing with an Xbox 360 might be in its future). 3. Needs to allow file size greater than 4GB. 4. Needs to be shareable with any future media servers/front-ends I build (all would be running a Linux variant such as Boxee, XBMC, Myth\*). I'm guessing Fat32 is out due to the file size requirement, and while I've used NTFS before, I'd prefer something native to Linux. I'm open to just about anything, thanks.
2009/05/29
[ "https://serverfault.com/questions/14235", "https://serverfault.com", "https://serverfault.com/users/145754/" ]
Given all access to the filesystem from non-Linux systems will be through an abstraction layer, pick whatever you want! I'd suggest your distro's default (ext3 probably). Media storage has no special needs in terms of speed or reliability, so you'll just add unnecessary complexity picking an exotic filesystem. In terms of the specific use cases you mentioned: * Vista includes an NFS client, and of course you can share the drive via Samba too. If you mean direct physical access to the drive, I would change my recommendation for the filesystem to NTFS, as it has the best cross platform compatibility between Windows and Linux. * Any filesystem works here - Samba abstracts that away from what the client sees. * Just don't pick FAT32! * Any current, non-exotic filesystem will be fine here. Even the 'exotic' filesystems like XFS/JFS will be supported in the kernel for years to come.
XFS is best for storing video because it's very stable and has excellent large file support. It's not even exotic anymore. Sharing (with another computer) is unrelated to the filesystem. Basically, if you're sharing with windows - choose Samba because it's easiest. While Samba works fine, if XBMC is your focus you might also like to consider UPNP (DLNA). DLNA is designed EXACTLY for sharing media across a network, there are several choices for linux - like mediatomb or ushare. mediatomb.cc ushare.geexbox.org Summary: Use XFS for the media partition, and Samba or DLNA for sharing. / Richy
14,235
I need some advice on what file system to use for my new 1TB media server hosted on my Linux box. I have a few requirements: 1. Needs to be shareable to a different Windows machine (not dual booting, totally different box). I see that there might at least be options to do this with ext3, and as I think this will be a rather rare scenario, I'm able to live with this. 2. Definitely needs to be able to be accessed via Samba on my Xbox running XBMC (and sharing with an Xbox 360 might be in its future). 3. Needs to allow file size greater than 4GB. 4. Needs to be shareable with any future media servers/front-ends I build (all would be running a Linux variant such as Boxee, XBMC, Myth\*). I'm guessing Fat32 is out due to the file size requirement, and while I've used NTFS before, I'd prefer something native to Linux. I'm open to just about anything, thanks.
2009/05/29
[ "https://serverfault.com/questions/14235", "https://serverfault.com", "https://serverfault.com/users/145754/" ]
I use XFS on my MythTV server, and it works very well. I've also shared out certain directories by way of Samba so my Windows workstations can get access to it. I have a script that transcodes shows into a format usable on my iriver clix2, which dumps to a directory I map to from my Windows laptop and transfer to the media player. One of the nicer things about using XFS for a media server is that XFS has a defragger, as keeping those very large files sequential on that undoubtedly SATA drive is a good idea. A suggestion that helped me out, is use the "allocsize=256m" mount option for XFS. This tells the kernel to allocate 256MB hunks of space when writing a file. As SD shows are taking 2.2GB/hour on my rig, this reduces frag significantly. The few HD shows I've managed to record are on the order of 15GB/hour, and my file-system hasn't blinked at it. It'd blink even less if I were running 64-bit. XFS support is relatively new in the land of Linux, but by 2.6.30 it has been in there a long time. I haven't had any corruption problems with it at home or at work. It isn't so hot for massively random I/O on SATA drives, such as the load VMWare Workstation puts on (ahem), but for sequential access it smokes. I'm actively in the planning stages of setting up another media server in the back room to supplement the storage on the encoder box. This will also be XFS, but shared out over NFS to the MythTV box for minimal network overhead. It *might* go ext4, but I haven't done anything with that FS yet.
For a filesystem that will have mostly large files, I would recommend using XFS. It has great performance for large file sizes and is very mature. JFS is worth mentioning, as well and has similar performance to XFS and is just as mature. However, depending on your distro, it might do you well to put the filesystem on top of LVM so that you can expand your storage seamlessly. Going one step further, I'd put the filesystem on LVM on top of a RAID array. This way you gain fault tolerance and performance while maintaining your ability to scale. Another option for direct storage (in addition to Alex's NFS recommendation), is to use iSCSI. I export storage to my Windows and Linux boxes via iSCSI using iSCSI Enterprise Target. Failing the need for direct access, samba will do the trick just fine. Just don't export over samba storage that you've imported over NFS; you'll have file locking problems.
14,235
I need some advice on what file system to use for my new 1TB media server hosted on my Linux box. I have a few requirements: 1. Needs to be shareable to a different Windows machine (not dual booting, totally different box). I see that there might at least be options to do this with ext3, and as I think this will be a rather rare scenario, I'm able to live with this. 2. Definitely needs to be able to be accessed via Samba on my Xbox running XBMC (and sharing with an Xbox 360 might be in its future). 3. Needs to allow file size greater than 4GB. 4. Needs to be shareable with any future media servers/front-ends I build (all would be running a Linux variant such as Boxee, XBMC, Myth\*). I'm guessing Fat32 is out due to the file size requirement, and while I've used NTFS before, I'd prefer something native to Linux. I'm open to just about anything, thanks.
2009/05/29
[ "https://serverfault.com/questions/14235", "https://serverfault.com", "https://serverfault.com/users/145754/" ]
XFS is best for storing video because it's very stable and has excellent large file support. It's not even exotic anymore. Sharing (with another computer) is unrelated to the filesystem. Basically, if you're sharing with windows - choose Samba because it's easiest. While Samba works fine, if XBMC is your focus you might also like to consider UPNP (DLNA). DLNA is designed EXACTLY for sharing media across a network, there are several choices for linux - like mediatomb or ushare. mediatomb.cc ushare.geexbox.org Summary: Use XFS for the media partition, and Samba or DLNA for sharing. / Richy
For a filesystem that will have mostly large files, I would recommend using XFS. It has great performance for large file sizes and is very mature. JFS is worth mentioning, as well and has similar performance to XFS and is just as mature. However, depending on your distro, it might do you well to put the filesystem on top of LVM so that you can expand your storage seamlessly. Going one step further, I'd put the filesystem on LVM on top of a RAID array. This way you gain fault tolerance and performance while maintaining your ability to scale. Another option for direct storage (in addition to Alex's NFS recommendation), is to use iSCSI. I export storage to my Windows and Linux boxes via iSCSI using iSCSI Enterprise Target. Failing the need for direct access, samba will do the trick just fine. Just don't export over samba storage that you've imported over NFS; you'll have file locking problems.
18,105,399
I have the following code: ``` List<int> moneys = new List<int>(); Console.WriteLine("Please enter the cost of your choice"); int money = int.Parse(Console.ReadLine()); moneys.Add(money); ``` From this if you enter text then the program stops working and an Unhandled exception message appears. I was wondering how you would handle the exception, if it is even possible so that the program doesn't stop working?
2013/08/07
[ "https://Stackoverflow.com/questions/18105399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657462/" ]
``` int money ; bool pass = int.TryParse(Console.ReadLine(), out money); if(pass) moneys.Add(money); ```
Implement a [`try-catch`](http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.90%29.aspx) block or use [`Int32.TryParse`](http://msdn.microsoft.com/en-us/library/f02979c7.aspx).
18,105,399
I have the following code: ``` List<int> moneys = new List<int>(); Console.WriteLine("Please enter the cost of your choice"); int money = int.Parse(Console.ReadLine()); moneys.Add(money); ``` From this if you enter text then the program stops working and an Unhandled exception message appears. I was wondering how you would handle the exception, if it is even possible so that the program doesn't stop working?
2013/08/07
[ "https://Stackoverflow.com/questions/18105399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657462/" ]
``` int money ; bool pass = int.TryParse(Console.ReadLine(), out money); if(pass) moneys.Add(money); ```
To handle the exception after it is thrown, use a try/catch block. ``` try { //input } catch(Exception ex) { //try again } ``` You can also handle it beforehand by using TryParse, and checking if int is null.
18,105,399
I have the following code: ``` List<int> moneys = new List<int>(); Console.WriteLine("Please enter the cost of your choice"); int money = int.Parse(Console.ReadLine()); moneys.Add(money); ``` From this if you enter text then the program stops working and an Unhandled exception message appears. I was wondering how you would handle the exception, if it is even possible so that the program doesn't stop working?
2013/08/07
[ "https://Stackoverflow.com/questions/18105399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657462/" ]
You should use [TryParse](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method. it will not throw an exception if input is not valid. do this ``` int money; if(int.TryParse(Console.ReadLine(), out money)) moneys.Add(money); ```
``` int money ; bool pass = int.TryParse(Console.ReadLine(), out money); if(pass) moneys.Add(money); ```
18,105,399
I have the following code: ``` List<int> moneys = new List<int>(); Console.WriteLine("Please enter the cost of your choice"); int money = int.Parse(Console.ReadLine()); moneys.Add(money); ``` From this if you enter text then the program stops working and an Unhandled exception message appears. I was wondering how you would handle the exception, if it is even possible so that the program doesn't stop working?
2013/08/07
[ "https://Stackoverflow.com/questions/18105399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657462/" ]
``` int money ; bool pass = int.TryParse(Console.ReadLine(), out money); if(pass) moneys.Add(money); ```
`int.Parse` is ment to throw an exception when it fails to parse the string. You have 2 choices: 1) Use Try/Catch to handle the exception ``` try { int money = int.Parse(Console.ReadLine()); moneys.Add(money); } catch { //Did not parse, do something } ``` This option allows more flexibility in dealing with different type of errors. You can extend the catch block to split the 3 possible mistakes in the input string and another default catch block to handle other errors: ``` } catch (ArgumentNullException e) { //The Console.ReadLine() returned Null } catch (FormatException e) { //The input did not match a valid number format } catch (OverflowException e) { //The input exceded the maximum value of a Int } catch (Exception e) { //Other unexpected exception (Mostlikely unrelated to the parsing itself) } ``` 2) Use `int.TryParse` which returns `true` or `false` depending on wether the string was parsed or not and sends the result into the variable specified in the 2nd paramater (with the `out`keyword) ``` int money; if(int.TryParse(Console.ReadLine(), out money)) moneys.Add(money); else //Did not parse, do something ```
18,105,399
I have the following code: ``` List<int> moneys = new List<int>(); Console.WriteLine("Please enter the cost of your choice"); int money = int.Parse(Console.ReadLine()); moneys.Add(money); ``` From this if you enter text then the program stops working and an Unhandled exception message appears. I was wondering how you would handle the exception, if it is even possible so that the program doesn't stop working?
2013/08/07
[ "https://Stackoverflow.com/questions/18105399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657462/" ]
You should use [TryParse](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method. it will not throw an exception if input is not valid. do this ``` int money; if(int.TryParse(Console.ReadLine(), out money)) moneys.Add(money); ```
Implement a [`try-catch`](http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.90%29.aspx) block or use [`Int32.TryParse`](http://msdn.microsoft.com/en-us/library/f02979c7.aspx).
18,105,399
I have the following code: ``` List<int> moneys = new List<int>(); Console.WriteLine("Please enter the cost of your choice"); int money = int.Parse(Console.ReadLine()); moneys.Add(money); ``` From this if you enter text then the program stops working and an Unhandled exception message appears. I was wondering how you would handle the exception, if it is even possible so that the program doesn't stop working?
2013/08/07
[ "https://Stackoverflow.com/questions/18105399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657462/" ]
You should use [TryParse](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method. it will not throw an exception if input is not valid. do this ``` int money; if(int.TryParse(Console.ReadLine(), out money)) moneys.Add(money); ```
To handle the exception after it is thrown, use a try/catch block. ``` try { //input } catch(Exception ex) { //try again } ``` You can also handle it beforehand by using TryParse, and checking if int is null.
18,105,399
I have the following code: ``` List<int> moneys = new List<int>(); Console.WriteLine("Please enter the cost of your choice"); int money = int.Parse(Console.ReadLine()); moneys.Add(money); ``` From this if you enter text then the program stops working and an Unhandled exception message appears. I was wondering how you would handle the exception, if it is even possible so that the program doesn't stop working?
2013/08/07
[ "https://Stackoverflow.com/questions/18105399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657462/" ]
You should use [TryParse](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method. it will not throw an exception if input is not valid. do this ``` int money; if(int.TryParse(Console.ReadLine(), out money)) moneys.Add(money); ```
`int.Parse` is ment to throw an exception when it fails to parse the string. You have 2 choices: 1) Use Try/Catch to handle the exception ``` try { int money = int.Parse(Console.ReadLine()); moneys.Add(money); } catch { //Did not parse, do something } ``` This option allows more flexibility in dealing with different type of errors. You can extend the catch block to split the 3 possible mistakes in the input string and another default catch block to handle other errors: ``` } catch (ArgumentNullException e) { //The Console.ReadLine() returned Null } catch (FormatException e) { //The input did not match a valid number format } catch (OverflowException e) { //The input exceded the maximum value of a Int } catch (Exception e) { //Other unexpected exception (Mostlikely unrelated to the parsing itself) } ``` 2) Use `int.TryParse` which returns `true` or `false` depending on wether the string was parsed or not and sends the result into the variable specified in the 2nd paramater (with the `out`keyword) ``` int money; if(int.TryParse(Console.ReadLine(), out money)) moneys.Add(money); else //Did not parse, do something ```
1,053,531
Xubuntu 18.04, `4.15.0-24-generic`, ThinkPad T430. Uses Intel HD iGPU graphics (nvidia dGPU disabled in BIOS). Recently started having this issue with a slow boot, where the boot process hangs on a black screen for an indefinite period of time before finally displaying the normal login splash screen. Process looks like: * OEM Bios select screen * blank, black screen (< 1 sec) * Blue Xubuntu title splash (< 2 sec) * Some grub printout (< 1 sec) * A black screen that has a blinking white cursor block (< 1 sec) * A blank, black screen with nothing on it (approx. 10 sec) * Finally, login splash screen No idea why it started doing this. Was working fine before. The only thing I've noticed, which may be a red herring or irrelevant, is that there have been a bunch of updates to the `mesa` package lately when I `apt update` and upgrade. Most other posts I've seen related to a hanging black screen on boot are either ancient (12.04) or unrelated (stuck on grub, or the flashing-cursor screen instead of blank). Though it seems like most of those posts are related to editing the grub file (`/etc/default/grub` line `GRUB_CMDLINE_LINUX_DEFAULT`). Any ideas? For reference, my grub file reads: ``` GRUB_DEFAULT=0 GRUB_HIDDEN_TIMEOUT=0 GRUB_HIDDEN_TIMEOUT_QUIET=true GRUB_TIMEOUT=10 GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian` GRUB_CMDLINE_LINUX_DEFAULT="quiet splash nouveau.runpm=0" GRUB_CMDLINE_LINUX="" ``` and the relevant output of `lscpi -k` ``` lspci -k 00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09) Subsystem: Lenovo 3rd Gen Core processor Graphics Controller Kernel driver in use: i915 Kernel modules: i915 ``` Things I've tried: ================== * change `GRUB_CMDLINE_LINUX_DEFAULT` to `"quiet splash` instead of `"quiet splash nouveau.runpm=0"` * `GRUB_TIMEOUT=0` instead of `10` * updating `mesa`, `xserver-xorg-video-intel` packages, both already installed and current * updating kernel (was already at latest, `4.15.0-24-generic`) Update: ======= Unfortunately was not able to figure out the source of the issue. I tried nearly every permutation of grub settings, but that did not end up changing the hanging boot issue. My guess it is probably related to the `4.15.0-24-generic`. Decided to reinstall Xubuntu 16.04 for this issue and a [few more](https://askubuntu.com/q/1051270/601020) I've had with 18.04. If anyone else is experiencing this hanging boot issue and solved the issue, please provide your solution for others (and possibly me if I decide to roll the dice again when Xubuntu 18.04.1 drops).
2018/07/09
[ "https://askubuntu.com/questions/1053531", "https://askubuntu.com", "https://askubuntu.com/users/601020/" ]
The Eclipse snap package from the default Ubuntu repositories is perfect for Java programming because it is bundled with a Java development environment. To install it open the terminal and type: ``` sudo snap install eclipse --classic ``` This command will install the latest Photon Release 4.8 version of Eclipse IDE for Java Developers which was updated 8 days ago. Eclipse changed its codename policy so that Eclipse releases from September 2018 and onward are named after the year and month of the release date, for example Eclipse 2020-06. This naming scheme also applies to the eclipse snap package. Photon JDT supports Java 9 completely: * The Eclipse compiler for Java (ECJ) implements all the new Java 9 language enhancements. * Updated significant features to support Java Modules, such as compiler, search and many editor features.
Though I always prefer packages from the Ubuntu distro, I make an exception for Eclipse because it (a) is trivial to install, (b) must be installed as user (no root required or recommended), and (c) it manages its own updates and plugins very well - including rollbacks, etc. The instructions below work for all Eclipse IDEs (Java, C/C++, Web, PHP, etc). 1. Install the JDK ``` sudo apt install default-jdk ``` 2. Download the latest Eclipse installer from [eclipse.org](https://www.eclipse.org/downloads/). Currently this is [Eclipse Photon](https://www.eclipse.org/downloads/download.php?file=/oomph/epp/photon/R/eclipse-inst-linux64.tar.gz). 3. Unpack it in a directory of your choice ``` mkdir -p ~/eclipse/installer tar -C ~/eclipse/installer -xzf ~/Downloads/eclipse-inst-linux64.tar.gz ``` 4. Run the installer ``` cd ~/eclipse/installer ./eclipse-inst ``` 5. Pick your IDE and follow the prompts When done, start your IDE with the `eclipse` script in the directory `eclipse` underneath where you installed the IDE. To **uninstall** any Eclipse IDE, simply `rm -r` its installation directory. If you are obsessive about kruft pollution then also `rm -rf ~/.eclipse`.
4,982,884
I am using a line like this: ``` Array stringArray = Array.CreateInstance(typeof(String), 2, 2); ``` to consume a method that returns a 2D System.Array with my **stringArray** variable. However stringArray = MyClassInstance.Work(...,... ...); is not filled with the return array of that function. How should I define my collection variable so that it can be assigned to the return value of a method which returns a 2D System.Array string array value? Thank you
2011/02/13
[ "https://Stackoverflow.com/questions/4982884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516512/" ]
`Array.CreateInstance` returns an `Array`, without its dimension and length specified(but anyway it's an `System.Array` which is the base class of all arrays in C#). In most circumstances a return array from a method is more like: ``` public string[] MyMethod() { } public int[,] Another(int something) { } string[] theStringResult = MyMethod(); int[,] theIntResult = Another(1); ```
On your 2D-Array: ----------------- ``` Array.CreateInstance(typeof(String), 2, 2); ``` This returns a `string[,]` cast to `Array`. It's identical to `(Array)(new string[2,2])`. So you can cast it to `string[,]` if you want. But why do you want to use that anyways? Can't you just use a `string[,]` instead? Don't you know that the element type is `string` at compile-time? Perhaps make in a generic parameter. On your overserved problem: --------------------------- > > However stringArray = MyClassInstance.Work(...,... ...); is not filled with the return array of that function. > > > We can't help you with that part of the problem unless you post the code where it happens. It seems like the MyClassInstance.Work doesn't return the array instance you created. But unless you show the code with the bug I can't tell you where it is.
18,148,079
Is there any way to redirect (push or perform segue etc.) to initial view controller aka rootViewController from `appdelegate` class? I am using `stroryboard` btw. Any answers are appreciated. **UP.** I am not using navigation controller.
2013/08/09
[ "https://Stackoverflow.com/questions/18148079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679671/" ]
``` UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIWindow *window = [[[UIApplication sharedApplication] delegate] window]; window.rootViewController = [storyboard instantiateInitialViewController]; ```
I suggest nesting all your navigation stack under a `UINavigationController`, then it would be as easy as invoking the `popToRootViewControllerAnimated:` method.
18,148,079
Is there any way to redirect (push or perform segue etc.) to initial view controller aka rootViewController from `appdelegate` class? I am using `stroryboard` btw. Any answers are appreciated. **UP.** I am not using navigation controller.
2013/08/09
[ "https://Stackoverflow.com/questions/18148079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679671/" ]
``` UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIWindow *window = [[[UIApplication sharedApplication] delegate] window]; window.rootViewController = [storyboard instantiateInitialViewController]; ```
UINavigationController popToRootViewController methods takes you there, if you're using UINav controller. Other way you can try out: self.window.rootViewController is a reference that might useful.
18,148,079
Is there any way to redirect (push or perform segue etc.) to initial view controller aka rootViewController from `appdelegate` class? I am using `stroryboard` btw. Any answers are appreciated. **UP.** I am not using navigation controller.
2013/08/09
[ "https://Stackoverflow.com/questions/18148079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679671/" ]
``` UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIWindow *window = [[[UIApplication sharedApplication] delegate] window]; window.rootViewController = [storyboard instantiateInitialViewController]; ```
By Using Swift 4.2 ``` let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let window: UIWindow? = (UIApplication.shared.delegate?.window)! window?.rootViewController = mainStoryboard.instantiateInitialViewController() ``` Working Perfect...
36,805,071
I tried the following code in Python 3.5.1: ``` >>> f = {x: (lambda y: x) for x in range(10)} >>> f[5](3) 9 ``` It's obvious that this should return `5`. I don't understand where the other value comes from, and I wasn't able to find anything. It seems like it's something related to reference - it always returns the answer of `f[9]`, which is the last function assigned. What's the error here, and how should this be done so that it works properly?
2016/04/23
[ "https://Stackoverflow.com/questions/36805071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5305568/" ]
**Python scoping is lexical**. A closure will refer to the name and scope of the variable, not the actual object/value of the variable. What happens is that each lambda is capturing the variable `x` *not* the value of `x`. At the end of the loop the variable `x` is bound to 9, therefore **every lambda will refer to this `x` whose value is 9.** Why @ChrisP's answer works: > > `make_func` forces the value of `x` to be evaluated (as it is passed > into a function). Thus, the lambda is made with value of `x` currently > and we avoid the above scoping issue. > > > ``` def make_func(x): return lambda y: x f = {x: make_func(x) for x in range(10)} ```
The following should work: ``` def make_func(x): return lambda y: x f = {x: make_func(x) for x in range(10)} ``` The `x` in your code ends up referring to the last `x` value, which is `9`, but in mine it refers to the `x` in the function scope.
58,905,569
I want to find the largest and second-largest number in the array. I can find the largest but second largest becomes same as largest and don't know why ``` int main() { int number[10]; cout<<"enter 10 numbers\n"; for (int i =0;i<=9;++i){ cin>>number[i]; } int larger2=number[0],larger=number[0]; for(int a=0;a<=9;++a){ if(number[a]>larger) { larger=number[a]; } } for(int b=0;b<=9;++b){ if( number[b]>larger2 && larger>larger2 ){ larger2=number[b]; } } cout<<"larger "<<larger<<endl; cout<<"larger 2 "<<larger2<<endl; return 0; } ```
2019/11/17
[ "https://Stackoverflow.com/questions/58905569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would modify your second evaluating loop to this: As you have not correctly assigned larger2 in at least one iteration, so you should not use it for comparisons. (ie Do not do this `larger>larger2`) ``` for(int b=0;b<=9;++b){ if( number[b]>larger2 && larger>number[b]){ larger2=number[b]; } } ```
Have a look at this (this works only if there are at least 2 element in the array, otherwise `number[1]` will produce a segmentation fault): ```cpp int main() { int number[10]; cout<<"enter 10 numbers\n"; for (int i =0;i<=9;++i){ cin>>number[i]; } int larger2=min(number[0],number[1]) ,larger=max(number[1],number[0]); for(int a=0;a<=9;++a){ if(number[a]>larger2) { if(number[a]>larger1){ larger2=larger; larger = number[a]; } else larger2=number[a]; } } cout<<"larger "<<larger<<endl; cout<<"larger 2 "<<larger2<<endl; return 0; } ``` The explanation is this: 1. take the biggest from the first 2 number and assign to `larger` and the smallest to `larger2` 2. loop through the array and if the current number is bigger than `larger2` we need to store that value in `larger` if it's the bigger, and so the second bigger will be the olfd value of `larger`, else we need to store it in `larger2` And that's it. Also take in account that this algorithm is O(n), because we need to travel the whole array just one time, instead of the original one that i O(n\*2) because you have to travel the whole array two times, so with bigger array size, this will end about in half the time
23,713,488
I have a program running 2 threads. The first is waiting for user input (using a scanf), the second is listening for some data over an udp socket. I would like to emulate user input to handle a specific notification with the first thread everytime I recive a specific udp packet. I know I can share variables between threads, so my question is: can I force the scanf to take input from a different thread? Can I skip the scanf in the first thread?
2014/05/17
[ "https://Stackoverflow.com/questions/23713488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3574984/" ]
You can use > > System.Diagnostics.Process.Start() > > > <http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx> followed by > > Process.WaitForExit > > > to run the Visual C++ compiler (CL.EXE). The documentation for CL.EXE is here: <http://msdn.microsoft.com/en-us/library/610ecb4h.aspx> Your needs might be as simple as: ``` c:\path-to-compiler\cl.exe file.cpp /clr ``` In particular, I'd recommend that you review all your choices for the /clr option: [http://msdn.microsoft.com/en-us/library/k8d11d4s(v=VS.80).aspx](http://msdn.microsoft.com/en-us/library/k8d11d4s%28v=VS.80%29.aspx) You need to have Visual C++ on your machine.
I assume you only want to treat single source file programs using only standard libraries. I also assume that you are working on Windows (asp.net). As soon as you have program source text, you can save it to a file. Then you start `cl` as an external program with your source as parameter to compile it. And finally you start the program you have just compiled. Of course, you will have to give pipes for Stdout and probably stdin and stderr.
35,390
I would like to write a function that pretty-prints the current source code block into a PDF. I know I can use ps-print-region-with-faces, but it would require that I first select the source code block. Is there a function in org to do this selection? thank you in advance Edit: the answer is org-babel-mark-block (answered by bertfred in a comment) org-mark-element selects the block but also selects the BEGIN\_ END\_ markers.
2017/09/09
[ "https://emacs.stackexchange.com/questions/35390", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/13769/" ]
Unlike `org-mark-element`, the function `org-babel-mark-block` only selects the contents of a block.
`org-mark-element` should be able to do the right thing. It's bound to `M-h` by default.
253,471
Something I have been puzzled about is this: how exactly does a computer regulate and tell time? For example: if I were to write a program that did this: Do 2+2 then wait 5 seconds How does the processor know what "5 seconds" is? How is time measured in computer systems? Is there a specific chip for that sole purpose? How does it work? Thanks for any replies; I'm really interested in computer science, and would love any help you could give me =D.
2011/03/05
[ "https://superuser.com/questions/253471", "https://superuser.com", "https://superuser.com/users/70272/" ]
IIRC, there's a small crystal the vibrates at a specific frequency when an electric current is passed through it. Each movement is counted and a specific number of them trigger a clock cycle.
> > HPET uses a 10 MHz clock > > > HPET uses **at leaast** a 10 Mhz clock. It can be more precise than 10 Mhz but never less. <http://en.wikipedia.org/wiki/High_Precision_Event_Timer#Comparison_to_predecessors>
253,471
Something I have been puzzled about is this: how exactly does a computer regulate and tell time? For example: if I were to write a program that did this: Do 2+2 then wait 5 seconds How does the processor know what "5 seconds" is? How is time measured in computer systems? Is there a specific chip for that sole purpose? How does it work? Thanks for any replies; I'm really interested in computer science, and would love any help you could give me =D.
2011/03/05
[ "https://superuser.com/questions/253471", "https://superuser.com", "https://superuser.com/users/70272/" ]
While Joel's answer is correct, in reality, it's a bit more complicated. First thing which needs to be taken into consideration (and I'm going to focus only on PCs here) is that there are several clocks in a computer and each has its own use. Most popular and easiest to understand is the [real-time clock](http://en.wikipedia.org/wiki/Real-time_clock). It is basically a chip which has a simple clock inside. They usually have same type of quartz crystals as standard clocks and usually have a battery for time keeping when the computer is powered down. The problem with them is that they aren't very accurate, as can be seen from Syntech's links. The 32.768 kHz crystal is too slow for any timekeeping on modern systems whose processors are in megahertz and gigahertz range. Here we come to the next point: There are internal clocks used for precise time measurements and countdowns. A simple clock is [programmable interval timer](http://en.wikipedia.org/wiki/Programmable_interval_timer). What it does is wait a certain amount of time and then send an interrupt to the CPU. When the CPU receives the interrupt, it will stop whatever it is doing and tend to the task which generated the interrupt. This way the CPU does not have to constantly check if something is done. Instead it can focus on other jobs and have the PIT tell it when the job is done. The PIT uses 1.193182 MHz clock source and is therefore much more precise than simple RTC. Next interesting measurement system is [time stamp counter](http://en.wikipedia.org/wiki/Time_Stamp_Counter). The idea behind it is that we can get much more precise measurements of time using processor's clock source that using various system timers. PIT has 1.193182 MHz clock, but even the earliest x86 processors had much higher clock. So we'll have a timer which is updated after every set amount of processor cycles. At the time processors had very stable clocks and use of TSC was a nice way to make precise time measurements. Use of TSC however brings a number of problems. Different processors have different tick rates and measure time at different speeds. Later on, as techniology advanced we got modern processors which can change their frequency. That is a major problem, sicen the CPU clock isn't constant anymore and we can't use it to measure time. And that's why we have [high precision event timers](http://en.wikipedia.org/wiki/High_Precision_Event_Timer) now. HPET uses a 10 MHz clock and is therefore more precise than PIT. On the other hand, its clock source does not depend on CPU's clock and it can be used to measure time even if CPU's clock changes. Unlike PIT, which works as countdown, HPET measures time since the computer was turned on and compares current time to time when an action is needed. There are other time sources available for computers which I believe need to be mentioned. Some computers are connected to atomic clocks and can use them to precisely measure time. A less expensive option and much more common is to use external time source to calibrate internal time sources of the computer. For example GPS receivers can be used to provide high precision time measurements, because GPS satellites have their internal atomic clocks. Another option which is less common than GPS receiver is to use a special radio receiver which decodes time information from time keeping radio stations such as DCF77 for example. Such time stations have their own high precision time sources and transmit their output over radio. Since radio waves travel at speed of light, the delay is often insignificant.
> > HPET uses a 10 MHz clock > > > HPET uses **at leaast** a 10 Mhz clock. It can be more precise than 10 Mhz but never less. <http://en.wikipedia.org/wiki/High_Precision_Event_Timer#Comparison_to_predecessors>
537,992
Yesterday, I have downloaded and installed Windows 8 Professional, after downloading it (legally) and burning it to a DVD, on my 3-year-old [Dell Studio 1555](https://en.wikipedia.org/wiki/Dell_Studio#Studio_15) (Intel Core Duo 2x2.4 GHz, 4 GB RAM, [Toshiba MK2555GSX](http://rads.stackoverflow.com/amzn/click/B001UUG9E0) hard disk drive). The installation failed two or three times, each time differently (error codes, for example 0xc000021a, with an infinite boot loop), but finally I completely formatted the hard drive and installed. Seemingly, everything was OK. However, after booting successfully, the OS is extremely slow. When I open the task manager, it shows that the HDD is at 100% - however, no application or background process or Windows process can be made responsible. I searched the Internet and found that Windows might try to "index" the hard drive, but I did't find a process that isn't also on my second computer, which still uses the Release Preview (restarting every two hours). Also, the startup is empty, and HD Tune and HDD Health show that the drive health is OK, even though I don't know how reliable these two programs are. I looked for diagnose software from Toshiba, but they only offer tools for "Fujitsu branded Toshiba devices"; I tried it out, and it did not work on my hard drive. Does this sound like a hard drive failure? The laptop is 3.5-years-old, has been carried around sometimes roughly and was used (and on) most of the time. However, it would have failed exactly the night before installing Windows 8 Profesional, which seems - unlikely. If this is a software error - then what did I do wrong if this occurs from the moment of installation (even the personalization at the end of installation took half an hour)? How can I fix this? ![Screenshot of taskmanager (Disk 1/drive E:\ is an external USB hard drive)](https://i.stack.imgur.com/nL8oV.png) ![The processes, none of which is shown to use the hard drive specifically](https://i.stack.imgur.com/Nay83.png) ![The second half of those processes](https://i.stack.imgur.com/fdOZR.png) ![Screenshot of HDD Health and HD Tune on the health of the drive](https://i.stack.imgur.com/0bR2h.png)
2013/01/18
[ "https://superuser.com/questions/537992", "https://superuser.com", "https://superuser.com/users/160047/" ]
I would suggest going to the Dell website and downloading all the drivers. Missing drivers can cause problems like that, especially [CPU](http://en.wikipedia.org/wiki/Central_processing_unit) and chipset drivers. The other possibility (as long as you didn't install 64-bit on a 32-bit system), is either the computer isn't compatible with Windows 8, a corrupted download or a bad burn... If you can find 'services', you can try turning off the indexer as it will run harder on a new install than an old install since it hasn't indexed any files yet, although I think it's more likely one of the above reasons. Most hard drives start making noises before they completely fail (as long as they aren't [SSD](http://en.wikipedia.org/wiki/Solid-state_drive) drives anyway).
Firstly I think the active 100% is a false alarm because the actual re/write speeds are 0. See this post: [Extremely high disk activity without any real usage](https://superuser.com/questions/470334/extremely-high-disk-activity-without-any-real-usage) Now you mentioned several failed installation attempts, this could most likely be due to a corrupted install disk, did you verify the disk after burning? It could also be due to HDD failures, if so does your HDD have SMART status (in BIOS). If the SMART status is ok then I would start to rule out HDD failure. You could run a full disk check on your HDD (Right click drive in Explorer > Properties > Tools Tab). If the optical disk is dodgy, burn another copy and try installing again. Windows 8 is search based (you search for apps, files settings etc) and will index your computer post install. I would not recommend you turn this off, instead leave the computer on for a while and let it finish indexing and downloading updates. After which the computer will run noticeably faster. Finally, you are installing new OS on old hardware. Why do you expect it to run faster? Your hardware manufacturer is most likely not going to be supporting this OS and will not provide new optimized drivers causing windows to use generic drivers for most devices which are not optimized for your hardware.
537,992
Yesterday, I have downloaded and installed Windows 8 Professional, after downloading it (legally) and burning it to a DVD, on my 3-year-old [Dell Studio 1555](https://en.wikipedia.org/wiki/Dell_Studio#Studio_15) (Intel Core Duo 2x2.4 GHz, 4 GB RAM, [Toshiba MK2555GSX](http://rads.stackoverflow.com/amzn/click/B001UUG9E0) hard disk drive). The installation failed two or three times, each time differently (error codes, for example 0xc000021a, with an infinite boot loop), but finally I completely formatted the hard drive and installed. Seemingly, everything was OK. However, after booting successfully, the OS is extremely slow. When I open the task manager, it shows that the HDD is at 100% - however, no application or background process or Windows process can be made responsible. I searched the Internet and found that Windows might try to "index" the hard drive, but I did't find a process that isn't also on my second computer, which still uses the Release Preview (restarting every two hours). Also, the startup is empty, and HD Tune and HDD Health show that the drive health is OK, even though I don't know how reliable these two programs are. I looked for diagnose software from Toshiba, but they only offer tools for "Fujitsu branded Toshiba devices"; I tried it out, and it did not work on my hard drive. Does this sound like a hard drive failure? The laptop is 3.5-years-old, has been carried around sometimes roughly and was used (and on) most of the time. However, it would have failed exactly the night before installing Windows 8 Profesional, which seems - unlikely. If this is a software error - then what did I do wrong if this occurs from the moment of installation (even the personalization at the end of installation took half an hour)? How can I fix this? ![Screenshot of taskmanager (Disk 1/drive E:\ is an external USB hard drive)](https://i.stack.imgur.com/nL8oV.png) ![The processes, none of which is shown to use the hard drive specifically](https://i.stack.imgur.com/Nay83.png) ![The second half of those processes](https://i.stack.imgur.com/fdOZR.png) ![Screenshot of HDD Health and HD Tune on the health of the drive](https://i.stack.imgur.com/0bR2h.png)
2013/01/18
[ "https://superuser.com/questions/537992", "https://superuser.com", "https://superuser.com/users/160047/" ]
Okay, so I bought a Samsung 840 pro Series 128 (de factor 120)GB and set it in - the laptop works perfectly now. So the hard drive must have been the cause. In case it had not been, I would have plugged the SSD into my desktop anyway. Thanks for all your ideas.
I would suggest going to the Dell website and downloading all the drivers. Missing drivers can cause problems like that, especially [CPU](http://en.wikipedia.org/wiki/Central_processing_unit) and chipset drivers. The other possibility (as long as you didn't install 64-bit on a 32-bit system), is either the computer isn't compatible with Windows 8, a corrupted download or a bad burn... If you can find 'services', you can try turning off the indexer as it will run harder on a new install than an old install since it hasn't indexed any files yet, although I think it's more likely one of the above reasons. Most hard drives start making noises before they completely fail (as long as they aren't [SSD](http://en.wikipedia.org/wiki/Solid-state_drive) drives anyway).
537,992
Yesterday, I have downloaded and installed Windows 8 Professional, after downloading it (legally) and burning it to a DVD, on my 3-year-old [Dell Studio 1555](https://en.wikipedia.org/wiki/Dell_Studio#Studio_15) (Intel Core Duo 2x2.4 GHz, 4 GB RAM, [Toshiba MK2555GSX](http://rads.stackoverflow.com/amzn/click/B001UUG9E0) hard disk drive). The installation failed two or three times, each time differently (error codes, for example 0xc000021a, with an infinite boot loop), but finally I completely formatted the hard drive and installed. Seemingly, everything was OK. However, after booting successfully, the OS is extremely slow. When I open the task manager, it shows that the HDD is at 100% - however, no application or background process or Windows process can be made responsible. I searched the Internet and found that Windows might try to "index" the hard drive, but I did't find a process that isn't also on my second computer, which still uses the Release Preview (restarting every two hours). Also, the startup is empty, and HD Tune and HDD Health show that the drive health is OK, even though I don't know how reliable these two programs are. I looked for diagnose software from Toshiba, but they only offer tools for "Fujitsu branded Toshiba devices"; I tried it out, and it did not work on my hard drive. Does this sound like a hard drive failure? The laptop is 3.5-years-old, has been carried around sometimes roughly and was used (and on) most of the time. However, it would have failed exactly the night before installing Windows 8 Profesional, which seems - unlikely. If this is a software error - then what did I do wrong if this occurs from the moment of installation (even the personalization at the end of installation took half an hour)? How can I fix this? ![Screenshot of taskmanager (Disk 1/drive E:\ is an external USB hard drive)](https://i.stack.imgur.com/nL8oV.png) ![The processes, none of which is shown to use the hard drive specifically](https://i.stack.imgur.com/Nay83.png) ![The second half of those processes](https://i.stack.imgur.com/fdOZR.png) ![Screenshot of HDD Health and HD Tune on the health of the drive](https://i.stack.imgur.com/0bR2h.png)
2013/01/18
[ "https://superuser.com/questions/537992", "https://superuser.com", "https://superuser.com/users/160047/" ]
I would suggest going to the Dell website and downloading all the drivers. Missing drivers can cause problems like that, especially [CPU](http://en.wikipedia.org/wiki/Central_processing_unit) and chipset drivers. The other possibility (as long as you didn't install 64-bit on a 32-bit system), is either the computer isn't compatible with Windows 8, a corrupted download or a bad burn... If you can find 'services', you can try turning off the indexer as it will run harder on a new install than an old install since it hasn't indexed any files yet, although I think it's more likely one of the above reasons. Most hard drives start making noises before they completely fail (as long as they aren't [SSD](http://en.wikipedia.org/wiki/Solid-state_drive) drives anyway).
Not sure if this helps you but I had such a hard time finding a fix for my problem, I wanted to post here: I had a very similar problem and I believe fixed it today. Now it might not be applicable to you but this is how I fixed my Windows 8 Pro 100% HDD activity. I installed my Win 8 on a SSD, but in the BIOS on the MOBO I had the Storage Configuration as IDE (I just upgraded the HD to an SSD and installed Win 8 Pro on it clean) instead of AHCI. I loaded Windows 8, and changed the Registry to accept AHCI using this method [Link](http://www.ithinkdiff.com/how-to-enable-ahci-in-windows-8-after-installation/) and then restarted Win 8. I went into my MOBOs BIOS and changed the Storage Configuration to AHCI. Restarted Windows and the problem seems to have disappeared. I hope this helps you!
537,992
Yesterday, I have downloaded and installed Windows 8 Professional, after downloading it (legally) and burning it to a DVD, on my 3-year-old [Dell Studio 1555](https://en.wikipedia.org/wiki/Dell_Studio#Studio_15) (Intel Core Duo 2x2.4 GHz, 4 GB RAM, [Toshiba MK2555GSX](http://rads.stackoverflow.com/amzn/click/B001UUG9E0) hard disk drive). The installation failed two or three times, each time differently (error codes, for example 0xc000021a, with an infinite boot loop), but finally I completely formatted the hard drive and installed. Seemingly, everything was OK. However, after booting successfully, the OS is extremely slow. When I open the task manager, it shows that the HDD is at 100% - however, no application or background process or Windows process can be made responsible. I searched the Internet and found that Windows might try to "index" the hard drive, but I did't find a process that isn't also on my second computer, which still uses the Release Preview (restarting every two hours). Also, the startup is empty, and HD Tune and HDD Health show that the drive health is OK, even though I don't know how reliable these two programs are. I looked for diagnose software from Toshiba, but they only offer tools for "Fujitsu branded Toshiba devices"; I tried it out, and it did not work on my hard drive. Does this sound like a hard drive failure? The laptop is 3.5-years-old, has been carried around sometimes roughly and was used (and on) most of the time. However, it would have failed exactly the night before installing Windows 8 Profesional, which seems - unlikely. If this is a software error - then what did I do wrong if this occurs from the moment of installation (even the personalization at the end of installation took half an hour)? How can I fix this? ![Screenshot of taskmanager (Disk 1/drive E:\ is an external USB hard drive)](https://i.stack.imgur.com/nL8oV.png) ![The processes, none of which is shown to use the hard drive specifically](https://i.stack.imgur.com/Nay83.png) ![The second half of those processes](https://i.stack.imgur.com/fdOZR.png) ![Screenshot of HDD Health and HD Tune on the health of the drive](https://i.stack.imgur.com/0bR2h.png)
2013/01/18
[ "https://superuser.com/questions/537992", "https://superuser.com", "https://superuser.com/users/160047/" ]
I would suggest going to the Dell website and downloading all the drivers. Missing drivers can cause problems like that, especially [CPU](http://en.wikipedia.org/wiki/Central_processing_unit) and chipset drivers. The other possibility (as long as you didn't install 64-bit on a 32-bit system), is either the computer isn't compatible with Windows 8, a corrupted download or a bad burn... If you can find 'services', you can try turning off the indexer as it will run harder on a new install than an old install since it hasn't indexed any files yet, although I think it's more likely one of the above reasons. Most hard drives start making noises before they completely fail (as long as they aren't [SSD](http://en.wikipedia.org/wiki/Solid-state_drive) drives anyway).
First of all, if you have a legal copy, the first place where you should ask it's at microsoft and/or you laptop/HDD vendor [Toshiba or Dell] support. (that's one of the advantages of having a legal license. Use it. **You paid for it**. Make those geeks work for you). If there's any driver incompatibility with your HDD model, It's a good practice to report it (either to microsoft or to your HDD vendor) so they can fix it in future patch releases (or maybe they already have a patch for it, **saving you money from buying another HDD**). Now, from my experience with windows installations, If you had experienced problems in the installation the odds for future problems are very high. Since your last update, I will go with HDD corrupted sectors (which cannot be repaired, but can be marked to be skipped with proper tools) or driver malfunction. Windows 8 installation (internally speaking) its very different, and if your laptop wasn't designed to work with windows 8, maybe you need a BIOS/UEFI update and/or use a different HDD driver in the installation (even if the installation wizard detects the drive). Thus, that's why you should contact microsoft/laptop/hdd vendor support in first place.
537,992
Yesterday, I have downloaded and installed Windows 8 Professional, after downloading it (legally) and burning it to a DVD, on my 3-year-old [Dell Studio 1555](https://en.wikipedia.org/wiki/Dell_Studio#Studio_15) (Intel Core Duo 2x2.4 GHz, 4 GB RAM, [Toshiba MK2555GSX](http://rads.stackoverflow.com/amzn/click/B001UUG9E0) hard disk drive). The installation failed two or three times, each time differently (error codes, for example 0xc000021a, with an infinite boot loop), but finally I completely formatted the hard drive and installed. Seemingly, everything was OK. However, after booting successfully, the OS is extremely slow. When I open the task manager, it shows that the HDD is at 100% - however, no application or background process or Windows process can be made responsible. I searched the Internet and found that Windows might try to "index" the hard drive, but I did't find a process that isn't also on my second computer, which still uses the Release Preview (restarting every two hours). Also, the startup is empty, and HD Tune and HDD Health show that the drive health is OK, even though I don't know how reliable these two programs are. I looked for diagnose software from Toshiba, but they only offer tools for "Fujitsu branded Toshiba devices"; I tried it out, and it did not work on my hard drive. Does this sound like a hard drive failure? The laptop is 3.5-years-old, has been carried around sometimes roughly and was used (and on) most of the time. However, it would have failed exactly the night before installing Windows 8 Profesional, which seems - unlikely. If this is a software error - then what did I do wrong if this occurs from the moment of installation (even the personalization at the end of installation took half an hour)? How can I fix this? ![Screenshot of taskmanager (Disk 1/drive E:\ is an external USB hard drive)](https://i.stack.imgur.com/nL8oV.png) ![The processes, none of which is shown to use the hard drive specifically](https://i.stack.imgur.com/Nay83.png) ![The second half of those processes](https://i.stack.imgur.com/fdOZR.png) ![Screenshot of HDD Health and HD Tune on the health of the drive](https://i.stack.imgur.com/0bR2h.png)
2013/01/18
[ "https://superuser.com/questions/537992", "https://superuser.com", "https://superuser.com/users/160047/" ]
Okay, so I bought a Samsung 840 pro Series 128 (de factor 120)GB and set it in - the laptop works perfectly now. So the hard drive must have been the cause. In case it had not been, I would have plugged the SSD into my desktop anyway. Thanks for all your ideas.
Firstly I think the active 100% is a false alarm because the actual re/write speeds are 0. See this post: [Extremely high disk activity without any real usage](https://superuser.com/questions/470334/extremely-high-disk-activity-without-any-real-usage) Now you mentioned several failed installation attempts, this could most likely be due to a corrupted install disk, did you verify the disk after burning? It could also be due to HDD failures, if so does your HDD have SMART status (in BIOS). If the SMART status is ok then I would start to rule out HDD failure. You could run a full disk check on your HDD (Right click drive in Explorer > Properties > Tools Tab). If the optical disk is dodgy, burn another copy and try installing again. Windows 8 is search based (you search for apps, files settings etc) and will index your computer post install. I would not recommend you turn this off, instead leave the computer on for a while and let it finish indexing and downloading updates. After which the computer will run noticeably faster. Finally, you are installing new OS on old hardware. Why do you expect it to run faster? Your hardware manufacturer is most likely not going to be supporting this OS and will not provide new optimized drivers causing windows to use generic drivers for most devices which are not optimized for your hardware.
537,992
Yesterday, I have downloaded and installed Windows 8 Professional, after downloading it (legally) and burning it to a DVD, on my 3-year-old [Dell Studio 1555](https://en.wikipedia.org/wiki/Dell_Studio#Studio_15) (Intel Core Duo 2x2.4 GHz, 4 GB RAM, [Toshiba MK2555GSX](http://rads.stackoverflow.com/amzn/click/B001UUG9E0) hard disk drive). The installation failed two or three times, each time differently (error codes, for example 0xc000021a, with an infinite boot loop), but finally I completely formatted the hard drive and installed. Seemingly, everything was OK. However, after booting successfully, the OS is extremely slow. When I open the task manager, it shows that the HDD is at 100% - however, no application or background process or Windows process can be made responsible. I searched the Internet and found that Windows might try to "index" the hard drive, but I did't find a process that isn't also on my second computer, which still uses the Release Preview (restarting every two hours). Also, the startup is empty, and HD Tune and HDD Health show that the drive health is OK, even though I don't know how reliable these two programs are. I looked for diagnose software from Toshiba, but they only offer tools for "Fujitsu branded Toshiba devices"; I tried it out, and it did not work on my hard drive. Does this sound like a hard drive failure? The laptop is 3.5-years-old, has been carried around sometimes roughly and was used (and on) most of the time. However, it would have failed exactly the night before installing Windows 8 Profesional, which seems - unlikely. If this is a software error - then what did I do wrong if this occurs from the moment of installation (even the personalization at the end of installation took half an hour)? How can I fix this? ![Screenshot of taskmanager (Disk 1/drive E:\ is an external USB hard drive)](https://i.stack.imgur.com/nL8oV.png) ![The processes, none of which is shown to use the hard drive specifically](https://i.stack.imgur.com/Nay83.png) ![The second half of those processes](https://i.stack.imgur.com/fdOZR.png) ![Screenshot of HDD Health and HD Tune on the health of the drive](https://i.stack.imgur.com/0bR2h.png)
2013/01/18
[ "https://superuser.com/questions/537992", "https://superuser.com", "https://superuser.com/users/160047/" ]
Okay, so I bought a Samsung 840 pro Series 128 (de factor 120)GB and set it in - the laptop works perfectly now. So the hard drive must have been the cause. In case it had not been, I would have plugged the SSD into my desktop anyway. Thanks for all your ideas.
Not sure if this helps you but I had such a hard time finding a fix for my problem, I wanted to post here: I had a very similar problem and I believe fixed it today. Now it might not be applicable to you but this is how I fixed my Windows 8 Pro 100% HDD activity. I installed my Win 8 on a SSD, but in the BIOS on the MOBO I had the Storage Configuration as IDE (I just upgraded the HD to an SSD and installed Win 8 Pro on it clean) instead of AHCI. I loaded Windows 8, and changed the Registry to accept AHCI using this method [Link](http://www.ithinkdiff.com/how-to-enable-ahci-in-windows-8-after-installation/) and then restarted Win 8. I went into my MOBOs BIOS and changed the Storage Configuration to AHCI. Restarted Windows and the problem seems to have disappeared. I hope this helps you!
537,992
Yesterday, I have downloaded and installed Windows 8 Professional, after downloading it (legally) and burning it to a DVD, on my 3-year-old [Dell Studio 1555](https://en.wikipedia.org/wiki/Dell_Studio#Studio_15) (Intel Core Duo 2x2.4 GHz, 4 GB RAM, [Toshiba MK2555GSX](http://rads.stackoverflow.com/amzn/click/B001UUG9E0) hard disk drive). The installation failed two or three times, each time differently (error codes, for example 0xc000021a, with an infinite boot loop), but finally I completely formatted the hard drive and installed. Seemingly, everything was OK. However, after booting successfully, the OS is extremely slow. When I open the task manager, it shows that the HDD is at 100% - however, no application or background process or Windows process can be made responsible. I searched the Internet and found that Windows might try to "index" the hard drive, but I did't find a process that isn't also on my second computer, which still uses the Release Preview (restarting every two hours). Also, the startup is empty, and HD Tune and HDD Health show that the drive health is OK, even though I don't know how reliable these two programs are. I looked for diagnose software from Toshiba, but they only offer tools for "Fujitsu branded Toshiba devices"; I tried it out, and it did not work on my hard drive. Does this sound like a hard drive failure? The laptop is 3.5-years-old, has been carried around sometimes roughly and was used (and on) most of the time. However, it would have failed exactly the night before installing Windows 8 Profesional, which seems - unlikely. If this is a software error - then what did I do wrong if this occurs from the moment of installation (even the personalization at the end of installation took half an hour)? How can I fix this? ![Screenshot of taskmanager (Disk 1/drive E:\ is an external USB hard drive)](https://i.stack.imgur.com/nL8oV.png) ![The processes, none of which is shown to use the hard drive specifically](https://i.stack.imgur.com/Nay83.png) ![The second half of those processes](https://i.stack.imgur.com/fdOZR.png) ![Screenshot of HDD Health and HD Tune on the health of the drive](https://i.stack.imgur.com/0bR2h.png)
2013/01/18
[ "https://superuser.com/questions/537992", "https://superuser.com", "https://superuser.com/users/160047/" ]
Okay, so I bought a Samsung 840 pro Series 128 (de factor 120)GB and set it in - the laptop works perfectly now. So the hard drive must have been the cause. In case it had not been, I would have plugged the SSD into my desktop anyway. Thanks for all your ideas.
First of all, if you have a legal copy, the first place where you should ask it's at microsoft and/or you laptop/HDD vendor [Toshiba or Dell] support. (that's one of the advantages of having a legal license. Use it. **You paid for it**. Make those geeks work for you). If there's any driver incompatibility with your HDD model, It's a good practice to report it (either to microsoft or to your HDD vendor) so they can fix it in future patch releases (or maybe they already have a patch for it, **saving you money from buying another HDD**). Now, from my experience with windows installations, If you had experienced problems in the installation the odds for future problems are very high. Since your last update, I will go with HDD corrupted sectors (which cannot be repaired, but can be marked to be skipped with proper tools) or driver malfunction. Windows 8 installation (internally speaking) its very different, and if your laptop wasn't designed to work with windows 8, maybe you need a BIOS/UEFI update and/or use a different HDD driver in the installation (even if the installation wizard detects the drive). Thus, that's why you should contact microsoft/laptop/hdd vendor support in first place.