qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
79,070
As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on?
2017/04/26
[ "https://money.stackexchange.com/questions/79070", "https://money.stackexchange.com", "https://money.stackexchange.com/users/41914/" ]
The time value decay is theoretically constant. In reality, it is driven by supply and demand, just like everything else in the market. For instance, if a big earnings announcement is coming out after the close for the day, you may see little or no time decay in the price of the options during the day before. Also, while in theory options have a set value as related to the trading price of the underlying security, that does not mean there will always be a buyer willing to pay a premium as they come close to expiration (in the last few minutes). You can't forget to account for the transaction fees associated with buying the options, or the risk factor involved. It is rare, but there are times I've actually had to sell in the money calls at a penny or two LESS than they're actually worth at the time just to unload them in the last few minutes before the market closed on expiration day.
The time value of the option (theta) decays constantly (by the millisecond) As it is one of the inputs to the option pricing model, it usually has a lower impact on the overall option price than other changes in the market. As the (US) markets price options in penny ($0.01) or nickel ($0.05) increments, you will only observe these changes when the impact of theta is big enough for the market maker to increase or decrease his bid or offer by another $0.01 or $0.05. This will happen slowly throughout the day but should be more significant from one day’s close to the next day’s open particularly if there is a weekend or long weekend in between.
79,070
As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on?
2017/04/26
[ "https://money.stackexchange.com/questions/79070", "https://money.stackexchange.com", "https://money.stackexchange.com/users/41914/" ]
The time value decay is theoretically constant. In reality, it is driven by supply and demand, just like everything else in the market. For instance, if a big earnings announcement is coming out after the close for the day, you may see little or no time decay in the price of the options during the day before. Also, while in theory options have a set value as related to the trading price of the underlying security, that does not mean there will always be a buyer willing to pay a premium as they come close to expiration (in the last few minutes). You can't forget to account for the transaction fees associated with buying the options, or the risk factor involved. It is rare, but there are times I've actually had to sell in the money calls at a penny or two LESS than they're actually worth at the time just to unload them in the last few minutes before the market closed on expiration day.
This has been my observation in the markets pertaining to option decay. Bulk of the decay happens in the first 15 minutes of trade at market open. Rest of the decay usually happens in pulses whenever market breaks out of ranges intraday. So if its call option and market breaks a range to the downside, call option will experience decay in proportion to time elapsed since open.
79,070
As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on?
2017/04/26
[ "https://money.stackexchange.com/questions/79070", "https://money.stackexchange.com", "https://money.stackexchange.com/users/41914/" ]
It has been my experience as an amateur trader, theory aside, that I generally see the time value come off at market open and not much during the trading day.
The time value of the option (theta) decays constantly (by the millisecond) As it is one of the inputs to the option pricing model, it usually has a lower impact on the overall option price than other changes in the market. As the (US) markets price options in penny ($0.01) or nickel ($0.05) increments, you will only observe these changes when the impact of theta is big enough for the market maker to increase or decrease his bid or offer by another $0.01 or $0.05. This will happen slowly throughout the day but should be more significant from one day’s close to the next day’s open particularly if there is a weekend or long weekend in between.
79,070
As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on?
2017/04/26
[ "https://money.stackexchange.com/questions/79070", "https://money.stackexchange.com", "https://money.stackexchange.com/users/41914/" ]
It has been my experience as an amateur trader, theory aside, that I generally see the time value come off at market open and not much during the trading day.
This has been my observation in the markets pertaining to option decay. Bulk of the decay happens in the first 15 minutes of trade at market open. Rest of the decay usually happens in pulses whenever market breaks out of ranges intraday. So if its call option and market breaks a range to the downside, call option will experience decay in proportion to time elapsed since open.
79,070
As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on?
2017/04/26
[ "https://money.stackexchange.com/questions/79070", "https://money.stackexchange.com", "https://money.stackexchange.com/users/41914/" ]
The time value of the option (theta) decays constantly (by the millisecond) As it is one of the inputs to the option pricing model, it usually has a lower impact on the overall option price than other changes in the market. As the (US) markets price options in penny ($0.01) or nickel ($0.05) increments, you will only observe these changes when the impact of theta is big enough for the market maker to increase or decrease his bid or offer by another $0.01 or $0.05. This will happen slowly throughout the day but should be more significant from one day’s close to the next day’s open particularly if there is a weekend or long weekend in between.
This has been my observation in the markets pertaining to option decay. Bulk of the decay happens in the first 15 minutes of trade at market open. Rest of the decay usually happens in pulses whenever market breaks out of ranges intraday. So if its call option and market breaks a range to the downside, call option will experience decay in proportion to time elapsed since open.
1,436,496
After upgrading to 22.10, my WiFi is not worling properly. I am using a MacBook Pro, with a Broadcom device.. LAN works fine, i can ping other devices on my home network, I can remote control the MacBook from a windows computer and I can ping 8.8.8.8, but can't access the internet and it seems like the network-manager service is missing.. This worked fine in 22.04. Please help! Update: Output from terminal: ``` lspci -knn | grep Net -A3 02:00.0 Ethernet controller [0200]: Broadcom Inc. and subsidiaries NetXtreme BCM57765 Gigabit Ethernet PCIe [14e4:16b4] (rev 10) Subsystem: Broadcom Inc. and subsidiaries NetXtreme BCM57765 Gigabit Ethernet PCIe [14e4:16b4] Kernel driver in use: tg3 Kernel modules: tg3 02:00.1 SD Host controller [0805]: Broadcom Inc. and subsidiaries BCM57765/57785 SDXC/MMC Card Reader [14e4:16bc] (rev 10) -- 03:00.0 Network controller [0280]: Broadcom Inc. and subsidiaries BCM4331 802.11a/b/g/n [14e4:4331] (rev 02) Subsystem: Broadcom Inc. and subsidiaries BCM4331 802.11a/b/g/n [14e4:4331] Kernel driver in use: wl Kernel modules: bcma, wl ```
2022/10/21
[ "https://askubuntu.com/questions/1436496", "https://askubuntu.com", "https://askubuntu.com/users/1631565/" ]
I fixed it! /etc/resolv.conf was corrupt or something.. I did ``` sudo rm /etc/resolv.conf ``` then I created a new resolv.conf ``` sudo nano /etc/resolv.conf ``` and added the line ``` nameserver 8.8.8.8 ``` after that I reconnected to my WiFi and I am back in the game Thank you for taking the time to hep me out! :)
A wrong driver is installed. Run ``` sudo apt purge bcmwl-kernel-source sudo apt install firmware-b43-installer sudo modprobe b43 ```
61,522,334
In this example below M = 10 and N = 2, and since M is considerably larger than 2\*\*N, the probability is that every possible combination of N booleans, (True, True), (True False), (False, True), (False, False) in this example, will be generated among the M outputs at least once, as has occurred below. ``` for _ in range(10): ... choice1 = np.random.choice((True, False)) ... choice2 = np.random.choice((True, False)) ... print(choice1, choice2) ... False False False False True False True False True True False True True True True True True False False False ``` But it isn't guaranteed. There is a low probability of getting 10 X (False, False) or alternatively 10 X (True, True), or perhaps a mix where one particular pair, say (False, True), never appears. In 'real life' the print is replaced by a yield statement, and `choice1` and `choice2` are accompanied by several other randomly generated numeric variables. How could I easily change the generation of `choice1` and `choice2` to make sure they always cover all of the 4 possibilities, while still keeping it (mostly) random, without just adding 4 extra non-random cases to force them to occur? I feel as if the selection without replacement option could be exploited, but I can't think how to incorporate this.
2020/04/30
[ "https://Stackoverflow.com/questions/61522334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3265562/" ]
It would be nice to see were exactly you had problems in accessing/calling the pandas dataframe. Here is possible solution based on `rolling(win)` and `max()`: ``` import pandas as pd d = dict(row = [0,0,0,0,0,0,0,1,0,0,0,0,0,0]) df = pd.DataFrame(d) win = 6 df['winMax'] = df.rolling(win).max().shift(-win+1) print(df) > row winMax 0 0 0.0 1 0 0.0 2 0 1.0 3 0 1.0 4 0 1.0 5 0 1.0 6 0 1.0 7 1 1.0 8 0 0.0 9 0 NaN 10 0 NaN 11 0 NaN 12 0 NaN 13 0 NaN ```
Possible solution by pandasql. Is there a way to avoid using it? ``` from pandasql import sqldf df_final = sqldf("""SELECT id, date, target_row, MAX(target_row) OVER (PARTITION BY id ORDER BY date ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING) FROM df """) ```
73,539,012
Ok in my code i was trying to get the camera to follow my player and i was following a tutorial i found on stack overflow. But when I did it the player "fell" and rotates on its y axis how did this happen and also I tried to spawn the ground class but i dont think i did. And looked on all the docs for ursina and looking at how to videos, I still dont understand why. wht did i do wrong? ``` from ursina import * from ursina.prefabs.first_person_controller import FirstPersonController app = Ursina() EditorCamera() cam = FirstPersonController() class Player(Entity): def __init__(self, **kwargs): super().__init__(model='cube', color=color.orange, collider='box', origin = (0, 0, -2), parent = cam) self.health_bar = Entity(parent=self, model='quad', color=color.red, scale_y=.1, y=1.2) self.max_health = 100 self.health = self.max_health class Beings(Entity): def __init__(self, **kwargs): super().__init__(model='cube', color=color.gray, scale=2, collider='box', position=Vec3(1,0,2), origin_y=-.5) self.health_bar = Entity(parent=self, model='quad', color=color.red, scale_y=.1, y=1.2) self.max_health = 100 self.health = self.max_health class Ground(Entity): def __init__(self, **kwargs): super().__init__(model='plane', color=color.gray, scale=2, collider='mesh', position=Vec3(1,0,2), origin_y=-.4) self.health_bar = Entity(parent=self, model='quad', color=color.red, scale_y=.1, y=1.2) self.max_health = 100 self.health = self.max_health class Buildings(Entity): def __init__(self, **kwargs): super().__init__(model='cube', color=color.gray, scale=2, collider='box', position=Vec3(1,0,2), origin_y=-.5) self.health_bar = Entity(parent=self, model='quad', color=color.red, scale_y=.1, y=1.2) self.max_health = 100 self.health = self.max_health class plants(Entity): def __init__(self, **kwargs): super().__init__(model='cube', color=color.gray, scale=2, collider='box', position=Vec3(1,0,2), origin_y=-.5) self.health_bar = Entity(parent=self, model='quad', color=color.red, scale_y=.1, y=1.2) self.max_health = 100 self.health = self.max_health class Earth(Entity): def __init__(self, **kwargs): super().__init__(model='cube', color=color.gray, scale=2, collider='box', position=Vec3(1,0,2), origin_y=-.5) self.health_bar = Entity(parent=self, model='quad', color=color.red, scale_y=.1, y=1.2) self.max_health = 100 self.health = self.max_health b = Beings() p = Player() def update(): Ground() p.z += (held_keys['w'] - held_keys['s']) * time.dt * 6 p.x += (held_keys['d'] - held_keys['a']) * time.dt * 6 if p.intersects(b).hit: b.color = color.lime print('player is inside trigger box') else: b.color = color.gray app.run() ```
2022/08/30
[ "https://Stackoverflow.com/questions/73539012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19353262/" ]
You can add this in another migration file. ```php use Illuminate\Support\Facades\DB; public function up() { // ini_set('memory_limit', '-1'); <-- you can add this in case the file is big DB::unprepared(file_get_contents('path/to/dump.sql')); } ```
You're not limited to migration or migration related procedures when writing a migration. So yes you can run insert queries etc. Safer would be to separate table creation migration and data insert migration. But you may also do it in same migration too. ``` Schema::create('your_tables', function (Blueprint $table) { //table properties here $table->id(); }); //then you can do inserts/creates etc. Make sure this table's model is defined ! YourTable::create(...); //if you want to run SQL file: $process = new Process([ 'mysql', '-h', DB::getConfig('host'), '-u', DB::getConfig('username'), '-p' . DB::getConfig('password'), DB::getConfig('database'), '-e', "source path/to/schema.sql" ]); $process->run(); ``` Process is a symfony component. So we are running the SQL file directly from MySQL console. In other words, this won't go through Laravel ORM. I suggest you use process otherwise it might fail with big and complex SQL files. In your case 35k might be big depending on row size. Remember, it is safer to do table creation and data insertion in separate files. This is the mentality of migration, one step at a time so it's easier to rollback later on.
59,472,319
The question is probably rather unclear, but i did not how to formulate it, maybe that was the reason why i was not able to find solution to this puzzle i have. anyway, here is an example of what i want to accomplish: ``` <Calendar tileContent={({ activeStartDate, date, view }) => this.renderGames(date, view) } /> ``` This is an example from npm package react-calendar, but i am sure you know what i mean. The param tileContent gets passed function that already has destructured object, and then i run my own function with data i get from that function. I was thinking that this was done by executing function in child where i would pass an object (or single param, i just use object as an example).
2019/12/24
[ "https://Stackoverflow.com/questions/59472319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11740922/" ]
`-1100` means `NSURLErrorFileDoesNotExist`. Also there is a possibility, that the server does not return a file [to specific country](https://github.com/SDWebImage/SDWebImage/issues/986#issuecomment-93899157) or due to [specific symbols](https://github.com/SDWebImage/SDWebImage/issues/1126) in the `urlString`. In this case you could apply the following encoding: `stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding`. You could also use [SDWebImageRetryFailed](https://github.com/SDWebImage/SDWebImage/blob/319322fbd55d2d6d3fc4076f5250997be5872c19/Docs/SDWebImage-5.0-Migration-guide.md#error-codes-and-domain) as it described in the [documentation](https://github.com/SDWebImage/SDWebImage/blob/3f29a3ef1e5b980f1f31949f22938525bd5dfe12/SDWebImage/MapKit/MKAnnotationView%2BWebCache.h#L118), more about [this flag](https://github.com/SDWebImage/SDWebImage/blob/96bb7b753e0759368846c9a987fd72cee7d0db7d/SDWebImage/Core/SDWebImageDefine.h#L57): ``` storeImg.sd_setImage(with: urlEncoded, placeholderImage: UIImage(named: Constants.storeImagePlaceorderImage), options: .retryFailed) { // handle result completion } ``` You could test your broken link with the following: ```swift import UIKit import SDWebImage import WebKit extension String { var encoded: String { return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" } } class ViewController: UIViewController { let testURL = "https://i.groupme.com/638x640.jpeg.d4f31c747b534baca03d12db5a2b6193" let testURLShouldEncode = "https://via.placeholder.com/468x60?text=Visit Blogging.com Now" var storeImg: UIImageView! var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() configureUI() if let urlEncoded = URL(string: testURLShouldEncode.encoded), !(testURL.isEmpty) { storeImg.sd_setImage(with: urlEncoded, placeholderImage: UIImage(named: Constants.storeImagePlaceorderImage)) { [unowned self] (image, error, cahce, url) in print("image \(String(describing: image))") print("error \(String(describing: error?.localizedDescription))") print("cache \(cahce)") print("url \(String(describing: url))") if (error != nil) { let request = URLRequest(url: urlEncoded) self.webView.load(request) } } } else { self.storeImg.image = UIImage(named: Constants.storeImagePlaceorderImage) } } func configureUI() { storeImg = UIImageView() storeImg.contentMode = .center storeImg.translatesAutoresizingMaskIntoConstraints = false webView = WKWebView() webView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(storeImg) view.addSubview(webView) view.backgroundColor = .blue storeImg.backgroundColor = .yellow webView.backgroundColor = .orange storeImg.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true storeImg.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true storeImg.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true storeImg.heightAnchor.constraint(equalToConstant: 300).isActive = true webView.topAnchor.constraint(equalTo: storeImg.safeAreaLayoutGuide.bottomAnchor).isActive = true webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true } } ```
I have encountered the problem too, and my solution was done by ADDING `"SD_WEBP=1"` into your `SDWebImage` target -> `Build Settings` -> `Preprocessor Macros`. [![enter image description here](https://i.stack.imgur.com/6r1st.png)](https://i.stack.imgur.com/6r1st.png)
392,931
Similes and metaphors drawn analogies, compare things. Is there another rhetorical term for when someone wants to draw a ***disanalogy***? I can imagine a poet or at least rhetorician wanting to say e.g. that their lover's eyes are *not like* pearls, but far lovelier.
2017/06/07
[ "https://english.stackexchange.com/questions/392931", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
Have you looked at *dissimile*? > > a [rhetorical] comparison of two dissimilar objects for the purpose of illustration > > > <https://www.collinsdictionary.com/us/dictionary/english/dissimile>
If the contrast is explicit then it's exactly that, a literary contrast. > > In literature, an author uses contrast when he or she describes the > difference(s) between two or more entities. For example, in the first > four lines of William Shakespeare's Sonnet 130, Shakespeare contrasts > a mistress to the sun, coral, snow, and wire. > > > [Contrast](https://en.wikipedia.org/wiki/Contrast_(literary)) is the antonym of simile > > > Not sure if an *implicit contrast* has a term
237,300
I understand Cantor's diagonal argument, but it just doesn't seem to jive for some reason. Lets say I assign the following numbers ad infinitum... 1. $1\to 0.1$ 2. $2\to 0.2$ 3. $3\to 0.3$ ... 4. $10\to 0.10$ 5. $11\to 0.11$ and so on... How come there's supposedly at least one more real number than you can map to a member of $\mathbb{N}$?
2012/11/14
[ "https://math.stackexchange.com/questions/237300", "https://math.stackexchange.com", "https://math.stackexchange.com/users/39748/" ]
If we apply the Cantor diagonal argument to the list you have there, and assign the $n$th digit in our constructed number to be 0 if the $n$th digit of the $n$th number in the list is 1, and 1 if it isn't, we construct the real number $0.0111111\ldots$ (which happens to be equal to $\frac1{90}$) and in fact is not anywhere in your list, since there is no integer that looks like $0111111\ldots$. So the construction worked fine: you presented what you claim is a list of all real numbers, and then the construction produced a real number that you omitted. Where's the problem? (If you're not happy with that, perhaps it's enough to point out that your list not only omits all the repeating decimals such as $\frac 13, \frac23, \frac 16, \frac 17, \frac 27\ldots$, but also all the numbers less than 1/10. So it's not even a list of all the *rational* numbers.)
Let's look at the interval $0 < x < 1.$ Let's assume all of its numbers are countable, i.e. they are listable. Let's say the list goes like: 1. 0.12345... 2. 0.32145... 3. 0.87654... 4. 0.28374... 5. 0.67676... 6. etc... From the list, I make a new number. Its first decimal place is the same as the first number's, its second decimal place is the same as the second number's, its third decimal place is the same as the third number's, etc. The new number I get is: $$0.12676...$$ Using this number, I create a new number. If a digit is a $1$ then I change it to a $2$. If a digit is anything else then I change it to a $1$. Thus: $$0.12676... \mapsto 0.21111...$$ This new number, $0.21111...$ is not on my list. It's not the first number because it's different in the first place, it's not the second number because it's different in the second place, it's not the third number because it's different in the third place, it's not the fourth number because it's different in the fourth place, etc. It follows that my new number is not in my list, and so I could not have listed all of the numbers $0 < x < 1$. Thus, by contradiction, the interval is not countable. Check out [this YouTube clip](http://youtu.be/elvOZm0d4H0).
237,300
I understand Cantor's diagonal argument, but it just doesn't seem to jive for some reason. Lets say I assign the following numbers ad infinitum... 1. $1\to 0.1$ 2. $2\to 0.2$ 3. $3\to 0.3$ ... 4. $10\to 0.10$ 5. $11\to 0.11$ and so on... How come there's supposedly at least one more real number than you can map to a member of $\mathbb{N}$?
2012/11/14
[ "https://math.stackexchange.com/questions/237300", "https://math.stackexchange.com", "https://math.stackexchange.com/users/39748/" ]
If we apply the Cantor diagonal argument to the list you have there, and assign the $n$th digit in our constructed number to be 0 if the $n$th digit of the $n$th number in the list is 1, and 1 if it isn't, we construct the real number $0.0111111\ldots$ (which happens to be equal to $\frac1{90}$) and in fact is not anywhere in your list, since there is no integer that looks like $0111111\ldots$. So the construction worked fine: you presented what you claim is a list of all real numbers, and then the construction produced a real number that you omitted. Where's the problem? (If you're not happy with that, perhaps it's enough to point out that your list not only omits all the repeating decimals such as $\frac 13, \frac23, \frac 16, \frac 17, \frac 27\ldots$, but also all the numbers less than 1/10. So it's not even a list of all the *rational* numbers.)
*How come there's supposedly at least one more real number than you can map to a member of $\mathbb N$?* Well, suppose there isn't - that Cantor's conclusion, his *theorem*, is wrong, because our enumeration covers all real numbers. Wonderful, but let us see what happens when we take our enumeration and apply Cantor's *diagonal technique* to obtain a real number that can't be in this sequence. But that contradicts our supposition! Hence our supposition - that we can have an enumeration of all reals - is false. That the argument can be applied to any enumeration is what it takes for Cantor's theorem to be true. Wilfred Hodges wrote an excellent survey of wrong refutations of Catonr' argument, his *An Editor Recalls Some Hopeless Papers* ([Postscript](http://www.math.ucla.edu/~asl/bsl/0401/0401-001.ps)). Section 7, dealing with how the counterfactual assumption confuses, might be of particular interest.
237,300
I understand Cantor's diagonal argument, but it just doesn't seem to jive for some reason. Lets say I assign the following numbers ad infinitum... 1. $1\to 0.1$ 2. $2\to 0.2$ 3. $3\to 0.3$ ... 4. $10\to 0.10$ 5. $11\to 0.11$ and so on... How come there's supposedly at least one more real number than you can map to a member of $\mathbb{N}$?
2012/11/14
[ "https://math.stackexchange.com/questions/237300", "https://math.stackexchange.com", "https://math.stackexchange.com/users/39748/" ]
If we apply the Cantor diagonal argument to the list you have there, and assign the $n$th digit in our constructed number to be 0 if the $n$th digit of the $n$th number in the list is 1, and 1 if it isn't, we construct the real number $0.0111111\ldots$ (which happens to be equal to $\frac1{90}$) and in fact is not anywhere in your list, since there is no integer that looks like $0111111\ldots$. So the construction worked fine: you presented what you claim is a list of all real numbers, and then the construction produced a real number that you omitted. Where's the problem? (If you're not happy with that, perhaps it's enough to point out that your list not only omits all the repeating decimals such as $\frac 13, \frac23, \frac 16, \frac 17, \frac 27\ldots$, but also all the numbers less than 1/10. So it's not even a list of all the *rational* numbers.)
Cantor's diagonal is a trick to show that given **any** list of reals, a real can be found that is not in the list. First a few properties: * You know that two numbers differ if just one digit differs. * If a number shares the previous property with every number in a set, it is not part of the set. Cantor's diagonal is a clever solution to finding a number which satisfies these properties. The number which is the diagonal is transformed s.t. it doesn't share the first digit of the first number nor the second digit with the second and so on. Thus the number is unique to the list. This is why Cantor's diagonal as a method proves the result that the reals are uncountable.
237,300
I understand Cantor's diagonal argument, but it just doesn't seem to jive for some reason. Lets say I assign the following numbers ad infinitum... 1. $1\to 0.1$ 2. $2\to 0.2$ 3. $3\to 0.3$ ... 4. $10\to 0.10$ 5. $11\to 0.11$ and so on... How come there's supposedly at least one more real number than you can map to a member of $\mathbb{N}$?
2012/11/14
[ "https://math.stackexchange.com/questions/237300", "https://math.stackexchange.com", "https://math.stackexchange.com/users/39748/" ]
Let's look at the interval $0 < x < 1.$ Let's assume all of its numbers are countable, i.e. they are listable. Let's say the list goes like: 1. 0.12345... 2. 0.32145... 3. 0.87654... 4. 0.28374... 5. 0.67676... 6. etc... From the list, I make a new number. Its first decimal place is the same as the first number's, its second decimal place is the same as the second number's, its third decimal place is the same as the third number's, etc. The new number I get is: $$0.12676...$$ Using this number, I create a new number. If a digit is a $1$ then I change it to a $2$. If a digit is anything else then I change it to a $1$. Thus: $$0.12676... \mapsto 0.21111...$$ This new number, $0.21111...$ is not on my list. It's not the first number because it's different in the first place, it's not the second number because it's different in the second place, it's not the third number because it's different in the third place, it's not the fourth number because it's different in the fourth place, etc. It follows that my new number is not in my list, and so I could not have listed all of the numbers $0 < x < 1$. Thus, by contradiction, the interval is not countable. Check out [this YouTube clip](http://youtu.be/elvOZm0d4H0).
*How come there's supposedly at least one more real number than you can map to a member of $\mathbb N$?* Well, suppose there isn't - that Cantor's conclusion, his *theorem*, is wrong, because our enumeration covers all real numbers. Wonderful, but let us see what happens when we take our enumeration and apply Cantor's *diagonal technique* to obtain a real number that can't be in this sequence. But that contradicts our supposition! Hence our supposition - that we can have an enumeration of all reals - is false. That the argument can be applied to any enumeration is what it takes for Cantor's theorem to be true. Wilfred Hodges wrote an excellent survey of wrong refutations of Catonr' argument, his *An Editor Recalls Some Hopeless Papers* ([Postscript](http://www.math.ucla.edu/~asl/bsl/0401/0401-001.ps)). Section 7, dealing with how the counterfactual assumption confuses, might be of particular interest.
237,300
I understand Cantor's diagonal argument, but it just doesn't seem to jive for some reason. Lets say I assign the following numbers ad infinitum... 1. $1\to 0.1$ 2. $2\to 0.2$ 3. $3\to 0.3$ ... 4. $10\to 0.10$ 5. $11\to 0.11$ and so on... How come there's supposedly at least one more real number than you can map to a member of $\mathbb{N}$?
2012/11/14
[ "https://math.stackexchange.com/questions/237300", "https://math.stackexchange.com", "https://math.stackexchange.com/users/39748/" ]
Let's look at the interval $0 < x < 1.$ Let's assume all of its numbers are countable, i.e. they are listable. Let's say the list goes like: 1. 0.12345... 2. 0.32145... 3. 0.87654... 4. 0.28374... 5. 0.67676... 6. etc... From the list, I make a new number. Its first decimal place is the same as the first number's, its second decimal place is the same as the second number's, its third decimal place is the same as the third number's, etc. The new number I get is: $$0.12676...$$ Using this number, I create a new number. If a digit is a $1$ then I change it to a $2$. If a digit is anything else then I change it to a $1$. Thus: $$0.12676... \mapsto 0.21111...$$ This new number, $0.21111...$ is not on my list. It's not the first number because it's different in the first place, it's not the second number because it's different in the second place, it's not the third number because it's different in the third place, it's not the fourth number because it's different in the fourth place, etc. It follows that my new number is not in my list, and so I could not have listed all of the numbers $0 < x < 1$. Thus, by contradiction, the interval is not countable. Check out [this YouTube clip](http://youtu.be/elvOZm0d4H0).
Cantor's diagonal is a trick to show that given **any** list of reals, a real can be found that is not in the list. First a few properties: * You know that two numbers differ if just one digit differs. * If a number shares the previous property with every number in a set, it is not part of the set. Cantor's diagonal is a clever solution to finding a number which satisfies these properties. The number which is the diagonal is transformed s.t. it doesn't share the first digit of the first number nor the second digit with the second and so on. Thus the number is unique to the list. This is why Cantor's diagonal as a method proves the result that the reals are uncountable.
237,300
I understand Cantor's diagonal argument, but it just doesn't seem to jive for some reason. Lets say I assign the following numbers ad infinitum... 1. $1\to 0.1$ 2. $2\to 0.2$ 3. $3\to 0.3$ ... 4. $10\to 0.10$ 5. $11\to 0.11$ and so on... How come there's supposedly at least one more real number than you can map to a member of $\mathbb{N}$?
2012/11/14
[ "https://math.stackexchange.com/questions/237300", "https://math.stackexchange.com", "https://math.stackexchange.com/users/39748/" ]
*How come there's supposedly at least one more real number than you can map to a member of $\mathbb N$?* Well, suppose there isn't - that Cantor's conclusion, his *theorem*, is wrong, because our enumeration covers all real numbers. Wonderful, but let us see what happens when we take our enumeration and apply Cantor's *diagonal technique* to obtain a real number that can't be in this sequence. But that contradicts our supposition! Hence our supposition - that we can have an enumeration of all reals - is false. That the argument can be applied to any enumeration is what it takes for Cantor's theorem to be true. Wilfred Hodges wrote an excellent survey of wrong refutations of Catonr' argument, his *An Editor Recalls Some Hopeless Papers* ([Postscript](http://www.math.ucla.edu/~asl/bsl/0401/0401-001.ps)). Section 7, dealing with how the counterfactual assumption confuses, might be of particular interest.
Cantor's diagonal is a trick to show that given **any** list of reals, a real can be found that is not in the list. First a few properties: * You know that two numbers differ if just one digit differs. * If a number shares the previous property with every number in a set, it is not part of the set. Cantor's diagonal is a clever solution to finding a number which satisfies these properties. The number which is the diagonal is transformed s.t. it doesn't share the first digit of the first number nor the second digit with the second and so on. Thus the number is unique to the list. This is why Cantor's diagonal as a method proves the result that the reals are uncountable.
30,455,386
Is it possible to pass defined in 'config' section of package.json variables to browserify? All is running from 'script' section such: ``` "config": { "API": "somePathToAPI", "port": 9999 }, "scripts": { "prewatch:js": "browserify app/js/app.js -o out/bundle.js -d", "watch:js": "watchify app/js/app.js -o out/bundle.js -v -d", "start": "npm run watch:js" }... ``` The idea is to pass both API and port variables to Browserifys environment (for example proccess.argv or process.env properities accessible from window object). I'm not sure if it's important but I try to achieve this on Windows 7 machine. Or maybe this approach is wrong and You use some other technics to store Yours config variables?
2015/05/26
[ "https://Stackoverflow.com/questions/30455386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638886/" ]
All values in your `package.json` are exported to the environment. The variable names should be `$npm_package_config_API` and `$npm_package_config_port`. You can see all the exported variables by running `npm run env`. *(Depending on your version of `npm`, you may need to add the `env` script yourself: `"scripts": { "env": "env" }`)* You can even override the variables in scripts too, by prefixing them with your package name and the variable's name. Check out the examples here: [NPM Config Variables](http://blog.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool/#npmconfigvariables) You might also want to check out [Per-Package Config Settings](https://docs.npmjs.com/misc/config#per-package-config-settings). If you're just looking for a transform to keep the environment as literals in your code, checkout [`envify`](https://www.npmjs.com/package/envify).
there is no way to access them in clientside js code, but on serverside code: ``` var port = process.env.npm_package_config_port; var api = process.env.npm_package_config_API; ``` EDIT: You could create a cookie with `port` and `API` server-side and send it to the client.
9,580,642
I have one huge project that I use only for source viewing. But the building of that project required to much time. However, I want to disable the automatically build only for this project. Is it possible? thx
2012/03/06
[ "https://Stackoverflow.com/questions/9580642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/597624/" ]
Not sure what you are trying to achieve here, but you can also disable individual builders for a project via Project Properties.
Create two working sets - one with and one without the big project. Then switch between the two working sets as you need and build as you need, and try to experiment with this feature. From the help docs: > > Working sets may also be a part of a manual build workflow. With > autobuild disabled the Project > Build Working Set menu becomes > enabled. From here you are able to selectively build working sets of > your choosing. > > >
9,580,642
I have one huge project that I use only for source viewing. But the building of that project required to much time. However, I want to disable the automatically build only for this project. Is it possible? thx
2012/03/06
[ "https://Stackoverflow.com/questions/9580642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/597624/" ]
Not sure what you are trying to achieve here, but you can also disable individual builders for a project via Project Properties.
One simple solution is launch another instance of Eclipse in a separate workspace and operate this project only, with auto-build turned off. Unless your RAM is heavily loaded, a separate Eclipse instance is better choice for such need.
9,580,642
I have one huge project that I use only for source viewing. But the building of that project required to much time. However, I want to disable the automatically build only for this project. Is it possible? thx
2012/03/06
[ "https://Stackoverflow.com/questions/9580642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/597624/" ]
Not sure what you are trying to achieve here, but you can also disable individual builders for a project via Project Properties.
The best approach is to use the Inclusion and Exclusion Patterns option in the Java Build Path. For example if you want to exclude one project of being automatically build: 1- Go to its Properties->Java Build Path->Source. 2- Expand the folder in the "Source folders on the build path:" area 3- Select Exclude->Edit 4- In the exclusion patterns add \*\* Note: for more information on this patterns: [Include and Exclusion Patterns](http://help.eclipse.org/juno/index.jsp?topic=/org.eclipse.jdt.doc.user/concepts/concept-inclusion-exclusion-patterns.htm&cp=1_2_1_0_0)
48,876,073
``` $ mvn dependency:tree -Dincludes=com.fasterxml.jackson.core [INFO] Scanning for projects... Downloading from central: https://repo.maven.apache.org/maven2/org/jooq/jooq-codegen-maven/3.9.1/jooq-codegen-maven-3.9.1.pom ``` I am executing this command, but it takes forever and got stuck here. My network is all good and I tried the command at different time but ended with the same. What might be the problem?
2018/02/20
[ "https://Stackoverflow.com/questions/48876073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697911/" ]
I've seen all kinds of problems with this. No idea what your specific issue is but here's a few possibilities * Your traffic is going through some kind of stateful package inspection/firewall/antivirus/IDS/bluecoat/etc and it's interfering and/or silently dropping the connection * There's some issues validating the certificate * The server is offline, which happens from time to time but is unlikely * Your settings.xml file is redirectly elsewhere and that "elsewhere" location is misbehaving. A few suggestions to work around the issue * try disabling https (i know) by using settings.xml to remap the apache repo from https to http. * try disabling any antivirus/firewall (temporarily) to try and isolate the problem. * check to make sure your hard drive is not full
To troubleshoot run mvn with --debug flat to see any issues to find if mvn is stuck on any command. Based on this, if you still need help, please update this question ``` mvn --debug ... ```
17,678,586
How to install sbcl in os linux for a freshman of lisp. I found just use the command sh install.sh the error info is: src/runtime/sbcl not found, aborting installation
2013/07/16
[ "https://Stackoverflow.com/questions/17678586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1323130/" ]
If you are using the Debian or Ubuntu distributions, you can install SBCL from their repositories: just type `sudo apt-get install sbcl`.
What flavor of linux? If you use a popular distribution, e.g., debian, ubuntu, fedora, &c, then sbcl comes prepackaged: `aptitude install sbcl` or `yum install sbcl`.
17,678,586
How to install sbcl in os linux for a freshman of lisp. I found just use the command sh install.sh the error info is: src/runtime/sbcl not found, aborting installation
2013/07/16
[ "https://Stackoverflow.com/questions/17678586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1323130/" ]
If you are using the Debian or Ubuntu distributions, you can install SBCL from their repositories: just type `sudo apt-get install sbcl`.
As it says on [SBCL's download page](http://www.sbcl.org/platform-table.html), if you have git access, you can run the command `git clone git://git.code.sf.net/p/sbcl/sbcl` to get the development version to compile from. To get the binary alone, you may use the following commands depending on your CPU architecture: x86 ``` wget --trust-server-name http://downloads.sourceforge.net/project/sbcl/sbcl/1.0.58/sbcl-1.0.58-x86-linux-binary.tar.bz2?r=http%3A%2F%2Fwww.sbcl.org%2Fplatform-table.html&ts=1374541378&use_mirror=hivelocity ``` AMD64 (Note that this is a newer version) ``` wget --trust-server-name http://downloads.sourceforge.net/project/sbcl/sbcl/1.1.9/sbcl-1.1.9-x86-64-linux-binary.tar.bz2?r=http%3A%2F%2Fwww.sbcl.org%2Fplatform-table.html&ts=1374541416&use_mirror=iweb ```
17,678,586
How to install sbcl in os linux for a freshman of lisp. I found just use the command sh install.sh the error info is: src/runtime/sbcl not found, aborting installation
2013/07/16
[ "https://Stackoverflow.com/questions/17678586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1323130/" ]
If you are using the Debian or Ubuntu distributions, you can install SBCL from their repositories: just type `sudo apt-get install sbcl`.
in file which include to archive with sources and named INSTALL we see next text: > > end of section 2.1 > > > ... > Now you should have the same src/runtime/sbcl and output/sbcl.core > files that come with the binary distribution, and you can install > them as described in the section 1. "BINARY DISTRIBUTION". > > > the way for you are next: 1. download sbcl sources using any convenient way for you. 2. run shell terminal (may be window) and go to the sources archive path $ cd /path/to/sbcl-sources.tar.bz2 $ tar -xjvf sbcl\*.tar.bz2 $ cd sbcl [TAB COMPLETE AND ENTER] $ emacs INSTALL now you will see INSTALL file, which contains installation notes. As we will see in 2.1 section > > To build SBCL you need a working toolchain and a Common Lisp system > (see section 2.5 "Supported platforms"). > You also need approximately 128 Mb of free RAM+swap. > > > To build SBCL using alredy installed SBCL run > > > ``` $sh make.sh # may be need execute rights. run 'chmod +x make.sh' and try again ``` and go next according instruction. If you don't have existing sbcl instruction said next: > > If you don't already have an SBCL binary installed as "sbcl" on your > system, you'll need to tell make.sh what Lisp to use as the > cross-compilation host. For example, to use CMUCL (assuming has > been installed under its default name "lisp") as the > cross-compilation host: > > > $ sh make.sh --xc-host='lisp -batch -noinit' > > > assuming supported lisp platforms see 2.5 section. Generally, if you attentively read INSTALL file you will able to do it easy and quickly. Have fun and happy new year.
17,678,586
How to install sbcl in os linux for a freshman of lisp. I found just use the command sh install.sh the error info is: src/runtime/sbcl not found, aborting installation
2013/07/16
[ "https://Stackoverflow.com/questions/17678586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1323130/" ]
If you are using the Debian or Ubuntu distributions, you can install SBCL from their repositories: just type `sudo apt-get install sbcl`.
install the binary first <http://sourceforge.net/projects/sbcl/files/sbcl/1.2.7/sbcl-1.2.7> then install the latest version <http://sourceforge.net/projects/sbcl/files/sbcl/1.2.16/sbcl-1.2.16-source.tar.bz2/download?use_mirror=iweb&download=>
33,875,840
The first way looks like this: ``` int *p_number = &number; ``` And the second like: ``` int *p_number; p_number = &number; ``` I don't get why the first way look as it looks, because I get that `p_number` is the address of `int *p_number` and we are basically giving `p_number` the address of `number` with the `&` operator. But why do we initialize `*p_number` with `&number`? Wouldn't that mean that the pointee of `p_number` is the address of number?
2015/11/23
[ "https://Stackoverflow.com/questions/33875840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2608572/" ]
I believe what's confusing you is the syntax ``` int *p_number = &number; ``` well, you can rewrite it as ``` int* p_number = &number; ``` which is same as ``` int *p_number; p_number = &number; ``` The first one is actually a combined step of definition and initialization.
``` int *p_number = &number; ``` This consists of two parts: a declartion of `p_number`, followed by its initializer `= &number` (read as "is address of number"). ``` int *p_number; p_number = &number; ``` This does the same, but is conceptually a bit different. The first line is the declaration (same as in previous example). The second line is an *assigment* and it is a statement.
33,875,840
The first way looks like this: ``` int *p_number = &number; ``` And the second like: ``` int *p_number; p_number = &number; ``` I don't get why the first way look as it looks, because I get that `p_number` is the address of `int *p_number` and we are basically giving `p_number` the address of `number` with the `&` operator. But why do we initialize `*p_number` with `&number`? Wouldn't that mean that the pointee of `p_number` is the address of number?
2015/11/23
[ "https://Stackoverflow.com/questions/33875840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2608572/" ]
I believe what's confusing you is the syntax ``` int *p_number = &number; ``` well, you can rewrite it as ``` int* p_number = &number; ``` which is same as ``` int *p_number; p_number = &number; ``` The first one is actually a combined step of definition and initialization.
Only the first of these is initializing the pointer. The second creates an uninitialized pointer, and then assigns a value to it. The net effect of these is the same (you have a pointer variable that points at a particular thing), and the code generated by the compiler is likely identical. The thing that seems to be confusing you is that the syntax of declarations and initializers is subtly different from the syntax of assignments. In particular, a `*` in a declaration means that you are declaring a pointer and *not* dereferencing it, while in an expression, a `*` means that you *are* dereferencing. This kind of subtle difference is considered a wart by some and a feature by others.
33,875,840
The first way looks like this: ``` int *p_number = &number; ``` And the second like: ``` int *p_number; p_number = &number; ``` I don't get why the first way look as it looks, because I get that `p_number` is the address of `int *p_number` and we are basically giving `p_number` the address of `number` with the `&` operator. But why do we initialize `*p_number` with `&number`? Wouldn't that mean that the pointee of `p_number` is the address of number?
2015/11/23
[ "https://Stackoverflow.com/questions/33875840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2608572/" ]
Only the first of these is initializing the pointer. The second creates an uninitialized pointer, and then assigns a value to it. The net effect of these is the same (you have a pointer variable that points at a particular thing), and the code generated by the compiler is likely identical. The thing that seems to be confusing you is that the syntax of declarations and initializers is subtly different from the syntax of assignments. In particular, a `*` in a declaration means that you are declaring a pointer and *not* dereferencing it, while in an expression, a `*` means that you *are* dereferencing. This kind of subtle difference is considered a wart by some and a feature by others.
``` int *p_number = &number; ``` This consists of two parts: a declartion of `p_number`, followed by its initializer `= &number` (read as "is address of number"). ``` int *p_number; p_number = &number; ``` This does the same, but is conceptually a bit different. The first line is the declaration (same as in previous example). The second line is an *assigment* and it is a statement.
13,494,551
I'm generating tables of buttons with php ``` echo ' <td"> <form action="test.php" method="POST"> <input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'"> <input type="hidden" id="service" name="service" value="'.$flavor.'"> <input type="hidden" id="running" name="running" value="false"> <input type="submit" value="OFF" class="button"> </form> </td>'; ``` I want to send the values without reloading via jquery ajax and I'm using this code for it: $(".button").click(function() { $('.error').hide(); ``` var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value; $.ajax({ type: "POST", url: "test.php", data: dataString, success: function() { alert ("Success"); } }); return false; }); ``` Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs". Is there a more elegant way to do this. Number of forms is dynamic.
2012/11/21
[ "https://Stackoverflow.com/questions/13494551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1745424/" ]
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique. ``` echo ' <td"> <form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '> <input type="hidden" name="node" value="'.$fnode->{'name'}.'"> <input type="hidden" name="service" value="'.$flavor.'"> <input type="hidden" name="running" value="false"> <input type="submit" value="OFF" class="button"> </form> </td>'; $(".button").click(function(e) { e.preventDefault(); $('.error').hide(); var $form = $(this).closest('form'), // the closest parent form dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding $.ajax({ type: "POST", url: "test.php", data: dataString, success: function() { alert ("Success submitting form ID " + $form.attr('id')); // you can now modify the form you submitted } }); return false; }); ```
The best way is to use unique IDs for form elements. Another way is to set classes to multiple elements with the same name. However, the following approach is much preferable: ``` $("form").on("submit", function() { $.ajax({ type: "POST", url: "test.php", data: $(this).serialize(), success: function() { alert ("Success"); } }); return false; }); ``` (But anyway don't forget to remove duplicating `id` attributes from the form elements.)
13,494,551
I'm generating tables of buttons with php ``` echo ' <td"> <form action="test.php" method="POST"> <input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'"> <input type="hidden" id="service" name="service" value="'.$flavor.'"> <input type="hidden" id="running" name="running" value="false"> <input type="submit" value="OFF" class="button"> </form> </td>'; ``` I want to send the values without reloading via jquery ajax and I'm using this code for it: $(".button").click(function() { $('.error').hide(); ``` var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value; $.ajax({ type: "POST", url: "test.php", data: dataString, success: function() { alert ("Success"); } }); return false; }); ``` Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs". Is there a more elegant way to do this. Number of forms is dynamic.
2012/11/21
[ "https://Stackoverflow.com/questions/13494551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1745424/" ]
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique. ``` echo ' <td"> <form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '> <input type="hidden" name="node" value="'.$fnode->{'name'}.'"> <input type="hidden" name="service" value="'.$flavor.'"> <input type="hidden" name="running" value="false"> <input type="submit" value="OFF" class="button"> </form> </td>'; $(".button").click(function(e) { e.preventDefault(); $('.error').hide(); var $form = $(this).closest('form'), // the closest parent form dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding $.ajax({ type: "POST", url: "test.php", data: dataString, success: function() { alert ("Success submitting form ID " + $form.attr('id')); // you can now modify the form you submitted } }); return false; }); ```
You can give each submit buttons an id: ``` <input id="button-1" type="submit" value="OFF" class="button"> ``` and then trigger the event on click of a specific button: ``` $("#button-1").click(function() { ... }); ```
70
Is it because it has super massive gravity and energy? Or is it some sort of an anti-light component in it because it used to be a star?
2013/09/25
[ "https://astronomy.stackexchange.com/questions/70", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/69/" ]
Gravity is a force, and it need not have a "speed"1. A gravitational body sets up a gravitational field around itself. Note that by the time the light wave approaches the body, *this field has already been set up*. The gravitational force does not need to "reach out" and "catch up to the light" — it's already there. In fact, it's not even really a force (though we can treat it as one to an approximation). Gravity bends the fabric of spacetime around it, messing with the meaning of a "straight line". From different reference frames, different lines appear straight. To the light wave, the inspiraling path seems "straight" and thus it follows that path. To an external observer, the light wave is not going straight. 1. It does, but that's the speed at which changes to the field propagate, not the speed at which it "catches up" with other things. Changes in the gravitational field propagate at lightspeed.
What happens is that the gravity produced by a black hole is simply so great that it warps the spacetime fabric in such a way that any light which crosses the [event horizon](http://en.wikipedia.org/wiki/Event_horizon) is funneled in by the fabric itself - it's a crazy notion, and one hard to get your head around. This diagram might help: ![enter image description here](https://i.stack.imgur.com/DIswU.gif)
70
Is it because it has super massive gravity and energy? Or is it some sort of an anti-light component in it because it used to be a star?
2013/09/25
[ "https://astronomy.stackexchange.com/questions/70", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/69/" ]
What happens is that the gravity produced by a black hole is simply so great that it warps the spacetime fabric in such a way that any light which crosses the [event horizon](http://en.wikipedia.org/wiki/Event_horizon) is funneled in by the fabric itself - it's a crazy notion, and one hard to get your head around. This diagram might help: ![enter image description here](https://i.stack.imgur.com/DIswU.gif)
Well, I have no astronomical background, so in layman's terms, > > If nothing travels at the speed of light, except light, how can a black hole also pull light into itself? > > > I believe OP is confused over how a gravity wave can capture light if both can travel at most at the speed C. It does not work quite that way. Say you move a massive BH from position X to position Y and an observer is at 1 LightYear away from Y. Then, the observer will not feel the gravitation effect of BH until 1 year because that's how much it will take a gravity waves to reach to observer. That is, its changes in gravitational field "Delta" propagate at the speed of light. As others have mentioned, gravity bends/shapes the spacetime fabric, so after one year, at observer, spacetime is bend according to the gravity of BH at Y. Thus, any light that passes near to the observer will bend as it follows the spacetime. Plus, the curvature of space BH create in their vicinity is so severe that space is wrapped completely around itself and hence light can not escape. Refer to [this](http://clarkplanetarium.org/cosmic-quiz-why-cant-light-escape-a-black-hole/) for simple explanation.
70
Is it because it has super massive gravity and energy? Or is it some sort of an anti-light component in it because it used to be a star?
2013/09/25
[ "https://astronomy.stackexchange.com/questions/70", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/69/" ]
Gravity is a force, and it need not have a "speed"1. A gravitational body sets up a gravitational field around itself. Note that by the time the light wave approaches the body, *this field has already been set up*. The gravitational force does not need to "reach out" and "catch up to the light" — it's already there. In fact, it's not even really a force (though we can treat it as one to an approximation). Gravity bends the fabric of spacetime around it, messing with the meaning of a "straight line". From different reference frames, different lines appear straight. To the light wave, the inspiraling path seems "straight" and thus it follows that path. To an external observer, the light wave is not going straight. 1. It does, but that's the speed at which changes to the field propagate, not the speed at which it "catches up" with other things. Changes in the gravitational field propagate at lightspeed.
Well, I have no astronomical background, so in layman's terms, > > If nothing travels at the speed of light, except light, how can a black hole also pull light into itself? > > > I believe OP is confused over how a gravity wave can capture light if both can travel at most at the speed C. It does not work quite that way. Say you move a massive BH from position X to position Y and an observer is at 1 LightYear away from Y. Then, the observer will not feel the gravitation effect of BH until 1 year because that's how much it will take a gravity waves to reach to observer. That is, its changes in gravitational field "Delta" propagate at the speed of light. As others have mentioned, gravity bends/shapes the spacetime fabric, so after one year, at observer, spacetime is bend according to the gravity of BH at Y. Thus, any light that passes near to the observer will bend as it follows the spacetime. Plus, the curvature of space BH create in their vicinity is so severe that space is wrapped completely around itself and hence light can not escape. Refer to [this](http://clarkplanetarium.org/cosmic-quiz-why-cant-light-escape-a-black-hole/) for simple explanation.
45,884,963
I have 575 bz2 files with average size 3G and need to convert them to .gz format to make them compatible with a downstream pipeline. ``` $ ll -h | head total 1.4T drwxrws---+ 1 dz33 dcistat 24K Aug 23 09:21 ./ drwxrws---+ 1 dz33 dcistat 446 Aug 22 11:57 ../ -rw-rw---- 1 dz33 dcistat 2.0G Aug 22 11:38 DRR091550_1.fastq.bz2 -rw-rw---- 1 dz33 dcistat 2.0G Aug 22 11:38 DRR091550_2.fastq.bz2 -rw-rw---- 1 dz33 dcistat 2.0G Aug 22 11:38 DRR091551_1.fastq.bz2 -rw-rw---- 1 dz33 dcistat 2.0G Aug 22 11:38 DRR091551_2.fastq.bz2 -rw-rw---- 1 dz33 dcistat 1.9G Aug 22 11:38 DRR091552_1.fastq.bz2 -rw-rw---- 1 dz33 dcistat 1.9G Aug 22 11:38 DRR091552_2.fastq.bz2 -rw-rw---- 1 dz33 dcistat 1.8G Aug 22 11:38 DRR091553_1.fastq.bz2 $ ll | wc -l 575 ``` For a single file I probably can do `bzcat a.bz2 | gzip -c >a.gz`, but I am wondering how to convert them entirely with one command or loop in bash/linux.
2017/08/25
[ "https://Stackoverflow.com/questions/45884963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3015453/" ]
Do them simply and fast in parallel with **GNU Parallel**: ``` parallel --dry-run 'bzcat {} | gzip -c > {.}.gz' ::: *bz2 ``` **Sample Output** ``` bzcat a.bz2 | gzip -c > a.gz bzcat b.bz2 | gzip -c > b.gz bzcat c.bz2 | gzip -c > c.gz ``` If you like how it looks, remove the `--dry-run`. Maybe add a progress meter with `--bar` or `--progress`.
In a terminal, change directory to the one containing the .bz files, then use the following command: ``` for f in *.bz; do bzcat "$f" | gzip -c >"${f%.*}.gz"; done ``` This will process each file, one at a time, and give the .gz file the name of the .bz file. Example: `DRR091550_1.fastq.bz2` will become `DRR091550_1.fastq.gz`.
1,704,474
Determine all the holomorphic functions $f$ from the open unit disk $D=\{z:|z|<1\}$ to whole complex plane which satisfies $f''(\frac{1}{n})+f(\frac{1}{n})=0$ for all $n=2,3,4,\ldots$ At first when i saw the differential equation, all i thought is the sine and cosine function, but the trouble is i dont know how should i use the given unit disk and the "$\frac{1}{n}$" in the parentheses. Anyone can guide me or give some hints for me?
2016/03/19
[ "https://math.stackexchange.com/questions/1704474", "https://math.stackexchange.com", "https://math.stackexchange.com/users/317077/" ]
Some people are mentioning the "identity theorem", which is reported in [this Wikipedia article](https://en.wikipedia.org/wiki/Identity_theorem) to say that if two holomorphic functions defined on some open subset $D$ of the plane agree with each other on some non-empty open subset of $D$, then the agree on $D$. But here what you're given is not agreement on some non-empty open subset of $D$, but satisfaction of a differential equation on a convergent sequence of points in $D$. You know $f$ is holomorphic in $D$; hence according to the proof given in [this article](https://en.wikipedia.org/wiki/Analyticity_of_holomorphic_functions), we have $$ f(z) = \sum\_{n=0}^\infty \frac{f^{(n)}(0)}{n!} z^n \tag 1 $$ for all $z$ in $D$ (generally for all $z$ closer to $0$ than the nearest point to which $f$ cannot be analytically continued, and there are no such ill-behaved points within the disk $D$). Power series can be differentiated term by term within the interior of their disk of convergence. So if you know $(1)$ and if you can show that $f''(0)+f(0)=0$, then all of the coefficients of the power series will be determined by $f(0)$ and $f'(0)$. And then you have a series that you know converges to $f(0)\cos z + f'(0)\sin z$. So how do you show that if $f''+f=0$ at $1/n$ for $n=2,3,4,\ldots$ then $f''+f=0$ at $0$? Here I'd think about the smooth nature of functions defined by convergent power series.
Here's a hint: let $g = f'' + f$. What then do you know about $g$? (Think identity theorem.)
36,887,692
Here is my code. ``` UIApplicationShortcutItem *bookmarksShortcutItem = [[UIApplicationShortcutItem alloc] initWithType:@"bookmarks" localizedTitle:@"Bookmarks" localizedSubtitle:@"test" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeBookmark] userInfo:@{@"type":@"bookmarks"}]; ``` So can I add my custom icon instead of UIApplicationShortcutIconTypeBookmark? Thanks in advance.
2016/04/27
[ "https://Stackoverflow.com/questions/36887692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4562216/" ]
This is how you do it: ``` UIApplicationShortcutIcon *shortcutIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"IMAGE_NAME"]; UIMutableApplicationShortcutItem *option = [[UIMutableApplicationShortcutItem alloc] initWithType:@"uniqueIdentifier" localizedTitle:@"title" localizedSubtitle:nil icon:shortcutIcon userInfo:nil]; [UIApplication sharedApplication].shortcutItems = @[option]; ```
Under UIApplicationShortcutItems you can specify your shortcuts, but you should do this in your plist rather than in the code. There you can create a dictionairy for every ShortcutAction and with UIApplicationShortcutItemIconFile you can define your own Icon. This could be helpful for you: <http://www.the-nerd.be/2015/09/30/add-3d-touch-quick-actions-tutorial/>
58,293,234
I have got a list with keywords. And I coded a method that if a string contains keyword from list, the method must remove keyword from string. Here is the method: ``` private string RemoveFromList(string sentence) { var lists = new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" }; var control = lists.Any(sentence.Contains); string result; if (control) { var index = sentence.IndexOf(lists.FirstOrDefault(sentence.Contains) ?? throw new InvalidOperationException(), StringComparison.Ordinal); result = index != -1 ? sentence.Remove(index) : sentence; } else result = sentence; return result; } var str = "ask- This is a sentence."; Message.Box(RemoveFromList(str)); // It does not give to me: This is a sentence. ``` This method does not work properly. It does not remove the keyword from the string.
2019/10/08
[ "https://Stackoverflow.com/questions/58293234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1827846/" ]
Using `string.Replace` is the simplest approach: ``` foreach (var word in lists) { sentence = sentence.Replace(word,"").Trim(); } ``` Although that will find the word in the middle of the string too. If you wanted to remove it only at the start you could use `IndexOf` check it's 0 and then take the string starting from `word.Length` using `Substring`. Or use `StartsWith`: ``` foreach (var word in lists) { if (sentence.StartsWith(word)) { sentence = sentence.Substring(word.Length).Trim(); // break; // if only one } } ```
There are 2 options for you. 1. First of all the Remove usage is incorrect. You just want to remove the keyword. If u pass 1 argument to remove it will remove from that index till end. Pass the length of keyword as second arg to Remove. s.Remove(index, len); 2. If string contains it than replace the occurrence of keyword with empty string s.Replace("keyword", "");
58,293,234
I have got a list with keywords. And I coded a method that if a string contains keyword from list, the method must remove keyword from string. Here is the method: ``` private string RemoveFromList(string sentence) { var lists = new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" }; var control = lists.Any(sentence.Contains); string result; if (control) { var index = sentence.IndexOf(lists.FirstOrDefault(sentence.Contains) ?? throw new InvalidOperationException(), StringComparison.Ordinal); result = index != -1 ? sentence.Remove(index) : sentence; } else result = sentence; return result; } var str = "ask- This is a sentence."; Message.Box(RemoveFromList(str)); // It does not give to me: This is a sentence. ``` This method does not work properly. It does not remove the keyword from the string.
2019/10/08
[ "https://Stackoverflow.com/questions/58293234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1827846/" ]
Using `string.Replace` is the simplest approach: ``` foreach (var word in lists) { sentence = sentence.Replace(word,"").Trim(); } ``` Although that will find the word in the middle of the string too. If you wanted to remove it only at the start you could use `IndexOf` check it's 0 and then take the string starting from `word.Length` using `Substring`. Or use `StartsWith`: ``` foreach (var word in lists) { if (sentence.StartsWith(word)) { sentence = sentence.Substring(word.Length).Trim(); // break; // if only one } } ```
Another option is you could create an extension since you already know what items to remove. ``` using System.Text.RegularExpressions; public static string RemoveFromList(this string sentence) { new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" }.ForEach(name => { sentence = Regex.Replace(sentence.Replace(name, string.Empty), " {2,}", " "); }); return sentence; } ``` **Useage** ``` var str = "ask- This is (app) a que- sentence.".RemoveFromList(); ``` **Note** I used `Regex.Replace` as it's possible you may have some blank spaces floating around after you remove the bad string/s, this helps ensure that doesn't happen.
58,293,234
I have got a list with keywords. And I coded a method that if a string contains keyword from list, the method must remove keyword from string. Here is the method: ``` private string RemoveFromList(string sentence) { var lists = new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" }; var control = lists.Any(sentence.Contains); string result; if (control) { var index = sentence.IndexOf(lists.FirstOrDefault(sentence.Contains) ?? throw new InvalidOperationException(), StringComparison.Ordinal); result = index != -1 ? sentence.Remove(index) : sentence; } else result = sentence; return result; } var str = "ask- This is a sentence."; Message.Box(RemoveFromList(str)); // It does not give to me: This is a sentence. ``` This method does not work properly. It does not remove the keyword from the string.
2019/10/08
[ "https://Stackoverflow.com/questions/58293234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1827846/" ]
There are 2 options for you. 1. First of all the Remove usage is incorrect. You just want to remove the keyword. If u pass 1 argument to remove it will remove from that index till end. Pass the length of keyword as second arg to Remove. s.Remove(index, len); 2. If string contains it than replace the occurrence of keyword with empty string s.Replace("keyword", "");
Another option is you could create an extension since you already know what items to remove. ``` using System.Text.RegularExpressions; public static string RemoveFromList(this string sentence) { new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" }.ForEach(name => { sentence = Regex.Replace(sentence.Replace(name, string.Empty), " {2,}", " "); }); return sentence; } ``` **Useage** ``` var str = "ask- This is (app) a que- sentence.".RemoveFromList(); ``` **Note** I used `Regex.Replace` as it's possible you may have some blank spaces floating around after you remove the bad string/s, this helps ensure that doesn't happen.
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
It's not clear what sort of "prompt" you mean. You could certainly do something like: ``` for (int i = 0; i < 6; i++) { System.out.println("Press return to continue..."); System.in.readLine(); // Do the body of the loop } ``` That's appropriate for a console app, but obviously not for (say) a Swing app. It also doesn't address the FLAG part of your sample code, because it's not clear what that's meant to mean. Are you trying to prompt the user for more information, or just confirmation to continue? If you could clarify what you're trying to achieve, that would really help. For the sake of testability, if this is for non-throwaway code you may want to extract the idea of a user prompt, so you can test with an implementation which *doesn't* actually prompt the user, but just records that it would have done so.
This would involve blocking the `Thread` that the for loop occupies. You can do this simply, but not very well, with this: ``` for(something) while(!FLAG) //Do procedure ``` Another way would be to have another `Thread` going on, and have the main thread wait for that other thread. Here's some more information: [How to make a Java thread wait for another thread's output?](https://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output)
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
It's not clear what sort of "prompt" you mean. You could certainly do something like: ``` for (int i = 0; i < 6; i++) { System.out.println("Press return to continue..."); System.in.readLine(); // Do the body of the loop } ``` That's appropriate for a console app, but obviously not for (say) a Swing app. It also doesn't address the FLAG part of your sample code, because it's not clear what that's meant to mean. Are you trying to prompt the user for more information, or just confirmation to continue? If you could clarify what you're trying to achieve, that would really help. For the sake of testability, if this is for non-throwaway code you may want to extract the idea of a user prompt, so you can test with an implementation which *doesn't* actually prompt the user, but just records that it would have done so.
Your goal is somewhat unclear. I think you want your program to keep running until you get six of a certain input and if so, that approach will work, though of course you'll need to get input from the user to move the loop forward. If your concern is that the while loop would use a lot of system resources, that will not be a problem.
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
It's not clear what sort of "prompt" you mean. You could certainly do something like: ``` for (int i = 0; i < 6; i++) { System.out.println("Press return to continue..."); System.in.readLine(); // Do the body of the loop } ``` That's appropriate for a console app, but obviously not for (say) a Swing app. It also doesn't address the FLAG part of your sample code, because it's not clear what that's meant to mean. Are you trying to prompt the user for more information, or just confirmation to continue? If you could clarify what you're trying to achieve, that would really help. For the sake of testability, if this is for non-throwaway code you may want to extract the idea of a user prompt, so you can test with an implementation which *doesn't* actually prompt the user, but just records that it would have done so.
Well, you could use `Thread.Sleep();` to pause for a little bit between flag checks, but what you are really looking for is a function that blocks while waiting for input, `System.in.readline();` blocks if I recall correctly ;) Like so: ``` int i = 0 do { if(FLAG) { //Do stuff i++; //Clear Flag } Thread.Sleep(50); //Sleep for 50 ms } while (i < 6); ``` or like so: ``` for(int i = 0; i < 6; i++) //Execute readline 6 times. { System.in.readLine(); } ```
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
When iterating through a for loop, for example, the one below, it does the following ``` for (int i = 0; i < 6; i++) { // Do stuff } ``` 1. It declares the variable `i` and assigns a value of `0`. 2. It checks the conditional `i < 6`. If true, then proceed to step 3. Otherwise go to step 6. 3. Goes through the body of the loop. 4. Increment the variable `i` due to the `i++` in the for loop header. 5. Go to step 2. 6. The loop ends. As for your objective, I'm not sure what your objective is. Are you looking to pause using a blocking method call? If so, then something like this would work: ``` for (int i = 0; i < 6; i++) { System.in.readLine(); } ``` Alternatively, you could use some sort of flag that polls to check whether the loop should proceed, such as: ``` for (int i = 0; i < 6; i++) { while (paused) { // An infinite loop that keeps on going until the pause flag is set to false } } ``` Hope this helped.
It's not clear what sort of "prompt" you mean. You could certainly do something like: ``` for (int i = 0; i < 6; i++) { System.out.println("Press return to continue..."); System.in.readLine(); // Do the body of the loop } ``` That's appropriate for a console app, but obviously not for (say) a Swing app. It also doesn't address the FLAG part of your sample code, because it's not clear what that's meant to mean. Are you trying to prompt the user for more information, or just confirmation to continue? If you could clarify what you're trying to achieve, that would really help. For the sake of testability, if this is for non-throwaway code you may want to extract the idea of a user prompt, so you can test with an implementation which *doesn't* actually prompt the user, but just records that it would have done so.
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
It's not clear what sort of "prompt" you mean. You could certainly do something like: ``` for (int i = 0; i < 6; i++) { System.out.println("Press return to continue..."); System.in.readLine(); // Do the body of the loop } ``` That's appropriate for a console app, but obviously not for (say) a Swing app. It also doesn't address the FLAG part of your sample code, because it's not clear what that's meant to mean. Are you trying to prompt the user for more information, or just confirmation to continue? If you could clarify what you're trying to achieve, that would really help. For the sake of testability, if this is for non-throwaway code you may want to extract the idea of a user prompt, so you can test with an implementation which *doesn't* actually prompt the user, but just records that it would have done so.
Others have covered how to use `System.in.readLine()` to have the program explicitly require action from the user. If what you need is not to have the program wait for the user, but allow you - the programmer - to slow the program down, in order to be able to find and fix a bug, you might want to consider using a debugger as this is exactly what it is designed for. Any modern Java IDE has a debugger. The keys chosen to use it, just varies. If you are using Eclipse, you are using either F11 or Ctrl-F11 (assuming Windows) to run your program. The difference is that F11 starts your program inside a debugger and Ctrl-F11 doesn't. Put the cursor at the first line inside the for-loop, and choose Run->Toggle Breakpoint. A blue bullet will show to the left of the line. This indicates that the *breakpoint* is active - the debugger will now stop your program every time it reaches that line. Now run your program in the debugger with F11. The program stops at the line, and you can investigate your variables in the Variables pane as needed, and continue execution with F8 whenever you are ready.
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
When iterating through a for loop, for example, the one below, it does the following ``` for (int i = 0; i < 6; i++) { // Do stuff } ``` 1. It declares the variable `i` and assigns a value of `0`. 2. It checks the conditional `i < 6`. If true, then proceed to step 3. Otherwise go to step 6. 3. Goes through the body of the loop. 4. Increment the variable `i` due to the `i++` in the for loop header. 5. Go to step 2. 6. The loop ends. As for your objective, I'm not sure what your objective is. Are you looking to pause using a blocking method call? If so, then something like this would work: ``` for (int i = 0; i < 6; i++) { System.in.readLine(); } ``` Alternatively, you could use some sort of flag that polls to check whether the loop should proceed, such as: ``` for (int i = 0; i < 6; i++) { while (paused) { // An infinite loop that keeps on going until the pause flag is set to false } } ``` Hope this helped.
This would involve blocking the `Thread` that the for loop occupies. You can do this simply, but not very well, with this: ``` for(something) while(!FLAG) //Do procedure ``` Another way would be to have another `Thread` going on, and have the main thread wait for that other thread. Here's some more information: [How to make a Java thread wait for another thread's output?](https://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output)
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
When iterating through a for loop, for example, the one below, it does the following ``` for (int i = 0; i < 6; i++) { // Do stuff } ``` 1. It declares the variable `i` and assigns a value of `0`. 2. It checks the conditional `i < 6`. If true, then proceed to step 3. Otherwise go to step 6. 3. Goes through the body of the loop. 4. Increment the variable `i` due to the `i++` in the for loop header. 5. Go to step 2. 6. The loop ends. As for your objective, I'm not sure what your objective is. Are you looking to pause using a blocking method call? If so, then something like this would work: ``` for (int i = 0; i < 6; i++) { System.in.readLine(); } ``` Alternatively, you could use some sort of flag that polls to check whether the loop should proceed, such as: ``` for (int i = 0; i < 6; i++) { while (paused) { // An infinite loop that keeps on going until the pause flag is set to false } } ``` Hope this helped.
Your goal is somewhat unclear. I think you want your program to keep running until you get six of a certain input and if so, that approach will work, though of course you'll need to get input from the user to move the loop forward. If your concern is that the while loop would use a lot of system resources, that will not be a problem.
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
When iterating through a for loop, for example, the one below, it does the following ``` for (int i = 0; i < 6; i++) { // Do stuff } ``` 1. It declares the variable `i` and assigns a value of `0`. 2. It checks the conditional `i < 6`. If true, then proceed to step 3. Otherwise go to step 6. 3. Goes through the body of the loop. 4. Increment the variable `i` due to the `i++` in the for loop header. 5. Go to step 2. 6. The loop ends. As for your objective, I'm not sure what your objective is. Are you looking to pause using a blocking method call? If so, then something like this would work: ``` for (int i = 0; i < 6; i++) { System.in.readLine(); } ``` Alternatively, you could use some sort of flag that polls to check whether the loop should proceed, such as: ``` for (int i = 0; i < 6; i++) { while (paused) { // An infinite loop that keeps on going until the pause flag is set to false } } ``` Hope this helped.
Well, you could use `Thread.Sleep();` to pause for a little bit between flag checks, but what you are really looking for is a function that blocks while waiting for input, `System.in.readline();` blocks if I recall correctly ;) Like so: ``` int i = 0 do { if(FLAG) { //Do stuff i++; //Clear Flag } Thread.Sleep(50); //Sleep for 50 ms } while (i < 6); ``` or like so: ``` for(int i = 0; i < 6; i++) //Execute readline 6 times. { System.in.readLine(); } ```
8,470,004
Is there a way to pause a for loop in java? So is there a way to only go forward one iteration when prompted? I read this <http://answers.yahoo.com/question/index?qid=20100212201605AAazS73> and the solution seems like it could have some problems mostly because I don't fully understand the order the for loop checks its header. The only method I could think of that could accomplish something similar is the following ``` do { if (FLAG) { //Do procedure i++; FLAG = false; } } while ( i < 6); ``` When the flag is true the procedure is done and the counter moves forward one. I don't like this, though, because it will keep looping as long as the counter is below 6, if I am not mistaken. Any ideas? -Sorry for the lack of clarity. The FLAG in my case would be a static boolean that could be called from another class. The procedure I allude to is dependent on i.
2011/12/12
[ "https://Stackoverflow.com/questions/8470004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067141/" ]
When iterating through a for loop, for example, the one below, it does the following ``` for (int i = 0; i < 6; i++) { // Do stuff } ``` 1. It declares the variable `i` and assigns a value of `0`. 2. It checks the conditional `i < 6`. If true, then proceed to step 3. Otherwise go to step 6. 3. Goes through the body of the loop. 4. Increment the variable `i` due to the `i++` in the for loop header. 5. Go to step 2. 6. The loop ends. As for your objective, I'm not sure what your objective is. Are you looking to pause using a blocking method call? If so, then something like this would work: ``` for (int i = 0; i < 6; i++) { System.in.readLine(); } ``` Alternatively, you could use some sort of flag that polls to check whether the loop should proceed, such as: ``` for (int i = 0; i < 6; i++) { while (paused) { // An infinite loop that keeps on going until the pause flag is set to false } } ``` Hope this helped.
Others have covered how to use `System.in.readLine()` to have the program explicitly require action from the user. If what you need is not to have the program wait for the user, but allow you - the programmer - to slow the program down, in order to be able to find and fix a bug, you might want to consider using a debugger as this is exactly what it is designed for. Any modern Java IDE has a debugger. The keys chosen to use it, just varies. If you are using Eclipse, you are using either F11 or Ctrl-F11 (assuming Windows) to run your program. The difference is that F11 starts your program inside a debugger and Ctrl-F11 doesn't. Put the cursor at the first line inside the for-loop, and choose Run->Toggle Breakpoint. A blue bullet will show to the left of the line. This indicates that the *breakpoint* is active - the debugger will now stop your program every time it reaches that line. Now run your program in the debugger with F11. The program stops at the line, and you can investigate your variables in the Variables pane as needed, and continue execution with F8 whenever you are ready.
44,975,964
I am creating a job which takes backup of a database and with the filename suffixing today's date. But I'm getting below error. ``` DECLARE @Query NVARCHAR(MAX) SET @Query = 'BACKUP DATABASE [DBName] TO DISK = ''D:\Backups\DBName_'+cast(convert(date,getdate())as varchar)+'.bak' EXEC sp_executeSql @Query ``` **Error Message:** ``` Msg 105, Level 15, State 1, Line 1 Unclosed quotation mark after the character string 'D:\Backups\DBName_2017-07-07.bak'. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'D:\Backups\DBName_2017-07-07.bak'. ```
2017/07/07
[ "https://Stackoverflow.com/questions/44975964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7845323/" ]
You are missing the last closing quote. It should end in `.txt'''` ``` SET @Query = 'BACKUP DATABASE [MetaCost] TO DISK = ''D:\Backups\DBName.bak_'+cast(convert(date,getdate())as varchar)+'.txt''' ``` Also typically you use the `.bak` extension for a sql database backup.
Your statement will output *BACKUP DATABASE [DBName] TO DISK = 'D:\Backups\DBName.bak\_2017-07-07.txt* You need to add `'.txt'''`
73,704,719
When we use arrays and pointers this way: ``` int *g() { int arr[] = {1, 2, 3}; return arr; } int f() { int *value = g(); for (size_t i = 0; i < 3; i++) { std::cout << value[i] << " "; } std::cout << std::endl; } int main(int argc, const char **argv) { f(); return 0; } ``` It is deleted from the stack after function g returns, so we get a segment error in the function f() But using `std::vector` this same logic works without any problem: ``` std::vector<int> g() { std::vector<int> arr = {1, 2, 3}; return arr; } int f() { std::vector<int> value = g(); for (size_t i = 0; i < value.size(); i++) { std::cout << value.at(i) << " "; } std::cout << std::endl; } int main(int argc, const char **argv) { f(); return 0; } ``` I was thinking that this is something related to the fact that we have the std::vector class acting as a container to the array but using a struct as a container delete the array either: ``` struct T { int *arr; }; T g() { T t; int arr[] = {1, 2, 3}; t.arr = arr; return t; } int f() { T value = g(); for (size_t i = 0; i < 3; i++) { std::cout << value.arr[i] << " "; } std::cout << std::endl; } int main(int argc, const char **argv) { f(); return 0; } ``` And in this case, g++ allow us to overflow the array pointer memory limits with the index subscription. Why vectors doesn't share the same problem?
2022/09/13
[ "https://Stackoverflow.com/questions/73704719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19986332/" ]
All the elements in the vector essentially count as part of the vector. And notice you are returning the vector, not a pointer to the vector. But you are returning a pointer to (the start of) the array. When the function `g` returns, the vector `arr` is destroyed but that's okay because that's not the same one that is returned. A copy of `arr` is returned. (Actually, the compiler is clever enough to reuse the same vector instead of copying it and then deleting one - but you can imagine that it makes a copy) Then `f` prints values from its own local variable `value` - no problem. By contrast, in the pointer version, `f` is printing values from the local variable `arr` inside `g`, which has already been destroyed. If `g` would return a pointer to a vector, it would have the same problem.
In the second method returning `vector<int>`. The `std::vector<int> arr` was copied to another a `temporary vector<int>`, then `std::vector<int> arr` was destroyed. Finally, the `vector<int> value` was assigned with `temporary vector<int>`, after assigning completed, `temporary vector<int>` was destroyed as well. That's what i think happening with your example.
73,704,719
When we use arrays and pointers this way: ``` int *g() { int arr[] = {1, 2, 3}; return arr; } int f() { int *value = g(); for (size_t i = 0; i < 3; i++) { std::cout << value[i] << " "; } std::cout << std::endl; } int main(int argc, const char **argv) { f(); return 0; } ``` It is deleted from the stack after function g returns, so we get a segment error in the function f() But using `std::vector` this same logic works without any problem: ``` std::vector<int> g() { std::vector<int> arr = {1, 2, 3}; return arr; } int f() { std::vector<int> value = g(); for (size_t i = 0; i < value.size(); i++) { std::cout << value.at(i) << " "; } std::cout << std::endl; } int main(int argc, const char **argv) { f(); return 0; } ``` I was thinking that this is something related to the fact that we have the std::vector class acting as a container to the array but using a struct as a container delete the array either: ``` struct T { int *arr; }; T g() { T t; int arr[] = {1, 2, 3}; t.arr = arr; return t; } int f() { T value = g(); for (size_t i = 0; i < 3; i++) { std::cout << value.arr[i] << " "; } std::cout << std::endl; } int main(int argc, const char **argv) { f(); return 0; } ``` And in this case, g++ allow us to overflow the array pointer memory limits with the index subscription. Why vectors doesn't share the same problem?
2022/09/13
[ "https://Stackoverflow.com/questions/73704719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19986332/" ]
All the elements in the vector essentially count as part of the vector. And notice you are returning the vector, not a pointer to the vector. But you are returning a pointer to (the start of) the array. When the function `g` returns, the vector `arr` is destroyed but that's okay because that's not the same one that is returned. A copy of `arr` is returned. (Actually, the compiler is clever enough to reuse the same vector instead of copying it and then deleting one - but you can imagine that it makes a copy) Then `f` prints values from its own local variable `value` - no problem. By contrast, in the pointer version, `f` is printing values from the local variable `arr` inside `g`, which has already been destroyed. If `g` would return a pointer to a vector, it would have the same problem.
Your intuition was somewhat right it has something to do with the containment of the array inside a struct, what you misunderstand however is the difference between (**int[]**) and (**int**\*) and probably you don't understand well where memory resides as well. To clarify: In C++ C-style array types (**int[]**), (**char[]**) etc cannot be returned from a function. Your function does not return (**int[]**) it returns **int**\* which is a pointer that points to an an (**int[]**'s zero element in the stack space of some function f() ) and hence the existence of this (**int[]**) stops past the lifetime of the function f(), but a dangling pointer was copied to the caller's site; Try ``` using int_array = int[4]; int_array f() { int_array arr { 1, 2, 3, 4}; return arr; // Does not compile cannot return array } int* f2() { int_array arr { 1, 2, 3, 4}; return arr; // Compiles because int[4] is implicitly cast to int* } ``` In the case of vector, it contains a pointer to a dynamically allocated memory block, acquired through some means(new, malloc, custom user defined allocator, etc) hence this memory block is not bound to the lifetime of a function call, but it is managed by the owner of it. When you return the vector to the caller, the memory block behind continues to exist until a (delete, free, custom-delete) is called on it. The vector does this in it's destructor ( **~vector()** ), but before that happening a **vector( const vector& )** constructor call occurs that copies the content of one vector to the other. Most compilers will optimize away this operation, as mentioned by another answer. In the case where you return the struct, the problem is the same, you are not returning an array (**int[]**) you are returning a pointer. If you were to contain an array inside the struct it would be successfully copied back to caller, because the restriction only applies for arrays and not for user defined types. Try: ``` struct Foo { int arr[4]; }; Foo f() { Foo obj{ 1, 2, 3, 4 }; // brace initialization of struct return obj; } int main() { Foo obj = f(); for(int i = 0; i < 4; i++) std::cout << i << ' '; // outputs 1 2 3 4 with no issues } ``` As you can see no issues with memory here. That's why the std::array<> from header exists - to wrap C-Style arrays so they can be copied over. I hope this explains well enough.
65,516,030
I can't make a CSS animation with my SVG sprite similar to Pinterest. The sprite is 90 frames, but I can't get it to work Pinterest Reactions Emojis ![Pinterest Reactions Emojis](https://i.stack.imgur.com/iG25Q.gif) [View Pinterest Sprite 90 frames in Svg](https://i.stack.imgur.com/ILB9G.png) My code: ```css .emoji{ width: 110px; height: 110px; background-image : url(https://s.pinimg.com/webapp/style/images/wow-0a7ea725.svg); animation: moveX 1s steps(90) infinite; } @keyframes moveX{ from{background-position-x:0px;} to{background-position-x:-500px;} } ``` ```html <div class="emoji"></div> ``` My JSFiddle: <https://jsfiddle.net/u81xkcon/>
2020/12/31
[ "https://Stackoverflow.com/questions/65516030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14893320/" ]
Here you go ```css .emoji { width: 110px; display: inline-flex; background-image: url(https://s.pinimg.com/webapp/style/images/wow-0a7ea725.svg); background-size: auto 100%; animation: moveX 1s steps(90) infinite; } .emoji::before { content: ""; padding-top: 100%; /* keep the square ratio */ } @keyframes moveX { to { background-position: right; /* you only need to move to right */ } } ``` ```html <div class="emoji"></div> <div class="emoji" style="width:50px"></div> ```
If you take Temani his great answer, add a modern W3C standard Web Component that uses *Template Literal* parsing to **create the SVG sprite *Client Side*** in a shadowDOM (*and do some better animation calculations in the* `<template>`) You save downloading a **65KB** SVG file, and get: ```html <svg-spriter w=100 h=100 s=40 width="130px"> <template> <g id="sprite${n}_${s}" transform="translate(${n*w})"> <rect x='5' y='5' width='90' height='90' rx='20' fill='#ffad65'></rect> <circle cx='30' cy='30' r='${12+(n<10?-n:n)*.1}'></circle> <circle cx='80' cy='30' r='${12+(n<10?n:-n)*.1}'></circle> <ellipse cx='60' cy='70' rx="${10+(n<20?n*0.5:((20-n)*-0.5))}" ry="5"></ellipse> </g> </template> </svg-spriter> <script> customElements.define("svg-spriter", class extends HTMLElement { constructor() { super().attachShadow({mode: "open"}) } connectedCallback() { const parsed = (template, vars = {}) => new Function('vars', [ 'let f = ( ' + Object.keys(vars).join(', ') + ' ) =>', '`' + template + '`','return f(...Object.values(vars))' ].join('\n'))(vars); setTimeout(() => { // wait till <template> is parsed by the Browser let attr = (x) => this.getAttribute(x); let [w, h, s] = ["w", "h", "s"].map(a => ~~attr(a)); let width = attr("width"); let frame = this.querySelector("template").innerHTML; let svg = (`data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${s*w} ${h}'>` + Array(s).fill().map((s, n) => parsed(frame, {n,w,h,s})).join("") + "</svg>").replace(/#/g, "%23").replace(/\n/g, "").replace(/</g, "%3C").replace(/>/g, "%3E").replaceAll('"', "'"); let html = `<style>div{width:${width};display:inline-flex;background-image: url("${svg}");background-size: auto ${width};animation:moveX 1s steps(${s-1}) infinite}div::before{content:"";padding-top:100%;}@keyframes moveX{to{background-position:right}}</style><div></div>`; html += `<br>Sprite as IMG:<br><img src="${svg}">`; this.shadowRoot.innerHTML = html; }) } }); </script> ```
13,914
I want to download the following fastq files at the same time in Salmon: ``` - SRR10611214 - SRR10611215 - SRR10611215 - SRR10611216 - SRR10611217 ``` Is there a way to do this using a bash for loop or fastq-dump? or prefetch
2020/07/17
[ "https://bioinformatics.stackexchange.com/questions/13914", "https://bioinformatics.stackexchange.com", "https://bioinformatics.stackexchange.com/users/9217/" ]
A sample code is given in the salmon documentation as follows. [Source](https://combine-lab.github.io/salmon/getting_started/) ``` #!/bin/bash mkdir data cd data for i in `seq 25 40`; do mkdir DRR0161${i}; cd DRR0161${i}; wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/DRR016/DRR0161${i}/DRR0161${i}_1.fastq.gz; wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/DRR016/DRR0161${i}/DRR0161${i}_2.fastq.gz; cd ..; done cd .. ``` This could be modified as follows. ``` #!/bin/bash mkdir data cd data for i in `seq 14 17`; do wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR106/0${i}/SRR106112${i}/SRR106112${i}_1.fastq.gz; wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR106/0${i}/SRR106112${i}/SRR106112${i}_2.fastq.gz; done cd .. ``` You can save the code as a shell script and run it from the linux terminal. For example `bash download_fastq.sh`
You can use `parallel`. ``` parallel -j 3 fastq-dump {} ::: SRR10611214 SRR10611215 SRR10611215 SRR10611216 SRR10611217 ``` The option `-j` says how many jobs should maximal run parallel. So in this case maximal 3 identifier would be handled at the same time. How many jobs you can run parallel depends on your machine. You can also take a look at [parallel-fastq-dump](https://github.com/rvalieris/parallel-fastq-dump).
13,914
I want to download the following fastq files at the same time in Salmon: ``` - SRR10611214 - SRR10611215 - SRR10611215 - SRR10611216 - SRR10611217 ``` Is there a way to do this using a bash for loop or fastq-dump? or prefetch
2020/07/17
[ "https://bioinformatics.stackexchange.com/questions/13914", "https://bioinformatics.stackexchange.com", "https://bioinformatics.stackexchange.com/users/9217/" ]
A sample code is given in the salmon documentation as follows. [Source](https://combine-lab.github.io/salmon/getting_started/) ``` #!/bin/bash mkdir data cd data for i in `seq 25 40`; do mkdir DRR0161${i}; cd DRR0161${i}; wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/DRR016/DRR0161${i}/DRR0161${i}_1.fastq.gz; wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/DRR016/DRR0161${i}/DRR0161${i}_2.fastq.gz; cd ..; done cd .. ``` This could be modified as follows. ``` #!/bin/bash mkdir data cd data for i in `seq 14 17`; do wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR106/0${i}/SRR106112${i}/SRR106112${i}_1.fastq.gz; wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR106/0${i}/SRR106112${i}/SRR106112${i}_2.fastq.gz; done cd .. ``` You can save the code as a shell script and run it from the linux terminal. For example `bash download_fastq.sh`
Make a list.txt file containing a single column of SRA numbers to download. then: `for i in $(cat list.txt); do echo $i; date; fasterq-dump -S $i; done` It works well to use NCBI's web interface to find SRA samples of interest, download and open findings in Excel, then copy single column containing SRA numbers and paste into list.txt using document editor such as vim. After downloading including the "R" can be nice: `for i in *_1.fastq; do mv $i ${i%_1.fastq}_R1.fastq; done` `for i in *_2.fastq; do mv $i ${i%_2.fastq}_R1.fastq; done` and zip: `pigz *fastq` If needed a conda option for downloading fasterq-dump: `conda install -c bioconda sra-tools`
13,914
I want to download the following fastq files at the same time in Salmon: ``` - SRR10611214 - SRR10611215 - SRR10611215 - SRR10611216 - SRR10611217 ``` Is there a way to do this using a bash for loop or fastq-dump? or prefetch
2020/07/17
[ "https://bioinformatics.stackexchange.com/questions/13914", "https://bioinformatics.stackexchange.com", "https://bioinformatics.stackexchange.com/users/9217/" ]
Make a list.txt file containing a single column of SRA numbers to download. then: `for i in $(cat list.txt); do echo $i; date; fasterq-dump -S $i; done` It works well to use NCBI's web interface to find SRA samples of interest, download and open findings in Excel, then copy single column containing SRA numbers and paste into list.txt using document editor such as vim. After downloading including the "R" can be nice: `for i in *_1.fastq; do mv $i ${i%_1.fastq}_R1.fastq; done` `for i in *_2.fastq; do mv $i ${i%_2.fastq}_R1.fastq; done` and zip: `pigz *fastq` If needed a conda option for downloading fasterq-dump: `conda install -c bioconda sra-tools`
You can use `parallel`. ``` parallel -j 3 fastq-dump {} ::: SRR10611214 SRR10611215 SRR10611215 SRR10611216 SRR10611217 ``` The option `-j` says how many jobs should maximal run parallel. So in this case maximal 3 identifier would be handled at the same time. How many jobs you can run parallel depends on your machine. You can also take a look at [parallel-fastq-dump](https://github.com/rvalieris/parallel-fastq-dump).
339,552
TL;DR I'm pretty sure our small network has been infected by some sort of worm/virus. It seems to only be afflicting our Windows XP machines, however. Windows 7 machines and Linux (well, yea) computers seem to be unaffected. Anti-virus scans are showing nothing, but our domain server has logged thousands of failed login attempts on various valid and invalid user accounts, particularly the administrator. How can I stop this unidentified worm from spreading? --- **Symptoms** A few of our Windows XP users have reported similar problems, although not entirely identical. They all experience random shutdowns/restarts that are software initiated. On one of the computers a dialog pops up with a countdown until system restart, apparently started by NT-AUTHORITY\SYSTEM and has to do with an RPC call. This dialog in particular is exactly the same as those described in articles detailing older RPC exploit worms. When two of the computers rebooted, they came back up at the login prompt (they are domain computers) but the user name listed was 'admin', even though they hadn't logged in as admin. On our Windows Server 2003 machine running the domain, I noticed several thousand login attempts from various sources. They tried all different login names including Administrator, admin, user, server, owner and others. Some of the logs listed IPs, some didn't. Of the ones that did have source IP address (for the failed logins) two of them correspond to the two Windows XP machines experiencing reboots. Just yesterday I noticed a bunch of failed login attempts from an outside IP address. A traceroute showed that outside IP address to be from a Canadian ISP. We shouldn't have an connections from there, ever (we do have VPN users though). So I am still not sure whats going on with the login attempts coming from a foriegn IP. It seems obvious that some sort of malware is on these computers, and part of what it does is try to enumerate passwords on domain accounts to gain access. **What I've Done So Far** After realizing what was happening, my first step was to make sure everyone was running up-to-date anti-virus and did a scan. Of the computers affected, one of them ha an expired anti-virus client, but the other two were current versions of Norton and full scans of both systems turned up nothing. The server itself regularly runs up-to-date anti-virus, and has not shown any infections. So 3/4 of the Windows NT based computers have up-to-date anti virus, but it hasn't detected anything. However I am convinced that something is going on, mainly evidenced by the thousands of failed login attempts for various accounts. I also noticed that the root of our main file share had pretty open permissions, so I just restricted it to read+execute for normal users. The administrator has full access of course. I am also about to have the users update their passwords (to strong ones), and I am going to rename to Administrator on the server and change its password. I already took of the machines off of the network, one is being replaced by a new one, but I know these things can spread through networks so I still need to get to the bottom of this. Also, the server has a NAT/Firewall setup with only certain ports open. I have yet to full investigate some of the Windows related services with ports open, as I am from a Linux background. **Now what?** So all the modern and up-to-date anti-virus hasn't detected anything, but I am absolutely convinced these computers have some sort of virus. I base this on the random restarts/instability of the XP machines combined with the thousands of login attempts originating from these machines. What I plan on doing is backing up user files on the affected machines, and then reinstalling windows and freshly formatting the drives. I also am taking a few measures to secure the common file shares that may have been used to spread to other machines. Knowing all this, what can I do to ensure that this worm isn't somewhere else on the network, and how can I stop it from spreading? I know this is a drawn out question, but I am out of my depths here and could use some pointers. Thanks for looking!
2011/12/09
[ "https://serverfault.com/questions/339552", "https://serverfault.com", "https://serverfault.com/users/71559/" ]
These are my general suggestions for this kind of process. I appreciate you'll have covered some of them already but its better to be told something twice than miss something important. These notes are orientated towards malware that's spreading on a LAN but could easily be scaled back to deal with more minor infections. Stopping the rot, and finding the infection source. --------------------------------------------------- 1. **Make sure you have an up to date backup of every system and every bit of data on this network that the business cares about.** Make sure you note that this restore media may be compromised, so that people don't try and restore from it in 3 months time while your back is turned and infect the network again. If you have a backup from before the infection happened, put this safely to one side too. 2. **Shut down the live network, if you possibly can** (you will probably need to do this as part of the cleanup process, at least). At the very least, seriously consider keeping this network, including servers, off the internet until you know what is going on - what if this worm is stealing info? 3. **Don't get ahead of yourself.** It's tempting to just say clean build everything at this point, force everyone to change passwords, etc, and call that 'good enough'. *While you will probably need to do this sooner or later*, it's likely to leave you with pockets of infection if you don't understand what is happening on your LAN. (*If you don't want to investigate the infection further go to step 6*) 4. Copy an infected machine to a virtual environment of some kind, **isolate this virtual environment from everything else including the host machine before you boot the compromised guest**. 5. Create another couple of clean virtual guest machines for it to infect then isolate that network and use tools like [wireshark](http://www.wireshark.org/) to monitor the network traffic (time to take advantage of that linux background and create *another* guest on this virtual LAN that can watch all this traffic without being infected by any Windows worm!) and [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645) to monitor changes happening on all these machines. Also consider that the issue may be a well hidden [rootkit](http://en.wikipedia.org/wiki/Rootkit) - try using a reputable tool for finding these but remember that this is a bit of an uphill struggle so finding nothing doesn't mean there is nothing there. 6. (Assuming you haven't / can't shut down the main LAN) Use wireshark on the main LAN to look at traffic being sent to/from the infected machines. Treat any unexplainable traffic from any machine as potentially suspicious - *absence of visible symptoms is not evidence of an absence of any compromise*. You should be especially worried about servers and any workstations running business critical information. 7. Once you have isolated any infected processes on the virtual guests, you should be able to **send a sample to the company that made the antivirus software you're using** on these machines. They will be keen to examine samples and produce fixes for any new malware they see. In fact, if you have not done so already, you should contact them with your tale of woe as they might have some way of helping. 8. **Try very hard to work out what the original infection vector was** - this worm may be an exploit that was hidden inside a compromised website that someone visited, it may have been brought in from someone's home on a memory stick or received by email, to name but a few ways. Did the exploit compromise these machines via a user with admin rights? If so, don't give users admin rights in future. You need to try and make sure the infection source is fixed and you need to see if there is any procedural change you can make to make that infection route more difficult for exploits in the future. Clean-up -------- Some of these steps will seem over the top. Heck some of them probably *are* over the top, especially if you determine that only a few machines are actually compromised, but they should guarantee your network is as clean as it can be. Bosses won't be keen on some of these steps either, but there's not much to be done about that. 1. **Shutdown all machines on the network.** All workstations. All servers. Everything. Yes, even the bosses' teenage son's laptop which the son uses to sneak onto the network while waiting for dad to finish work so the son can play '*dubious-javascript-exploit-Ville*' on whatever the current social media site du-jour is. In fact, thinking about it, shut this machine down *especially*. With a brick if that's what it takes. 2. **Start up each server in turn.** Apply any fix you've discovered for yourself or have been given by an AV company. Audit the users and groups for any unexplained accounts (both local accounts and AD accounts), audit installed software for anything unexpected and use wireshark on another system to watch traffic coming from this server (If you find *any* issues at this point then seriously consider rebuilding that server). *Shut each system down before you start the next one, so that a compromised machine can't attack the others. Or unplug them from the network, so you can do several at once but they can't talk to each other, its all good.* 3. Once you're as sure as you can be that all your servers are clean, start them up and using wireshark, process monitor, etc. again observe them again for any strange behaviour. 4. **Reset every single user password**. And if possible, service account passwords, too. Yeah I know its a pain. We're about to head into "possibly over the top" territory at this point. Your call. 5. **Rebuild all the workstations**. Do so one at a time, so that possibly infected machines aren't sitting there idle on the LAN attacking freshly rebuilt ones. Yes this will take a while, sorry about that. 6. If that's not possible then: Carry out the steps I outlined above for servers on all the "hopefully clean" workstations. Rebuild all the ones that showed any hint of suspicious activity, and do so while all the "hopefully clean" machines are powered off. 7. If you haven't already then consider centralised AV that will report problems back to a server where you can watch for problems, centralised event logging, network monitoring, etc. Obviously pick and choose which of these are right for this network's needs and budgets, but there's clearly a problem here, right? 8. Review user rights and software installs on these machines, and set up a periodic audit to make sure things are still how you expect them to be. Also make sure that users are encouraged to report things asap without being moaned at, encourage a business culture of fixing IT problems rather than shooting the messenger, etc.
You've done all the things I would do (if I were still a Windows admin) -- The canonical steps are (or were, last time I was a Windows guy): 1. Isolate the affected machines. 2. Update anti-virus definitions Run AV/Malware/etc. scans on the whole network 3. Blow away the affected machines (completely wipe the suckers out) and reinstall. 4. Restore user data from backups (making sure it's clean). Note that there's always a chance the virus/worm/whatever is lurking in email (on your mail server), or inside a macro in a word/excel document -- If the problem comes back you may need to be more aggressive in your cleaning the next time around.
339,552
TL;DR I'm pretty sure our small network has been infected by some sort of worm/virus. It seems to only be afflicting our Windows XP machines, however. Windows 7 machines and Linux (well, yea) computers seem to be unaffected. Anti-virus scans are showing nothing, but our domain server has logged thousands of failed login attempts on various valid and invalid user accounts, particularly the administrator. How can I stop this unidentified worm from spreading? --- **Symptoms** A few of our Windows XP users have reported similar problems, although not entirely identical. They all experience random shutdowns/restarts that are software initiated. On one of the computers a dialog pops up with a countdown until system restart, apparently started by NT-AUTHORITY\SYSTEM and has to do with an RPC call. This dialog in particular is exactly the same as those described in articles detailing older RPC exploit worms. When two of the computers rebooted, they came back up at the login prompt (they are domain computers) but the user name listed was 'admin', even though they hadn't logged in as admin. On our Windows Server 2003 machine running the domain, I noticed several thousand login attempts from various sources. They tried all different login names including Administrator, admin, user, server, owner and others. Some of the logs listed IPs, some didn't. Of the ones that did have source IP address (for the failed logins) two of them correspond to the two Windows XP machines experiencing reboots. Just yesterday I noticed a bunch of failed login attempts from an outside IP address. A traceroute showed that outside IP address to be from a Canadian ISP. We shouldn't have an connections from there, ever (we do have VPN users though). So I am still not sure whats going on with the login attempts coming from a foriegn IP. It seems obvious that some sort of malware is on these computers, and part of what it does is try to enumerate passwords on domain accounts to gain access. **What I've Done So Far** After realizing what was happening, my first step was to make sure everyone was running up-to-date anti-virus and did a scan. Of the computers affected, one of them ha an expired anti-virus client, but the other two were current versions of Norton and full scans of both systems turned up nothing. The server itself regularly runs up-to-date anti-virus, and has not shown any infections. So 3/4 of the Windows NT based computers have up-to-date anti virus, but it hasn't detected anything. However I am convinced that something is going on, mainly evidenced by the thousands of failed login attempts for various accounts. I also noticed that the root of our main file share had pretty open permissions, so I just restricted it to read+execute for normal users. The administrator has full access of course. I am also about to have the users update their passwords (to strong ones), and I am going to rename to Administrator on the server and change its password. I already took of the machines off of the network, one is being replaced by a new one, but I know these things can spread through networks so I still need to get to the bottom of this. Also, the server has a NAT/Firewall setup with only certain ports open. I have yet to full investigate some of the Windows related services with ports open, as I am from a Linux background. **Now what?** So all the modern and up-to-date anti-virus hasn't detected anything, but I am absolutely convinced these computers have some sort of virus. I base this on the random restarts/instability of the XP machines combined with the thousands of login attempts originating from these machines. What I plan on doing is backing up user files on the affected machines, and then reinstalling windows and freshly formatting the drives. I also am taking a few measures to secure the common file shares that may have been used to spread to other machines. Knowing all this, what can I do to ensure that this worm isn't somewhere else on the network, and how can I stop it from spreading? I know this is a drawn out question, but I am out of my depths here and could use some pointers. Thanks for looking!
2011/12/09
[ "https://serverfault.com/questions/339552", "https://serverfault.com", "https://serverfault.com/users/71559/" ]
You've done all the things I would do (if I were still a Windows admin) -- The canonical steps are (or were, last time I was a Windows guy): 1. Isolate the affected machines. 2. Update anti-virus definitions Run AV/Malware/etc. scans on the whole network 3. Blow away the affected machines (completely wipe the suckers out) and reinstall. 4. Restore user data from backups (making sure it's clean). Note that there's always a chance the virus/worm/whatever is lurking in email (on your mail server), or inside a macro in a word/excel document -- If the problem comes back you may need to be more aggressive in your cleaning the next time around.
The first lesson to take from this is that AV solutions aren't perfect. Not even close. If you are up to date with the AV software vendors, call them. All of them have support numbers for exactly this sort of thing. As a matter of fact they'll probably be very interested in what hit you. As others have said, take each machine down, wipe it and reinstall. You might take this opportunity to get everyone off of XP anyway. It's been a dead OS for quite some time. At the very least this should involve destroying the HD partitions and reformatting them. Although, it sounds like there aren't that many machines involved, so buying completely new replacements might be a better option. Also, let your boss(es) know that this just got expensive. Finally, why in the world would you run all of that off of a single server? (Rhetorical, I know you "inherited" it) A DC should NEVER be accessible from the internet. Fix this by getting the appropriate hardware in place to take care of the functionality you need.
339,552
TL;DR I'm pretty sure our small network has been infected by some sort of worm/virus. It seems to only be afflicting our Windows XP machines, however. Windows 7 machines and Linux (well, yea) computers seem to be unaffected. Anti-virus scans are showing nothing, but our domain server has logged thousands of failed login attempts on various valid and invalid user accounts, particularly the administrator. How can I stop this unidentified worm from spreading? --- **Symptoms** A few of our Windows XP users have reported similar problems, although not entirely identical. They all experience random shutdowns/restarts that are software initiated. On one of the computers a dialog pops up with a countdown until system restart, apparently started by NT-AUTHORITY\SYSTEM and has to do with an RPC call. This dialog in particular is exactly the same as those described in articles detailing older RPC exploit worms. When two of the computers rebooted, they came back up at the login prompt (they are domain computers) but the user name listed was 'admin', even though they hadn't logged in as admin. On our Windows Server 2003 machine running the domain, I noticed several thousand login attempts from various sources. They tried all different login names including Administrator, admin, user, server, owner and others. Some of the logs listed IPs, some didn't. Of the ones that did have source IP address (for the failed logins) two of them correspond to the two Windows XP machines experiencing reboots. Just yesterday I noticed a bunch of failed login attempts from an outside IP address. A traceroute showed that outside IP address to be from a Canadian ISP. We shouldn't have an connections from there, ever (we do have VPN users though). So I am still not sure whats going on with the login attempts coming from a foriegn IP. It seems obvious that some sort of malware is on these computers, and part of what it does is try to enumerate passwords on domain accounts to gain access. **What I've Done So Far** After realizing what was happening, my first step was to make sure everyone was running up-to-date anti-virus and did a scan. Of the computers affected, one of them ha an expired anti-virus client, but the other two were current versions of Norton and full scans of both systems turned up nothing. The server itself regularly runs up-to-date anti-virus, and has not shown any infections. So 3/4 of the Windows NT based computers have up-to-date anti virus, but it hasn't detected anything. However I am convinced that something is going on, mainly evidenced by the thousands of failed login attempts for various accounts. I also noticed that the root of our main file share had pretty open permissions, so I just restricted it to read+execute for normal users. The administrator has full access of course. I am also about to have the users update their passwords (to strong ones), and I am going to rename to Administrator on the server and change its password. I already took of the machines off of the network, one is being replaced by a new one, but I know these things can spread through networks so I still need to get to the bottom of this. Also, the server has a NAT/Firewall setup with only certain ports open. I have yet to full investigate some of the Windows related services with ports open, as I am from a Linux background. **Now what?** So all the modern and up-to-date anti-virus hasn't detected anything, but I am absolutely convinced these computers have some sort of virus. I base this on the random restarts/instability of the XP machines combined with the thousands of login attempts originating from these machines. What I plan on doing is backing up user files on the affected machines, and then reinstalling windows and freshly formatting the drives. I also am taking a few measures to secure the common file shares that may have been used to spread to other machines. Knowing all this, what can I do to ensure that this worm isn't somewhere else on the network, and how can I stop it from spreading? I know this is a drawn out question, but I am out of my depths here and could use some pointers. Thanks for looking!
2011/12/09
[ "https://serverfault.com/questions/339552", "https://serverfault.com", "https://serverfault.com/users/71559/" ]
You've done all the things I would do (if I were still a Windows admin) -- The canonical steps are (or were, last time I was a Windows guy): 1. Isolate the affected machines. 2. Update anti-virus definitions Run AV/Malware/etc. scans on the whole network 3. Blow away the affected machines (completely wipe the suckers out) and reinstall. 4. Restore user data from backups (making sure it's clean). Note that there's always a chance the virus/worm/whatever is lurking in email (on your mail server), or inside a macro in a word/excel document -- If the problem comes back you may need to be more aggressive in your cleaning the next time around.
It's most likely a rootkit if your A/V programs turn up nothing. Try running [TDSSkiller](http://support.kaspersky.com/faq/?qid=208280684) and see what you find. Also, this would be a perfect time to simply replace the archaic Windows XP computers with something less than over a decade old. Aside from software like anti-virus programs, I've seen very very little in the way of programs that couldn't be made to run via a shim or loosening a few NTFS/Registry permissions on Windows 7. There's really little excuse for continuing to run XP.
339,552
TL;DR I'm pretty sure our small network has been infected by some sort of worm/virus. It seems to only be afflicting our Windows XP machines, however. Windows 7 machines and Linux (well, yea) computers seem to be unaffected. Anti-virus scans are showing nothing, but our domain server has logged thousands of failed login attempts on various valid and invalid user accounts, particularly the administrator. How can I stop this unidentified worm from spreading? --- **Symptoms** A few of our Windows XP users have reported similar problems, although not entirely identical. They all experience random shutdowns/restarts that are software initiated. On one of the computers a dialog pops up with a countdown until system restart, apparently started by NT-AUTHORITY\SYSTEM and has to do with an RPC call. This dialog in particular is exactly the same as those described in articles detailing older RPC exploit worms. When two of the computers rebooted, they came back up at the login prompt (they are domain computers) but the user name listed was 'admin', even though they hadn't logged in as admin. On our Windows Server 2003 machine running the domain, I noticed several thousand login attempts from various sources. They tried all different login names including Administrator, admin, user, server, owner and others. Some of the logs listed IPs, some didn't. Of the ones that did have source IP address (for the failed logins) two of them correspond to the two Windows XP machines experiencing reboots. Just yesterday I noticed a bunch of failed login attempts from an outside IP address. A traceroute showed that outside IP address to be from a Canadian ISP. We shouldn't have an connections from there, ever (we do have VPN users though). So I am still not sure whats going on with the login attempts coming from a foriegn IP. It seems obvious that some sort of malware is on these computers, and part of what it does is try to enumerate passwords on domain accounts to gain access. **What I've Done So Far** After realizing what was happening, my first step was to make sure everyone was running up-to-date anti-virus and did a scan. Of the computers affected, one of them ha an expired anti-virus client, but the other two were current versions of Norton and full scans of both systems turned up nothing. The server itself regularly runs up-to-date anti-virus, and has not shown any infections. So 3/4 of the Windows NT based computers have up-to-date anti virus, but it hasn't detected anything. However I am convinced that something is going on, mainly evidenced by the thousands of failed login attempts for various accounts. I also noticed that the root of our main file share had pretty open permissions, so I just restricted it to read+execute for normal users. The administrator has full access of course. I am also about to have the users update their passwords (to strong ones), and I am going to rename to Administrator on the server and change its password. I already took of the machines off of the network, one is being replaced by a new one, but I know these things can spread through networks so I still need to get to the bottom of this. Also, the server has a NAT/Firewall setup with only certain ports open. I have yet to full investigate some of the Windows related services with ports open, as I am from a Linux background. **Now what?** So all the modern and up-to-date anti-virus hasn't detected anything, but I am absolutely convinced these computers have some sort of virus. I base this on the random restarts/instability of the XP machines combined with the thousands of login attempts originating from these machines. What I plan on doing is backing up user files on the affected machines, and then reinstalling windows and freshly formatting the drives. I also am taking a few measures to secure the common file shares that may have been used to spread to other machines. Knowing all this, what can I do to ensure that this worm isn't somewhere else on the network, and how can I stop it from spreading? I know this is a drawn out question, but I am out of my depths here and could use some pointers. Thanks for looking!
2011/12/09
[ "https://serverfault.com/questions/339552", "https://serverfault.com", "https://serverfault.com/users/71559/" ]
These are my general suggestions for this kind of process. I appreciate you'll have covered some of them already but its better to be told something twice than miss something important. These notes are orientated towards malware that's spreading on a LAN but could easily be scaled back to deal with more minor infections. Stopping the rot, and finding the infection source. --------------------------------------------------- 1. **Make sure you have an up to date backup of every system and every bit of data on this network that the business cares about.** Make sure you note that this restore media may be compromised, so that people don't try and restore from it in 3 months time while your back is turned and infect the network again. If you have a backup from before the infection happened, put this safely to one side too. 2. **Shut down the live network, if you possibly can** (you will probably need to do this as part of the cleanup process, at least). At the very least, seriously consider keeping this network, including servers, off the internet until you know what is going on - what if this worm is stealing info? 3. **Don't get ahead of yourself.** It's tempting to just say clean build everything at this point, force everyone to change passwords, etc, and call that 'good enough'. *While you will probably need to do this sooner or later*, it's likely to leave you with pockets of infection if you don't understand what is happening on your LAN. (*If you don't want to investigate the infection further go to step 6*) 4. Copy an infected machine to a virtual environment of some kind, **isolate this virtual environment from everything else including the host machine before you boot the compromised guest**. 5. Create another couple of clean virtual guest machines for it to infect then isolate that network and use tools like [wireshark](http://www.wireshark.org/) to monitor the network traffic (time to take advantage of that linux background and create *another* guest on this virtual LAN that can watch all this traffic without being infected by any Windows worm!) and [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645) to monitor changes happening on all these machines. Also consider that the issue may be a well hidden [rootkit](http://en.wikipedia.org/wiki/Rootkit) - try using a reputable tool for finding these but remember that this is a bit of an uphill struggle so finding nothing doesn't mean there is nothing there. 6. (Assuming you haven't / can't shut down the main LAN) Use wireshark on the main LAN to look at traffic being sent to/from the infected machines. Treat any unexplainable traffic from any machine as potentially suspicious - *absence of visible symptoms is not evidence of an absence of any compromise*. You should be especially worried about servers and any workstations running business critical information. 7. Once you have isolated any infected processes on the virtual guests, you should be able to **send a sample to the company that made the antivirus software you're using** on these machines. They will be keen to examine samples and produce fixes for any new malware they see. In fact, if you have not done so already, you should contact them with your tale of woe as they might have some way of helping. 8. **Try very hard to work out what the original infection vector was** - this worm may be an exploit that was hidden inside a compromised website that someone visited, it may have been brought in from someone's home on a memory stick or received by email, to name but a few ways. Did the exploit compromise these machines via a user with admin rights? If so, don't give users admin rights in future. You need to try and make sure the infection source is fixed and you need to see if there is any procedural change you can make to make that infection route more difficult for exploits in the future. Clean-up -------- Some of these steps will seem over the top. Heck some of them probably *are* over the top, especially if you determine that only a few machines are actually compromised, but they should guarantee your network is as clean as it can be. Bosses won't be keen on some of these steps either, but there's not much to be done about that. 1. **Shutdown all machines on the network.** All workstations. All servers. Everything. Yes, even the bosses' teenage son's laptop which the son uses to sneak onto the network while waiting for dad to finish work so the son can play '*dubious-javascript-exploit-Ville*' on whatever the current social media site du-jour is. In fact, thinking about it, shut this machine down *especially*. With a brick if that's what it takes. 2. **Start up each server in turn.** Apply any fix you've discovered for yourself or have been given by an AV company. Audit the users and groups for any unexplained accounts (both local accounts and AD accounts), audit installed software for anything unexpected and use wireshark on another system to watch traffic coming from this server (If you find *any* issues at this point then seriously consider rebuilding that server). *Shut each system down before you start the next one, so that a compromised machine can't attack the others. Or unplug them from the network, so you can do several at once but they can't talk to each other, its all good.* 3. Once you're as sure as you can be that all your servers are clean, start them up and using wireshark, process monitor, etc. again observe them again for any strange behaviour. 4. **Reset every single user password**. And if possible, service account passwords, too. Yeah I know its a pain. We're about to head into "possibly over the top" territory at this point. Your call. 5. **Rebuild all the workstations**. Do so one at a time, so that possibly infected machines aren't sitting there idle on the LAN attacking freshly rebuilt ones. Yes this will take a while, sorry about that. 6. If that's not possible then: Carry out the steps I outlined above for servers on all the "hopefully clean" workstations. Rebuild all the ones that showed any hint of suspicious activity, and do so while all the "hopefully clean" machines are powered off. 7. If you haven't already then consider centralised AV that will report problems back to a server where you can watch for problems, centralised event logging, network monitoring, etc. Obviously pick and choose which of these are right for this network's needs and budgets, but there's clearly a problem here, right? 8. Review user rights and software installs on these machines, and set up a periodic audit to make sure things are still how you expect them to be. Also make sure that users are encouraged to report things asap without being moaned at, encourage a business culture of fixing IT problems rather than shooting the messenger, etc.
The first lesson to take from this is that AV solutions aren't perfect. Not even close. If you are up to date with the AV software vendors, call them. All of them have support numbers for exactly this sort of thing. As a matter of fact they'll probably be very interested in what hit you. As others have said, take each machine down, wipe it and reinstall. You might take this opportunity to get everyone off of XP anyway. It's been a dead OS for quite some time. At the very least this should involve destroying the HD partitions and reformatting them. Although, it sounds like there aren't that many machines involved, so buying completely new replacements might be a better option. Also, let your boss(es) know that this just got expensive. Finally, why in the world would you run all of that off of a single server? (Rhetorical, I know you "inherited" it) A DC should NEVER be accessible from the internet. Fix this by getting the appropriate hardware in place to take care of the functionality you need.
339,552
TL;DR I'm pretty sure our small network has been infected by some sort of worm/virus. It seems to only be afflicting our Windows XP machines, however. Windows 7 machines and Linux (well, yea) computers seem to be unaffected. Anti-virus scans are showing nothing, but our domain server has logged thousands of failed login attempts on various valid and invalid user accounts, particularly the administrator. How can I stop this unidentified worm from spreading? --- **Symptoms** A few of our Windows XP users have reported similar problems, although not entirely identical. They all experience random shutdowns/restarts that are software initiated. On one of the computers a dialog pops up with a countdown until system restart, apparently started by NT-AUTHORITY\SYSTEM and has to do with an RPC call. This dialog in particular is exactly the same as those described in articles detailing older RPC exploit worms. When two of the computers rebooted, they came back up at the login prompt (they are domain computers) but the user name listed was 'admin', even though they hadn't logged in as admin. On our Windows Server 2003 machine running the domain, I noticed several thousand login attempts from various sources. They tried all different login names including Administrator, admin, user, server, owner and others. Some of the logs listed IPs, some didn't. Of the ones that did have source IP address (for the failed logins) two of them correspond to the two Windows XP machines experiencing reboots. Just yesterday I noticed a bunch of failed login attempts from an outside IP address. A traceroute showed that outside IP address to be from a Canadian ISP. We shouldn't have an connections from there, ever (we do have VPN users though). So I am still not sure whats going on with the login attempts coming from a foriegn IP. It seems obvious that some sort of malware is on these computers, and part of what it does is try to enumerate passwords on domain accounts to gain access. **What I've Done So Far** After realizing what was happening, my first step was to make sure everyone was running up-to-date anti-virus and did a scan. Of the computers affected, one of them ha an expired anti-virus client, but the other two were current versions of Norton and full scans of both systems turned up nothing. The server itself regularly runs up-to-date anti-virus, and has not shown any infections. So 3/4 of the Windows NT based computers have up-to-date anti virus, but it hasn't detected anything. However I am convinced that something is going on, mainly evidenced by the thousands of failed login attempts for various accounts. I also noticed that the root of our main file share had pretty open permissions, so I just restricted it to read+execute for normal users. The administrator has full access of course. I am also about to have the users update their passwords (to strong ones), and I am going to rename to Administrator on the server and change its password. I already took of the machines off of the network, one is being replaced by a new one, but I know these things can spread through networks so I still need to get to the bottom of this. Also, the server has a NAT/Firewall setup with only certain ports open. I have yet to full investigate some of the Windows related services with ports open, as I am from a Linux background. **Now what?** So all the modern and up-to-date anti-virus hasn't detected anything, but I am absolutely convinced these computers have some sort of virus. I base this on the random restarts/instability of the XP machines combined with the thousands of login attempts originating from these machines. What I plan on doing is backing up user files on the affected machines, and then reinstalling windows and freshly formatting the drives. I also am taking a few measures to secure the common file shares that may have been used to spread to other machines. Knowing all this, what can I do to ensure that this worm isn't somewhere else on the network, and how can I stop it from spreading? I know this is a drawn out question, but I am out of my depths here and could use some pointers. Thanks for looking!
2011/12/09
[ "https://serverfault.com/questions/339552", "https://serverfault.com", "https://serverfault.com/users/71559/" ]
These are my general suggestions for this kind of process. I appreciate you'll have covered some of them already but its better to be told something twice than miss something important. These notes are orientated towards malware that's spreading on a LAN but could easily be scaled back to deal with more minor infections. Stopping the rot, and finding the infection source. --------------------------------------------------- 1. **Make sure you have an up to date backup of every system and every bit of data on this network that the business cares about.** Make sure you note that this restore media may be compromised, so that people don't try and restore from it in 3 months time while your back is turned and infect the network again. If you have a backup from before the infection happened, put this safely to one side too. 2. **Shut down the live network, if you possibly can** (you will probably need to do this as part of the cleanup process, at least). At the very least, seriously consider keeping this network, including servers, off the internet until you know what is going on - what if this worm is stealing info? 3. **Don't get ahead of yourself.** It's tempting to just say clean build everything at this point, force everyone to change passwords, etc, and call that 'good enough'. *While you will probably need to do this sooner or later*, it's likely to leave you with pockets of infection if you don't understand what is happening on your LAN. (*If you don't want to investigate the infection further go to step 6*) 4. Copy an infected machine to a virtual environment of some kind, **isolate this virtual environment from everything else including the host machine before you boot the compromised guest**. 5. Create another couple of clean virtual guest machines for it to infect then isolate that network and use tools like [wireshark](http://www.wireshark.org/) to monitor the network traffic (time to take advantage of that linux background and create *another* guest on this virtual LAN that can watch all this traffic without being infected by any Windows worm!) and [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645) to monitor changes happening on all these machines. Also consider that the issue may be a well hidden [rootkit](http://en.wikipedia.org/wiki/Rootkit) - try using a reputable tool for finding these but remember that this is a bit of an uphill struggle so finding nothing doesn't mean there is nothing there. 6. (Assuming you haven't / can't shut down the main LAN) Use wireshark on the main LAN to look at traffic being sent to/from the infected machines. Treat any unexplainable traffic from any machine as potentially suspicious - *absence of visible symptoms is not evidence of an absence of any compromise*. You should be especially worried about servers and any workstations running business critical information. 7. Once you have isolated any infected processes on the virtual guests, you should be able to **send a sample to the company that made the antivirus software you're using** on these machines. They will be keen to examine samples and produce fixes for any new malware they see. In fact, if you have not done so already, you should contact them with your tale of woe as they might have some way of helping. 8. **Try very hard to work out what the original infection vector was** - this worm may be an exploit that was hidden inside a compromised website that someone visited, it may have been brought in from someone's home on a memory stick or received by email, to name but a few ways. Did the exploit compromise these machines via a user with admin rights? If so, don't give users admin rights in future. You need to try and make sure the infection source is fixed and you need to see if there is any procedural change you can make to make that infection route more difficult for exploits in the future. Clean-up -------- Some of these steps will seem over the top. Heck some of them probably *are* over the top, especially if you determine that only a few machines are actually compromised, but they should guarantee your network is as clean as it can be. Bosses won't be keen on some of these steps either, but there's not much to be done about that. 1. **Shutdown all machines on the network.** All workstations. All servers. Everything. Yes, even the bosses' teenage son's laptop which the son uses to sneak onto the network while waiting for dad to finish work so the son can play '*dubious-javascript-exploit-Ville*' on whatever the current social media site du-jour is. In fact, thinking about it, shut this machine down *especially*. With a brick if that's what it takes. 2. **Start up each server in turn.** Apply any fix you've discovered for yourself or have been given by an AV company. Audit the users and groups for any unexplained accounts (both local accounts and AD accounts), audit installed software for anything unexpected and use wireshark on another system to watch traffic coming from this server (If you find *any* issues at this point then seriously consider rebuilding that server). *Shut each system down before you start the next one, so that a compromised machine can't attack the others. Or unplug them from the network, so you can do several at once but they can't talk to each other, its all good.* 3. Once you're as sure as you can be that all your servers are clean, start them up and using wireshark, process monitor, etc. again observe them again for any strange behaviour. 4. **Reset every single user password**. And if possible, service account passwords, too. Yeah I know its a pain. We're about to head into "possibly over the top" territory at this point. Your call. 5. **Rebuild all the workstations**. Do so one at a time, so that possibly infected machines aren't sitting there idle on the LAN attacking freshly rebuilt ones. Yes this will take a while, sorry about that. 6. If that's not possible then: Carry out the steps I outlined above for servers on all the "hopefully clean" workstations. Rebuild all the ones that showed any hint of suspicious activity, and do so while all the "hopefully clean" machines are powered off. 7. If you haven't already then consider centralised AV that will report problems back to a server where you can watch for problems, centralised event logging, network monitoring, etc. Obviously pick and choose which of these are right for this network's needs and budgets, but there's clearly a problem here, right? 8. Review user rights and software installs on these machines, and set up a periodic audit to make sure things are still how you expect them to be. Also make sure that users are encouraged to report things asap without being moaned at, encourage a business culture of fixing IT problems rather than shooting the messenger, etc.
It's most likely a rootkit if your A/V programs turn up nothing. Try running [TDSSkiller](http://support.kaspersky.com/faq/?qid=208280684) and see what you find. Also, this would be a perfect time to simply replace the archaic Windows XP computers with something less than over a decade old. Aside from software like anti-virus programs, I've seen very very little in the way of programs that couldn't be made to run via a shim or loosening a few NTFS/Registry permissions on Windows 7. There's really little excuse for continuing to run XP.
339,552
TL;DR I'm pretty sure our small network has been infected by some sort of worm/virus. It seems to only be afflicting our Windows XP machines, however. Windows 7 machines and Linux (well, yea) computers seem to be unaffected. Anti-virus scans are showing nothing, but our domain server has logged thousands of failed login attempts on various valid and invalid user accounts, particularly the administrator. How can I stop this unidentified worm from spreading? --- **Symptoms** A few of our Windows XP users have reported similar problems, although not entirely identical. They all experience random shutdowns/restarts that are software initiated. On one of the computers a dialog pops up with a countdown until system restart, apparently started by NT-AUTHORITY\SYSTEM and has to do with an RPC call. This dialog in particular is exactly the same as those described in articles detailing older RPC exploit worms. When two of the computers rebooted, they came back up at the login prompt (they are domain computers) but the user name listed was 'admin', even though they hadn't logged in as admin. On our Windows Server 2003 machine running the domain, I noticed several thousand login attempts from various sources. They tried all different login names including Administrator, admin, user, server, owner and others. Some of the logs listed IPs, some didn't. Of the ones that did have source IP address (for the failed logins) two of them correspond to the two Windows XP machines experiencing reboots. Just yesterday I noticed a bunch of failed login attempts from an outside IP address. A traceroute showed that outside IP address to be from a Canadian ISP. We shouldn't have an connections from there, ever (we do have VPN users though). So I am still not sure whats going on with the login attempts coming from a foriegn IP. It seems obvious that some sort of malware is on these computers, and part of what it does is try to enumerate passwords on domain accounts to gain access. **What I've Done So Far** After realizing what was happening, my first step was to make sure everyone was running up-to-date anti-virus and did a scan. Of the computers affected, one of them ha an expired anti-virus client, but the other two were current versions of Norton and full scans of both systems turned up nothing. The server itself regularly runs up-to-date anti-virus, and has not shown any infections. So 3/4 of the Windows NT based computers have up-to-date anti virus, but it hasn't detected anything. However I am convinced that something is going on, mainly evidenced by the thousands of failed login attempts for various accounts. I also noticed that the root of our main file share had pretty open permissions, so I just restricted it to read+execute for normal users. The administrator has full access of course. I am also about to have the users update their passwords (to strong ones), and I am going to rename to Administrator on the server and change its password. I already took of the machines off of the network, one is being replaced by a new one, but I know these things can spread through networks so I still need to get to the bottom of this. Also, the server has a NAT/Firewall setup with only certain ports open. I have yet to full investigate some of the Windows related services with ports open, as I am from a Linux background. **Now what?** So all the modern and up-to-date anti-virus hasn't detected anything, but I am absolutely convinced these computers have some sort of virus. I base this on the random restarts/instability of the XP machines combined with the thousands of login attempts originating from these machines. What I plan on doing is backing up user files on the affected machines, and then reinstalling windows and freshly formatting the drives. I also am taking a few measures to secure the common file shares that may have been used to spread to other machines. Knowing all this, what can I do to ensure that this worm isn't somewhere else on the network, and how can I stop it from spreading? I know this is a drawn out question, but I am out of my depths here and could use some pointers. Thanks for looking!
2011/12/09
[ "https://serverfault.com/questions/339552", "https://serverfault.com", "https://serverfault.com/users/71559/" ]
The first lesson to take from this is that AV solutions aren't perfect. Not even close. If you are up to date with the AV software vendors, call them. All of them have support numbers for exactly this sort of thing. As a matter of fact they'll probably be very interested in what hit you. As others have said, take each machine down, wipe it and reinstall. You might take this opportunity to get everyone off of XP anyway. It's been a dead OS for quite some time. At the very least this should involve destroying the HD partitions and reformatting them. Although, it sounds like there aren't that many machines involved, so buying completely new replacements might be a better option. Also, let your boss(es) know that this just got expensive. Finally, why in the world would you run all of that off of a single server? (Rhetorical, I know you "inherited" it) A DC should NEVER be accessible from the internet. Fix this by getting the appropriate hardware in place to take care of the functionality you need.
It's most likely a rootkit if your A/V programs turn up nothing. Try running [TDSSkiller](http://support.kaspersky.com/faq/?qid=208280684) and see what you find. Also, this would be a perfect time to simply replace the archaic Windows XP computers with something less than over a decade old. Aside from software like anti-virus programs, I've seen very very little in the way of programs that couldn't be made to run via a shim or loosening a few NTFS/Registry permissions on Windows 7. There's really little excuse for continuing to run XP.
68,780,038
I currently have an API where it uploads a PDF to a lesson but I want to make the PDF upload nullable but it returns an error: > > Error: Call to a member function store() on null in file C:\xampp\htdocs\drv-api\app\Http\Controllers\Api\LessonCRUDController.php on line 66 > > > And this is my line 66: > > $uploaded\_files = $request->file->store('public/uploads/'); > > > I want to make the PDF file upload nullable. Any help will be appreciated. Thank you!
2021/08/14
[ "https://Stackoverflow.com/questions/68780038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16621915/" ]
You can check if the uploaded file is valid using `isValid()` method. ``` if($request->file->isValid()){ $uploaded_files = $request->file->store('public/uploads/'); } ```
I now fixed this and this is the code I added: ``` $file = $request->file('file'); $file = $request->file; if ($request->hasFile('file')) { $original_file_name = $request->file->getClientOriginalName(); // $uploaded_files = $request->file->store('public/uploads/'); $uploaded_files = $request->file->storeAs('public/uploads/', $request->file->getClientOriginalName()); $lessons->lesson_pdf = $request->file->hashName(); $results = $lessons->save(); } ``` I also read this article from laravel: laravel.com/docs/8.x/requests#retrieving-uploaded-files
538,937
I'm trying to install vCenter 5.1 on a windows 2012 dedicated (with SQL express standalone) During the installation of the Single Sign On module i've a warning "the fully qualified domain name cannot be resolved with nslookup. if you continue the installation some features might not work correctly. for detailed requiments see the installation and setup guide" The only indication that i've found are about the reverse zone dns resolution.. and this works! * i've verified that the dns works properly with nslookup > > > ``` > C:\Users\admin>nslookup srv6.mydomain.local > Server: srv2.mydomain.local > Address: 172.25.4.22 > Nome: srv6.mydomain.local > Address: 172.25.1.26 > > > C:\Users\admin>nslookup 172.25.1.26 > Server: srv2.mydomain.local > Address: 172.25.4.22 > > Nome: srv6.mydomain.local > Address: 172.25.1.26 > > ``` > > (all ip are right: I've the vCenter=srv6 and DC+DNS=srv2 on different vlan) * i've tryed to force the resolution of the ip changing the [..]\drivers\etc\hosts file * i've disabled the IPv6 support * i've used all combination with domain prefixes (explicit, by dhcp, undefined..) * i've disabled all antivirus/firewall (kaspersky end point 10) is this a bug of vcenter 5.1.0-1065152 ? have you got any suggestions for me?
2013/09/14
[ "https://serverfault.com/questions/538937", "https://serverfault.com", "https://serverfault.com/users/171115/" ]
*(you don't need to obfuscate your private IP addresses... it hurts question readability)* Please make sure you have the reverse zone configured properly and records populated for that IP/name. VMware SSO is odd in that it *can* query the forward and reverse on *every* interface on the server. Do you have multiple interfaces on this system? It sounds like a physical server, so possibly? Check the log details in: `{system drive}\users\{username}\AppData\Local\Temp\vm_ssoreg.log`
If you added reverse dns record after first check, try to flush dns cache ``` ipconfig /flushdns ``` and try again
538,937
I'm trying to install vCenter 5.1 on a windows 2012 dedicated (with SQL express standalone) During the installation of the Single Sign On module i've a warning "the fully qualified domain name cannot be resolved with nslookup. if you continue the installation some features might not work correctly. for detailed requiments see the installation and setup guide" The only indication that i've found are about the reverse zone dns resolution.. and this works! * i've verified that the dns works properly with nslookup > > > ``` > C:\Users\admin>nslookup srv6.mydomain.local > Server: srv2.mydomain.local > Address: 172.25.4.22 > Nome: srv6.mydomain.local > Address: 172.25.1.26 > > > C:\Users\admin>nslookup 172.25.1.26 > Server: srv2.mydomain.local > Address: 172.25.4.22 > > Nome: srv6.mydomain.local > Address: 172.25.1.26 > > ``` > > (all ip are right: I've the vCenter=srv6 and DC+DNS=srv2 on different vlan) * i've tryed to force the resolution of the ip changing the [..]\drivers\etc\hosts file * i've disabled the IPv6 support * i've used all combination with domain prefixes (explicit, by dhcp, undefined..) * i've disabled all antivirus/firewall (kaspersky end point 10) is this a bug of vcenter 5.1.0-1065152 ? have you got any suggestions for me?
2013/09/14
[ "https://serverfault.com/questions/538937", "https://serverfault.com", "https://serverfault.com/users/171115/" ]
I got the same error doing the same (fresh install of 5.1 on windows 2012). My DNS setup is also perfectly okay (incl. reverse lookup), so I just ignored the warning. Everything installed fine and is now working without any issues.
If you added reverse dns record after first check, try to flush dns cache ``` ipconfig /flushdns ``` and try again
3,480,462
I grew up with Portuguese as my first language, both my parents are immigrants without a high school diploma. My dad taught me multiplication over the course of a couple of days at 5 years old but didn't know any mathematics beyond that. He worked construction since the age of 15, my mom never held down a job, dropped out of high school in Portugal to work on a farm. She speaks broken English. My elementary school was OK, I got all A's from 2nd grade to 5th grade without much effort. There was a kid named Ryan that I would tutor that ending up doing well. 6th grade our elementary school got a new teacher, the class average was a D. I found it impossible to learn from her. Ryan got lucky with a good teacher for 6th grade. We were sent to an inner city middle school, I was put in standard class's because of a poor performance in 6th grade. He was put in honors class's. 75% of the kids in my class's in the 7th and 8th grade were living in project housing, had a parent in prison, or from a single parent home living on the poverty line. A small group of kids would harass the teachers and disrupt the class room so that 90% of the class was babysitting. This carried over into high school which was actually worse, a lot of my high school classmates are serving time in prison with a couple for murder convictions. Ryan stayed in honors class's throughout, eventually getting into BU. I fell so far behind that although I graduated high school on time, I didn't even know how to simplify basic fractions. I didn't know what "x" was in a mathematical context. I just assumed I was bad at math. My Algebra 1 teacher taught us nothing we watched movies all day, same with geometry, I was completely lost in Algebra 2. I would get mostly D's, I failed Chemistry twice, with my second Chemistry teacher saying that I had a strong work ethic. After working dead end jobs and trying my hand at boxing and music in my early 20's I decided to go to community college after a severe boxing injury. Boxing gave me a lot of confidence, I did fine at community college for a year and got into state university. I was soo confidenct that decided to take Calculus without knowing any algebra, geometry, trig, or precalc, or even how to properly manipulate fractions. My advisor told me I was insane, she told me that I would 100% fail if I took Calculus based on my transcripts. From sheer willpower and brute force I managed a B in Calculus teaching myself the absolute basics of algebra, geometry, trig, and pre calc along the way and just rote memorizing everything. I just took Calc and nothing else while working a full time 40 hr job. My guidance councilor was in complete disbelief. After a talk she recommended that I enroll in the Physics program so I did, she thought I was like the guy from Good Will Hunting. I did ok the first semester but did worse and worse as I went on, I couldn't complete a Physics undergrad without really knowing Algebra or so much of the other high school maths, so I took a year off of school. I bought an Algebra 1 and 2 textbook, a geometry text book, trig textbook, a high school physics book and chemistry. I worked a job 20 hours a week and thoroughly taught myself all those high school math and science subjects over the course of a year to the point were I would search the internet for a Pre-Calc / Geometry / Trig problem that I couldn't solve but couldn't find any. I was able to solve any math problem I could find on the internet that only required up to high school pre-calc. I re-enrolled in class's at univeristy, I retook Calc 1 with the hardest professor at the university, I took Classical Mechanics with the hardest physics professor at the university, I also took astronomy and a logic course. I got 100 on every test in all my class's and 120 on my Calc final. The average grade in the class for Calc was a 55. I felt like things were finally going to start going my way . . . boy was I wrong. I discovered that a really poor primary school education and growing up in poverty was only a part of the reason I had done poorly historically in school . . . I also have ADHD. I did great for a couple of semesters and then started doing poorly again . . . This time I was at my wits end . . I couldn't understand why I was doing poorly again but I've pretty much come to a conclusion. After reading a bit of some great text books in Real Analysis and Topology I've come to the conclusion that school just isn't for me. It's not that I'm stupid or bad at math or whatever it's just that lectures are a complete waste of time for me. My time is 100% best served by reading through well written advanced math texts and learning everything at my own pace from there. In hindsight, what I should have done when I had finished teaching myself all of middle school and high school mathematics and science extremely thoroughly and rigorously over the course of a year, I should have continued to teach myself all of College Math and College freshman and sophomore Physics from home using quality texts. After teaching myself all of College math, I could have enrolled back in college and taken all the necessary courses for a BS in mathematics in 2 years after which I likely would have had the opportunity at grad school or at least a good transcript. My transcript now just looks like a hodgepodge of what the heck was going on with you. Now in the second part of my Junior year in the math program and in my late 20's I'm getting annoyed that I don't have a career yet. I'm extremely tempted to take 1 or 2 years off and load up on self teaching math texts, go back and finish with all A's in 1 year, rather than continue doing crappy and finishing in 2 years anyways, getting worse grades and learning less. Part of me says screw it and take the next 6 to 9 months mastering my Python programming skill set and getting a decent a job so I can finally start a family with my Fiance. Ryan, the guy who I tutored in Elementary school has started a family, makes over 100K working at a big bank as a bank manager. I just feel so behind . . . part of me regrets not becoming a Plumber out of high school, I'd have bought a house by now and established a family. Any advice on what to do next?
2019/12/18
[ "https://math.stackexchange.com/questions/3480462", "https://math.stackexchange.com", "https://math.stackexchange.com/users/387822/" ]
It is not hard to see that$$(\forall n\in\mathbb N):\left(1+\sqrt2\right)^n+\left(1-\sqrt2\right)^n\in\mathbb N.$$Besides, $\lim\_{n\to\infty}\left(1-\sqrt2\right)^n=0$ and $(\forall n\in\mathbb N):\sin(n\pi)=0$. Therefore,$$\lim\_{n\to\infty}\sin\left(\left(1+\sqrt2\right)^n\pi\right)=0.$$
Write $$\sin((1+\sqrt{2})^n\pi+(1-\sqrt{2})^n\pi-(1-\sqrt{2})^n\pi)$$ and use the addition formulas for the sin-function.
4,568,166
i tring to send print command through VB using mscomm control it working fine but it throw error: '4 line clode is below ``` MSComm1.CommPort = 1 MSComm1.Settings = "9600 ,N,8,1" MSComm1.PortOpen = False MSComm1.Output = "String to hardware" ``` Error: (8015) Could not set comm state, there may be one or more invalid communications parameters.
2010/12/31
[ "https://Stackoverflow.com/questions/4568166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558966/" ]
Nothing is working because your port is closed. Line 3 should be as follows: `MSComm1.PortOpen = True` Setting the `PortOpen` proptery to `true` opens the port. Setting it to `false` closes it.
Do not set printer on port COM1. COM1 port will be occupied by Printer in COM1 port. When use Visual Basic MSCOMM component, you do not need any printer driver. If you do set Printer in COM1 port. You can use the following code. this code will not impacted by printer setting. Visual Basic: Open "COM1" For Output AS #1
4,568,166
i tring to send print command through VB using mscomm control it working fine but it throw error: '4 line clode is below ``` MSComm1.CommPort = 1 MSComm1.Settings = "9600 ,N,8,1" MSComm1.PortOpen = False MSComm1.Output = "String to hardware" ``` Error: (8015) Could not set comm state, there may be one or more invalid communications parameters.
2010/12/31
[ "https://Stackoverflow.com/questions/4568166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558966/" ]
Nothing is working because your port is closed. Line 3 should be as follows: `MSComm1.PortOpen = True` Setting the `PortOpen` proptery to `true` opens the port. Setting it to `false` closes it.
uninstall driver for com1, then restart windows, and try. it will work
4,568,166
i tring to send print command through VB using mscomm control it working fine but it throw error: '4 line clode is below ``` MSComm1.CommPort = 1 MSComm1.Settings = "9600 ,N,8,1" MSComm1.PortOpen = False MSComm1.Output = "String to hardware" ``` Error: (8015) Could not set comm state, there may be one or more invalid communications parameters.
2010/12/31
[ "https://Stackoverflow.com/questions/4568166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558966/" ]
The same 8015 error happened to me while trying to communicate with external hardware. I have only COM1 in the mainboard, and I had installed an EPSON TM-T88III in COM1, but was not using it. I changed the COM port in the printer to COM4 (although it does not exist physically) and voilà: My VB6 program opened COM1 with no problems. Bottomline: Doublecheck that no other hardware or driver has the port open, thus blocking it, even if you're not explicitly using that other hardware or driver. Bottomline 2: Make sure that `MSComm1.PortOpen = False` is changed to `MSComm1.PortOpen = True`, other wise you'll NOT be able to communicate at all!
Do not set printer on port COM1. COM1 port will be occupied by Printer in COM1 port. When use Visual Basic MSCOMM component, you do not need any printer driver. If you do set Printer in COM1 port. You can use the following code. this code will not impacted by printer setting. Visual Basic: Open "COM1" For Output AS #1
4,568,166
i tring to send print command through VB using mscomm control it working fine but it throw error: '4 line clode is below ``` MSComm1.CommPort = 1 MSComm1.Settings = "9600 ,N,8,1" MSComm1.PortOpen = False MSComm1.Output = "String to hardware" ``` Error: (8015) Could not set comm state, there may be one or more invalid communications parameters.
2010/12/31
[ "https://Stackoverflow.com/questions/4568166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558966/" ]
The same 8015 error happened to me while trying to communicate with external hardware. I have only COM1 in the mainboard, and I had installed an EPSON TM-T88III in COM1, but was not using it. I changed the COM port in the printer to COM4 (although it does not exist physically) and voilà: My VB6 program opened COM1 with no problems. Bottomline: Doublecheck that no other hardware or driver has the port open, thus blocking it, even if you're not explicitly using that other hardware or driver. Bottomline 2: Make sure that `MSComm1.PortOpen = False` is changed to `MSComm1.PortOpen = True`, other wise you'll NOT be able to communicate at all!
uninstall driver for com1, then restart windows, and try. it will work
12,068,704
I am trying to display a simple jtable in frame but It is not displaying the columns of the table, I followed the example from the oracle tutorials but there is something I am not doing right. The program is compiling and running. Here is the code: ``` import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.math.BigDecimal; import java.math.RoundingMode; public class SimpleTableDemo extends JPanel { SimpleTableDemo() { String[] columnNames = {"#", "Repayment Dates", "Principle Amount", "Interest", "Comission fee", "Total installement amount", "Principle balance"}; // BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN); //each line of the two dimentional array is a line in the table Object[][] data = { {new Integer(1), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(2), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(3), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(4), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(5), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(6), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(7), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(8), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(9), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(10), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(11), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(12), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(13), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(14), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(15), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(16), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(17), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, {new Integer(18), new java.util.Date(), new BigDecimal(12509.23).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(1571.77).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(0.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(14081.00).setScale(2, RoundingMode.HALF_EVEN), new BigDecimal(147490.77).setScale(2, RoundingMode.HALF_EVEN)}, }; JTable table = new JTable(data, columnNames); // JScrollPane scrollPane = new JScrollPane(table); // scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); table.setFillsViewportHeight(true); this.add(table); } public static void main(String[] args) { JFrame application = new JFrame(); SimpleTableDemo panel = new SimpleTableDemo(); application.add(panel); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // application.setSize(730,650); application.pack(); application.setLocationRelativeTo(panel); // application.setResizable(false); application.setVisible(true); } } ```
2012/08/22
[ "https://Stackoverflow.com/questions/12068704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506241/" ]
Table columns are only automatically displayed if the `JTable` is inside a `JScrollPane`. Instead of `this.add(table);`, try `this.add(new JScrollPane(table));` Actually, you seem to have some scrollpane-related code lying about already - just uncomment `JScrollPane scrollPane = new JScrollPane(table);` and change `this.add(table);` to `this.add(scrollpane);`
Having a `JScrollPane` always helps. You already have the following code: ``` JScrollPane scrollPane = new JScrollPane(table); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); ``` All you need to do is add your `JTable` to this `scrollpane`. However,I would suggest that any updates to the user interface to happen on the **event dispatch thread**. Basically, instead of having this: ``` public static void main(String[] args) { JFrame application = new JFrame(); SimpleTableDemo panel = new SimpleTableDemo(); application.add(panel); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // application.setSize(730,650); application.pack(); application.setLocationRelativeTo(panel); // application.setResizable(false); application.setVisible(true); } ``` Consider: ``` public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JFrame application = new JFrame(); SimpleTableDemo panel = new SimpleTableDemo(); application.add(panel); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // application.setSize(730,650); application.pack(); application.setLocationRelativeTo(panel); // application.setResizable(false); application.setVisible(true); } }); } ``` [This article](http://www.javamex.com/tutorials/threads/invokelater.shtml) might help you understand the concept of "Threading with Swing"
43,585,705
I want to replace every white pixel in an image by black, but keep everything else unchanged ``` Window { id: window; width: 800; height: 600; visible: true; Image { id: sourceImage anchors.centerIn: parent source: "qrc:/source.png" } Item { anchors.fill: sourceImage layer.enabled: true layer.samplerName: "maskSource" layer.effect: ShaderEffect { fragmentShader: " uniform lowp sampler2D maskSource; uniform lowp float qt_Opacity; varying highp vec2 qt_TexCoord0; void main() { vec4 pixel = texture2D(maskSource, qt_TexCoord0); if (pixel == vec4(1.0, 1.0, 1.0, pixel.a)) { pixel = vec4(0.0, 0.0, 0.0, pixel.a); } gl_FragColor = vec4(pixel.r, pixel.g, pixel.b, pixel.a); }" } } } ``` I can't manage to make it work
2017/04/24
[ "https://Stackoverflow.com/questions/43585705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1107595/" ]
I found a solution to my problem : ``` ShaderEffect { property variant src: sourceImage vertexShader: " uniform highp mat4 qt_Matrix; attribute highp vec4 qt_Vertex; attribute highp vec2 qt_MultiTexCoord0; varying highp vec2 coord; void main() { coord = qt_MultiTexCoord0; gl_Position = qt_Matrix * qt_Vertex; }" fragmentShader: " uniform lowp sampler2D src; uniform lowp float qt_Opacity; varying highp vec2 coord; void main() { vec4 pixel = texture2D(src, coord); if (pixel.r > 0.2 && pixel.g > 0.2 && pixel.b > 0.2) { pixel.rgb = vec3(0.0, 0.0, 0.0); } gl_FragColor = pixel; }" } ``` The values I use to detect whites (0.2,0.2,0.2) work for my images, but they would probably not work for every cases. I don't know if this is the best that can be done.
Maybe you should use a `image preprocessing algorithm` in `Python` or `C++` for example on your image ? And then just load it in your `QML` application. QML is aimed to be used for UI part, and you have to avoid as much as possible to do such things like image processing in `QML`.
43,943,736
I need to copy all databases from server1 to Server2, i saw with SSIS is possible transfer objects with "Transfer SQL Database Task", but it works just for one database. It's possible coppy all databasses from server1 to server2 using SSIS ? Best Regards:
2017/05/12
[ "https://Stackoverflow.com/questions/43943736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6698229/" ]
The problem was that Gradle was not finding the Dagger generated files by `kapt`, so I solved the problem by adding `src/main/kapt` to my sourceSets configuration on my Core module (lib): **build.gradle (Core module)** ``` android { ... sourceSets { main.java.srcDirs += ['src/main/kotlin', 'src/main/kapt'] } } ``` After that, the Core module started finding their Dagger 2 generated files.
Java module should have ``` plugins { id("java-library") id("kotlin") id("kotlin-kapt") } java { sourceSets { main.java.srcDirs += ['build/generated/source/kapt/main'] } } ```
519,191
I managed to get working Apache and everything's fine. Got MySQL running, which is nice. But then it turned out that I had to use terminal for all the SQL commands I had to put inside. I'm not close to that good to manage database by commands. So I wanted to use phpmyadmin, which prompted thousands errors and I can't even look into a table I just set up. Does somebody know Ubuntu friendly MySQL database manager?
2014/09/02
[ "https://askubuntu.com/questions/519191", "https://askubuntu.com", "https://askubuntu.com/users/322131/" ]
Universal database managers a) DBeaver ``` wget -c http://dbeaver.jkiss.org/files/dbeaver_3.4.5_i386.deb sudo dpkg -i dbeaver_3.4.5_i386.deb sudo apt-get install -f ``` b) Valentina Studio ``` wget -c https://www.valentina-db.com/en/studio/download/current/vstudio_x64_lin-deb?format=raw sudo dpkg -i vstudio_5_lin.deb sudo apt-get install -f ```
You can try Mysql Workbench: ``` sudo apt-get install mysql-workbench ``` This lives in universe, so you have to enable universe repository for that to work. That said, if you are going to code anything (esp. SQL), you will need to get used to command line.
519,191
I managed to get working Apache and everything's fine. Got MySQL running, which is nice. But then it turned out that I had to use terminal for all the SQL commands I had to put inside. I'm not close to that good to manage database by commands. So I wanted to use phpmyadmin, which prompted thousands errors and I can't even look into a table I just set up. Does somebody know Ubuntu friendly MySQL database manager?
2014/09/02
[ "https://askubuntu.com/questions/519191", "https://askubuntu.com", "https://askubuntu.com/users/322131/" ]
You can try Mysql Workbench: ``` sudo apt-get install mysql-workbench ``` This lives in universe, so you have to enable universe repository for that to work. That said, if you are going to code anything (esp. SQL), you will need to get used to command line.
There's also [SQuirreL SQL](http://squirrel-sql.sourceforge.net/#installation). It requires Java, so you might need to run first: ``` apt-get install openjdk-7-jre ```
519,191
I managed to get working Apache and everything's fine. Got MySQL running, which is nice. But then it turned out that I had to use terminal for all the SQL commands I had to put inside. I'm not close to that good to manage database by commands. So I wanted to use phpmyadmin, which prompted thousands errors and I can't even look into a table I just set up. Does somebody know Ubuntu friendly MySQL database manager?
2014/09/02
[ "https://askubuntu.com/questions/519191", "https://askubuntu.com", "https://askubuntu.com/users/322131/" ]
It seems that the question is not about the category "GUI clients that make writing SQL statements easier", but "clients that *avoid* SQL or generate it for you". So, relevant products would have wizards, or query builders, or table builders, or QBE. `phpMyAdmin` has already been excluded, and `MySQL Workbench` has already been mentioned. Non-WINE possibilities are 1. `SQLeo Visual Query Builder` (requires Java) 2. `Open Office Base` [OpenOffice Base website- creating tables](https://wiki.openoffice.org/wiki/Documentation/OOoAuthors_User_Manual/Getting_Started/Creating_database_tables) 3. `Adminer` [Adminer offical website](https://www.adminer.org/) (requires php). I am not a user of these products, I am only suggesting that they might fit the question.
You can try Mysql Workbench: ``` sudo apt-get install mysql-workbench ``` This lives in universe, so you have to enable universe repository for that to work. That said, if you are going to code anything (esp. SQL), you will need to get used to command line.
519,191
I managed to get working Apache and everything's fine. Got MySQL running, which is nice. But then it turned out that I had to use terminal for all the SQL commands I had to put inside. I'm not close to that good to manage database by commands. So I wanted to use phpmyadmin, which prompted thousands errors and I can't even look into a table I just set up. Does somebody know Ubuntu friendly MySQL database manager?
2014/09/02
[ "https://askubuntu.com/questions/519191", "https://askubuntu.com", "https://askubuntu.com/users/322131/" ]
Universal database managers a) DBeaver ``` wget -c http://dbeaver.jkiss.org/files/dbeaver_3.4.5_i386.deb sudo dpkg -i dbeaver_3.4.5_i386.deb sudo apt-get install -f ``` b) Valentina Studio ``` wget -c https://www.valentina-db.com/en/studio/download/current/vstudio_x64_lin-deb?format=raw sudo dpkg -i vstudio_5_lin.deb sudo apt-get install -f ```
There's also [SQuirreL SQL](http://squirrel-sql.sourceforge.net/#installation). It requires Java, so you might need to run first: ``` apt-get install openjdk-7-jre ```
519,191
I managed to get working Apache and everything's fine. Got MySQL running, which is nice. But then it turned out that I had to use terminal for all the SQL commands I had to put inside. I'm not close to that good to manage database by commands. So I wanted to use phpmyadmin, which prompted thousands errors and I can't even look into a table I just set up. Does somebody know Ubuntu friendly MySQL database manager?
2014/09/02
[ "https://askubuntu.com/questions/519191", "https://askubuntu.com", "https://askubuntu.com/users/322131/" ]
It seems that the question is not about the category "GUI clients that make writing SQL statements easier", but "clients that *avoid* SQL or generate it for you". So, relevant products would have wizards, or query builders, or table builders, or QBE. `phpMyAdmin` has already been excluded, and `MySQL Workbench` has already been mentioned. Non-WINE possibilities are 1. `SQLeo Visual Query Builder` (requires Java) 2. `Open Office Base` [OpenOffice Base website- creating tables](https://wiki.openoffice.org/wiki/Documentation/OOoAuthors_User_Manual/Getting_Started/Creating_database_tables) 3. `Adminer` [Adminer offical website](https://www.adminer.org/) (requires php). I am not a user of these products, I am only suggesting that they might fit the question.
There's also [SQuirreL SQL](http://squirrel-sql.sourceforge.net/#installation). It requires Java, so you might need to run first: ``` apt-get install openjdk-7-jre ```
28,055,522
so I've had a bit of a problem with trying to make a section's width to 0 and have everything inside the object do the same thing. Essentially hide the section and everything inside it. Thing is, the section will change to a width of 0px but the text inside still displays and also sort of pushes off to the side. Is there any way that I can use either css or javascript to hide the text and bring it back when the sections width changes back over? Code pasted into jsfiddle: <http://jsfiddle.net/t6ck9ajb/> ``` $(document).ready(function(){ $("#about").click(function(){ if ($("#about-me").css("width") <= "0vw") { $("#introduction").animate({width:"0vw"}, 500); /*$("#intro").css("display","none"); $("#port").css("display","none"); $("#about").css("display","none"); */ } else { $("#introduction").animate({width:"0vw"}); } }); }); ``` This is what I have to attempt at hiding the text, but this didn't really hide it.
2015/01/20
[ "https://Stackoverflow.com/questions/28055522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4475798/" ]
If you're wanting to hide the content when the `'#about'` selector is clicked, why not just use `$('#introduction').toggle()`?
This a CSS issue. You need to add `overflow: hidden;` to whatever you want to be hidden with a change of width, in this case `#intro`.
28,055,522
so I've had a bit of a problem with trying to make a section's width to 0 and have everything inside the object do the same thing. Essentially hide the section and everything inside it. Thing is, the section will change to a width of 0px but the text inside still displays and also sort of pushes off to the side. Is there any way that I can use either css or javascript to hide the text and bring it back when the sections width changes back over? Code pasted into jsfiddle: <http://jsfiddle.net/t6ck9ajb/> ``` $(document).ready(function(){ $("#about").click(function(){ if ($("#about-me").css("width") <= "0vw") { $("#introduction").animate({width:"0vw"}, 500); /*$("#intro").css("display","none"); $("#port").css("display","none"); $("#about").css("display","none"); */ } else { $("#introduction").animate({width:"0vw"}); } }); }); ``` This is what I have to attempt at hiding the text, but this didn't really hide it.
2015/01/20
[ "https://Stackoverflow.com/questions/28055522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4475798/" ]
Here is a different approach: ```js $(function(){ $('#about').on('click', homeAboutToggle); $('#home').on('click', homeAboutToggle); }); function homeAboutToggle(){ $('#introduction').toggleClass('active'); $('#about-me').toggleClass('active'); } ``` ```css * { margin: 0px 0px; padding: 0px 0px; font-family: "Open Sans"; } #container{ width: 100vw; height: 100vh; overflow:hidden; position:relative; } .full-page { width: 100vw; height: 100vh; background-color: #5085aa; position: absolute; float: left; transition:all ease-in-out 400ms; -webkit-transition:all ease-in-out 400ms; } .full-page.right{ transform: translateX(100vw); -webkit-transform: translateX(100vw); } .full-page.left{ transform: translateX(-100vw); -webkit-transform: translateX(-100vw); } .full-page.active{ transition:all ease-in-out 400ms; -webkit-transition:all ease-in-out 400ms; transform: translateX(0); -webkit-transform: translateX(0); } #introduction { z-index: 1; } #about-me { z-index: 0; } #information { text-align: center; } #intro { font-size: 4vw; color: white; text-align: center; padding-top: 30vh; } #port{ position: absolute; right: 3vw; bottom: 5vh; color: white; font-size: 1.5vw; text-decoration: none; font-weight: bold; } #home, #about{ position: absolute; left: 3vw; bottom: 5vh; color: white; font-size: 1.5vw; text-decoration: none; font-weight: bold; } #about:active #about-me { width: 100vw; } .big { font-size: 8vw; color: lightblue; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="container"> <section class="full-page right" id="about-me"> <h1 id="information">About Me</h1> <a id="home">Back home</a> </section> <section class="full-page left active" id="introduction"> <h1 id="intro">Hello, my name is<br/><span class="big">Michael!</span> </h1> <a id="port">Portfolio</a> <a id="about">About Me</a> </section> </div> </body> ```
If you're wanting to hide the content when the `'#about'` selector is clicked, why not just use `$('#introduction').toggle()`?
28,055,522
so I've had a bit of a problem with trying to make a section's width to 0 and have everything inside the object do the same thing. Essentially hide the section and everything inside it. Thing is, the section will change to a width of 0px but the text inside still displays and also sort of pushes off to the side. Is there any way that I can use either css or javascript to hide the text and bring it back when the sections width changes back over? Code pasted into jsfiddle: <http://jsfiddle.net/t6ck9ajb/> ``` $(document).ready(function(){ $("#about").click(function(){ if ($("#about-me").css("width") <= "0vw") { $("#introduction").animate({width:"0vw"}, 500); /*$("#intro").css("display","none"); $("#port").css("display","none"); $("#about").css("display","none"); */ } else { $("#introduction").animate({width:"0vw"}); } }); }); ``` This is what I have to attempt at hiding the text, but this didn't really hide it.
2015/01/20
[ "https://Stackoverflow.com/questions/28055522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4475798/" ]
If you're wanting to hide the content when the `'#about'` selector is clicked, why not just use `$('#introduction').toggle()`?
Here a working fiddle with the intended animation: [fiddle](http://jsfiddle.net/t6ck9ajb/3/) CSS: ``` #introduction { z-index: 1; visibility:"visible"; overflow:hidden; } ``` jQuery ``` $(document).ready(function () { $("#about").click(function () { if ($("#about-me").css("width") <= "0px") { $("#introduction").animate({ width: "0px" }, 500, function () { $("#introduction").css("visibility", "hidden"); }) } else { $("#introduction").animate({ width: "0px" }); } }); }); ```
28,055,522
so I've had a bit of a problem with trying to make a section's width to 0 and have everything inside the object do the same thing. Essentially hide the section and everything inside it. Thing is, the section will change to a width of 0px but the text inside still displays and also sort of pushes off to the side. Is there any way that I can use either css or javascript to hide the text and bring it back when the sections width changes back over? Code pasted into jsfiddle: <http://jsfiddle.net/t6ck9ajb/> ``` $(document).ready(function(){ $("#about").click(function(){ if ($("#about-me").css("width") <= "0vw") { $("#introduction").animate({width:"0vw"}, 500); /*$("#intro").css("display","none"); $("#port").css("display","none"); $("#about").css("display","none"); */ } else { $("#introduction").animate({width:"0vw"}); } }); }); ``` This is what I have to attempt at hiding the text, but this didn't really hide it.
2015/01/20
[ "https://Stackoverflow.com/questions/28055522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4475798/" ]
Here is a different approach: ```js $(function(){ $('#about').on('click', homeAboutToggle); $('#home').on('click', homeAboutToggle); }); function homeAboutToggle(){ $('#introduction').toggleClass('active'); $('#about-me').toggleClass('active'); } ``` ```css * { margin: 0px 0px; padding: 0px 0px; font-family: "Open Sans"; } #container{ width: 100vw; height: 100vh; overflow:hidden; position:relative; } .full-page { width: 100vw; height: 100vh; background-color: #5085aa; position: absolute; float: left; transition:all ease-in-out 400ms; -webkit-transition:all ease-in-out 400ms; } .full-page.right{ transform: translateX(100vw); -webkit-transform: translateX(100vw); } .full-page.left{ transform: translateX(-100vw); -webkit-transform: translateX(-100vw); } .full-page.active{ transition:all ease-in-out 400ms; -webkit-transition:all ease-in-out 400ms; transform: translateX(0); -webkit-transform: translateX(0); } #introduction { z-index: 1; } #about-me { z-index: 0; } #information { text-align: center; } #intro { font-size: 4vw; color: white; text-align: center; padding-top: 30vh; } #port{ position: absolute; right: 3vw; bottom: 5vh; color: white; font-size: 1.5vw; text-decoration: none; font-weight: bold; } #home, #about{ position: absolute; left: 3vw; bottom: 5vh; color: white; font-size: 1.5vw; text-decoration: none; font-weight: bold; } #about:active #about-me { width: 100vw; } .big { font-size: 8vw; color: lightblue; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="container"> <section class="full-page right" id="about-me"> <h1 id="information">About Me</h1> <a id="home">Back home</a> </section> <section class="full-page left active" id="introduction"> <h1 id="intro">Hello, my name is<br/><span class="big">Michael!</span> </h1> <a id="port">Portfolio</a> <a id="about">About Me</a> </section> </div> </body> ```
This a CSS issue. You need to add `overflow: hidden;` to whatever you want to be hidden with a change of width, in this case `#intro`.
28,055,522
so I've had a bit of a problem with trying to make a section's width to 0 and have everything inside the object do the same thing. Essentially hide the section and everything inside it. Thing is, the section will change to a width of 0px but the text inside still displays and also sort of pushes off to the side. Is there any way that I can use either css or javascript to hide the text and bring it back when the sections width changes back over? Code pasted into jsfiddle: <http://jsfiddle.net/t6ck9ajb/> ``` $(document).ready(function(){ $("#about").click(function(){ if ($("#about-me").css("width") <= "0vw") { $("#introduction").animate({width:"0vw"}, 500); /*$("#intro").css("display","none"); $("#port").css("display","none"); $("#about").css("display","none"); */ } else { $("#introduction").animate({width:"0vw"}); } }); }); ``` This is what I have to attempt at hiding the text, but this didn't really hide it.
2015/01/20
[ "https://Stackoverflow.com/questions/28055522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4475798/" ]
Here is a different approach: ```js $(function(){ $('#about').on('click', homeAboutToggle); $('#home').on('click', homeAboutToggle); }); function homeAboutToggle(){ $('#introduction').toggleClass('active'); $('#about-me').toggleClass('active'); } ``` ```css * { margin: 0px 0px; padding: 0px 0px; font-family: "Open Sans"; } #container{ width: 100vw; height: 100vh; overflow:hidden; position:relative; } .full-page { width: 100vw; height: 100vh; background-color: #5085aa; position: absolute; float: left; transition:all ease-in-out 400ms; -webkit-transition:all ease-in-out 400ms; } .full-page.right{ transform: translateX(100vw); -webkit-transform: translateX(100vw); } .full-page.left{ transform: translateX(-100vw); -webkit-transform: translateX(-100vw); } .full-page.active{ transition:all ease-in-out 400ms; -webkit-transition:all ease-in-out 400ms; transform: translateX(0); -webkit-transform: translateX(0); } #introduction { z-index: 1; } #about-me { z-index: 0; } #information { text-align: center; } #intro { font-size: 4vw; color: white; text-align: center; padding-top: 30vh; } #port{ position: absolute; right: 3vw; bottom: 5vh; color: white; font-size: 1.5vw; text-decoration: none; font-weight: bold; } #home, #about{ position: absolute; left: 3vw; bottom: 5vh; color: white; font-size: 1.5vw; text-decoration: none; font-weight: bold; } #about:active #about-me { width: 100vw; } .big { font-size: 8vw; color: lightblue; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="container"> <section class="full-page right" id="about-me"> <h1 id="information">About Me</h1> <a id="home">Back home</a> </section> <section class="full-page left active" id="introduction"> <h1 id="intro">Hello, my name is<br/><span class="big">Michael!</span> </h1> <a id="port">Portfolio</a> <a id="about">About Me</a> </section> </div> </body> ```
Here a working fiddle with the intended animation: [fiddle](http://jsfiddle.net/t6ck9ajb/3/) CSS: ``` #introduction { z-index: 1; visibility:"visible"; overflow:hidden; } ``` jQuery ``` $(document).ready(function () { $("#about").click(function () { if ($("#about-me").css("width") <= "0px") { $("#introduction").animate({ width: "0px" }, 500, function () { $("#introduction").css("visibility", "hidden"); }) } else { $("#introduction").animate({ width: "0px" }); } }); }); ```
56,296,546
I am updating a form to have two sets of radio buttons that turns on or off panels. The first says "Yes" to contact the customer or "No". If we are to contact, then present choice of which method is used, phone or email. (Previously there was just the question to contact or not.) While I can get the show function to work properly, I do not understand why I cannot get the radio button to show as selected. (It could be that I am fairly green to AngularJS.) ``` <div class="radio styled-radio" id="callTheCustomerDiv"> <input class="form-control" id="callTheCustomerRadio1" name="callTheCustomer" type="radio" value="Yes" ng-required="issueType=='IncidentDiv'" ng-model="$parent.callTheCustomer" ng-click="contactSelection('none')"/> <label for="callTheCustomerRadio1"> Yes</label> - Please indicate how the customer wants to be contacted.<br/> <div class="form-group" id="howToContactDiv" ng-show=state class="row fullWidth"> <div id="contactOptions" class="form-group"> <label for="phoneRadio">Phone</label> <!-- radio indicator is not working correctly --> <input id="phoneRadio" class="form-control" type="radio" ng-click="contactSelection('phone')" name="phoneSelect" ng-model="$parent.phoneSelect" value="{{$parent.phoneSelect}}" /> &nbsp; &nbsp; &nbsp; &nbsp; <label for="emailRadio">Email</label> <input id="emailRadio" class="form-control" type="radio" ng-click="contactSelection('email')" name="emailSelect" ng-model="$parent.emailSelect" value="{{$parent.emailSelect}}" /> <br/> <!-- phoneSelect : {{phoneSelect}} --> </div> <div id="phoneContact" ng-show="contactType=='phone'"> <span>Phone <input class="form-control input-sm" type="text" name="callTheCustomerPhone" id="callTheCustomerPhone" ng-model="$parent.callTheCustomerPhone" ng-required="$parent.contactType=='phone' && accForm.phoneNumber.$viewValue === ''" maxlength="20"/> </span> </div> ``` ``` <br/> <div id="emailContact" ng-show="contactType=='email'"> <span>Email <input class="form-control input-sm" type="text" name="emailTheCustomer" id="emailTheCustomer" ng-model="$parent.emailTheCustomer" ng-required="$parent.contactType=='email' && accForm.emailTheCustomer.$viewValue === ''" maxlength="150"/></span> </div> </div> <input class="form-control" id="callTheCustomerRadio2" name="callTheCustomer" type="radio" value="No" ng-required="issueType=='IncidentDiv'" ng-model="$parent.callTheCustomer" ng-click="contactSelection('no')"/> <label for="callTheCustomerRadio2">No</label> </div> ``` Looks like this when Phone is selected: --------------------------------------- [![enter image description here](https://i.stack.imgur.com/dQ8Ib.png)](https://i.stack.imgur.com/dQ8Ib.png) and like this when email is selected: ------------------------------------- [![enter image description here](https://i.stack.imgur.com/oEW4T.png)](https://i.stack.imgur.com/oEW4T.png) I added this method to the Main controller: ------------------------------------------- ``` $scope.contactSelection = (function (contact) { if (contact=='none' ||contact=='email' ||contact=='phone'){ $scope.state = true; $scope.contactType = contact; if (contact=='phone'){$scope.phoneSelect = true;$scope.emailSelect = false;} if (contact=='email'){$scope.emailSelect = true;$scope.phoneSelect = false;} }else{ $scope.state = false; $scope.contactType = 'no'; $scope.emailTheCustomer = ''; $scope.callTheCustomerPhone = ''; $scope.phoneSelect = false; $scope.emailSelect = false; } }); ```
2019/05/24
[ "https://Stackoverflow.com/questions/56296546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552782/" ]
Radio buttons normally come in groups and the `name` attribute is used to group them. There are two radio groups in your code, the Yes/No and Phone/Email. The Yes/No radio buttons have the same name `callTheCustomer` while the Phone/Email radio buttons have different names. Change the `name` attributes for the phone and email radio buttons to something more meaningful to that group like `phoneOrEmail`.
Couple things were in play here 1. I had to change the label-input tag order. ``` <div class="radio styled-radio" id="callTheCustomerDiv"> <input class="form-control" id="callTheCustomerRadio1" name="callTheCustomer" type="radio" value="Yes" ng-required="issueType=='IncidentDiv'" ng-model="callTheCustomer" ng-click="contactSelection(null)" /> <label for="callTheCustomerRadio1"> Yes</label> - Please indicate how the customer wants to be contacted.<br/> <div class="form-group" id="howToContactDiv" ng-if="customerContact.contactOptionShow" class="row fullWidth"> <div id="contactOptionsDiv" > <div id="contactOptionsSelectDiv" > <input class="form-control" id="phoneRadio" type="radio" name="contactSelection" ng-model="customerContact.contactSelection" value="phone" /> <label for="phoneRadio">Phone</label> &nbsp; &nbsp; &nbsp; &nbsp; <input class="form-control" id="emailRadio" type="radio" name="contactSelection" ng-model="customerContact.contactSelection" value="email" /> <label for="emailRadio">Email</label> <br/> </div> <div id="phoneContactDiv" ng-show="customerContact.contactSelection=='phone'"> <span>Phone <input class="form-control input-sm" type="text" name="callTheCustomerPhone" id="callTheCustomerPhone" ng-model="callTheCustomerPhone" ng-required="customerContact.contactSelection=='phone' && accForm.phoneNumber.$viewValue === ''" maxlength="20"/></span> </div> <br/> <div id="emailContactDiv" ng-show="customerContact.contactSelection=='email'"> <span>Email <input class="form-control input-sm" type="text" name="emailTheCustomer" id="emailTheCustomer" ng-model="emailTheCustomer" ng-required="customerContact.contactSelection=='email' && accForm.emailTheCustomer.$viewValue === ''" maxlength="150"/></span> </div> </div> </div> <input class="form-control" id="callTheCustomerRadio2" name="callTheCustomer" type="radio" value="No" ng-required="issueType=='IncidentDiv'" ng-model="callTheCustomer" ng-click="contactSelection('clear')" /> <label for="callTheCustomerRadio2">No</label> </div> ``` 2. I completely removed the $parent references and simplified the function by using the properties of the variable. modified the mainController method and variable to look like: ``` $scope.customerContact ={ contactOptionShow : false, contactSelection : null }; $scope.contactSelection = (function (contact) { if (contact != null && contact=='clear' ){ $scope.customerContact.contactOptionShow = false; $scope.customerContact.contactSelection = ''; $scope.emailTheCustomer = ''; $scope.callTheCustomerPhone = ''; }else{ $scope.customerContact.contactOptionShow = true; } }); ``` I think it reads better now as well.
56,296,546
I am updating a form to have two sets of radio buttons that turns on or off panels. The first says "Yes" to contact the customer or "No". If we are to contact, then present choice of which method is used, phone or email. (Previously there was just the question to contact or not.) While I can get the show function to work properly, I do not understand why I cannot get the radio button to show as selected. (It could be that I am fairly green to AngularJS.) ``` <div class="radio styled-radio" id="callTheCustomerDiv"> <input class="form-control" id="callTheCustomerRadio1" name="callTheCustomer" type="radio" value="Yes" ng-required="issueType=='IncidentDiv'" ng-model="$parent.callTheCustomer" ng-click="contactSelection('none')"/> <label for="callTheCustomerRadio1"> Yes</label> - Please indicate how the customer wants to be contacted.<br/> <div class="form-group" id="howToContactDiv" ng-show=state class="row fullWidth"> <div id="contactOptions" class="form-group"> <label for="phoneRadio">Phone</label> <!-- radio indicator is not working correctly --> <input id="phoneRadio" class="form-control" type="radio" ng-click="contactSelection('phone')" name="phoneSelect" ng-model="$parent.phoneSelect" value="{{$parent.phoneSelect}}" /> &nbsp; &nbsp; &nbsp; &nbsp; <label for="emailRadio">Email</label> <input id="emailRadio" class="form-control" type="radio" ng-click="contactSelection('email')" name="emailSelect" ng-model="$parent.emailSelect" value="{{$parent.emailSelect}}" /> <br/> <!-- phoneSelect : {{phoneSelect}} --> </div> <div id="phoneContact" ng-show="contactType=='phone'"> <span>Phone <input class="form-control input-sm" type="text" name="callTheCustomerPhone" id="callTheCustomerPhone" ng-model="$parent.callTheCustomerPhone" ng-required="$parent.contactType=='phone' && accForm.phoneNumber.$viewValue === ''" maxlength="20"/> </span> </div> ``` ``` <br/> <div id="emailContact" ng-show="contactType=='email'"> <span>Email <input class="form-control input-sm" type="text" name="emailTheCustomer" id="emailTheCustomer" ng-model="$parent.emailTheCustomer" ng-required="$parent.contactType=='email' && accForm.emailTheCustomer.$viewValue === ''" maxlength="150"/></span> </div> </div> <input class="form-control" id="callTheCustomerRadio2" name="callTheCustomer" type="radio" value="No" ng-required="issueType=='IncidentDiv'" ng-model="$parent.callTheCustomer" ng-click="contactSelection('no')"/> <label for="callTheCustomerRadio2">No</label> </div> ``` Looks like this when Phone is selected: --------------------------------------- [![enter image description here](https://i.stack.imgur.com/dQ8Ib.png)](https://i.stack.imgur.com/dQ8Ib.png) and like this when email is selected: ------------------------------------- [![enter image description here](https://i.stack.imgur.com/oEW4T.png)](https://i.stack.imgur.com/oEW4T.png) I added this method to the Main controller: ------------------------------------------- ``` $scope.contactSelection = (function (contact) { if (contact=='none' ||contact=='email' ||contact=='phone'){ $scope.state = true; $scope.contactType = contact; if (contact=='phone'){$scope.phoneSelect = true;$scope.emailSelect = false;} if (contact=='email'){$scope.emailSelect = true;$scope.phoneSelect = false;} }else{ $scope.state = false; $scope.contactType = 'no'; $scope.emailTheCustomer = ''; $scope.callTheCustomerPhone = ''; $scope.phoneSelect = false; $scope.emailSelect = false; } }); ```
2019/05/24
[ "https://Stackoverflow.com/questions/56296546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552782/" ]
Avoid using `$parent` --------------------- Using `$parent` is problematic. If the template nests more than one directive which instantiates a child scope, the two-way binding will have a data hiding problem. It is better to bind ng-models to a property of an object in the controller scope. If `$parent` binds the `ng-model` to `$rootScope`, the controller $scope will not be able to set the model value. > > The model value is getting set, just the display does not change. > > > The model is getting set because the `ng-click` handler is setting it manually. If the binding is correct, the `ng-model` controller should set it automatically and there would be no need to set it manually. The `ngModelController` needs the proper binding to render to the HTML. Avoid using `$parent`. Define objects in the $scope for your controller, then reference a property of that object. See [Nuances of scope inheritance in AngularJS](https://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs). The below example binds correctly even though the `ng-if` directive adds a child scope: ```js angular.module("app",[]) .controller("ctrl",function($scope) { $scope.fd1={ sel1: null, yes1: false }; }) ``` ```html <script src="//unpkg.com/angular/angular.js"></script> <body ng-app="app" ng-controller="ctrl"> <form name="form1"> <input ng-model="fd1.yes1" type="checkbox" /> OK to Contact?<br> <div ng-if="fd1.yes1"> <input ng-model="fd1.sel1" type="radio" name="sel1" value="email" /> email <input ng-model="fd1.sel1" type="radio" name="sel1" value="phone" /> phone <br>{{fd1.sel1}} <div ng-show="fd1.sel1"> <input ng-model="fd1.info1"> <br> <button ng-click="fd1.sel1=null">Reset choice</button> </div> </div> </form> </body> ```
Couple things were in play here 1. I had to change the label-input tag order. ``` <div class="radio styled-radio" id="callTheCustomerDiv"> <input class="form-control" id="callTheCustomerRadio1" name="callTheCustomer" type="radio" value="Yes" ng-required="issueType=='IncidentDiv'" ng-model="callTheCustomer" ng-click="contactSelection(null)" /> <label for="callTheCustomerRadio1"> Yes</label> - Please indicate how the customer wants to be contacted.<br/> <div class="form-group" id="howToContactDiv" ng-if="customerContact.contactOptionShow" class="row fullWidth"> <div id="contactOptionsDiv" > <div id="contactOptionsSelectDiv" > <input class="form-control" id="phoneRadio" type="radio" name="contactSelection" ng-model="customerContact.contactSelection" value="phone" /> <label for="phoneRadio">Phone</label> &nbsp; &nbsp; &nbsp; &nbsp; <input class="form-control" id="emailRadio" type="radio" name="contactSelection" ng-model="customerContact.contactSelection" value="email" /> <label for="emailRadio">Email</label> <br/> </div> <div id="phoneContactDiv" ng-show="customerContact.contactSelection=='phone'"> <span>Phone <input class="form-control input-sm" type="text" name="callTheCustomerPhone" id="callTheCustomerPhone" ng-model="callTheCustomerPhone" ng-required="customerContact.contactSelection=='phone' && accForm.phoneNumber.$viewValue === ''" maxlength="20"/></span> </div> <br/> <div id="emailContactDiv" ng-show="customerContact.contactSelection=='email'"> <span>Email <input class="form-control input-sm" type="text" name="emailTheCustomer" id="emailTheCustomer" ng-model="emailTheCustomer" ng-required="customerContact.contactSelection=='email' && accForm.emailTheCustomer.$viewValue === ''" maxlength="150"/></span> </div> </div> </div> <input class="form-control" id="callTheCustomerRadio2" name="callTheCustomer" type="radio" value="No" ng-required="issueType=='IncidentDiv'" ng-model="callTheCustomer" ng-click="contactSelection('clear')" /> <label for="callTheCustomerRadio2">No</label> </div> ``` 2. I completely removed the $parent references and simplified the function by using the properties of the variable. modified the mainController method and variable to look like: ``` $scope.customerContact ={ contactOptionShow : false, contactSelection : null }; $scope.contactSelection = (function (contact) { if (contact != null && contact=='clear' ){ $scope.customerContact.contactOptionShow = false; $scope.customerContact.contactSelection = ''; $scope.emailTheCustomer = ''; $scope.callTheCustomerPhone = ''; }else{ $scope.customerContact.contactOptionShow = true; } }); ``` I think it reads better now as well.
28,508,008
I know I need to use free() in here somewhere, but I'm unsure where. ``` struct info{ char string1[30]; float float1; int int1; char string2[30]; }; struct info* build(){ FILE *data; int i, lines; lines=0; data=fopen("hw3.data","r"); struct info info; struct info *infoArr; infoArr = (struct info*)calloc(lines,sizeof(struct info)); for(i=0; i<2; i++){ //change not to 2 fscanf(data, "%s %f %d %s", info.string1, &info.float1, &info.int1, info.string2); strcpy(infoArr[i].string1, info.string1); infoArr[i].float1 = info.float1; infoArr[i].int1 = info.int1; strcpy(infoArr[i].string2, info.string2); } fclose(data); return infoArr; } void function1(){ int i; for(i=0; i<2; i++){ printf("%s %f %d %s\n", build()[i].string1, build()[i].float1, build()[i].int1, build()[i].string2); } } ``` I want to use it at the end of function1(), after the print statement, but will the context still be available there? I don't belief I can free(\*infoArr) at the end of build() as I need to access that array elsewhere, which is the whole point of build(). build() is intended to be used in multiple functions. If I use free() at the end of function1(), do I use free(infoArr) or free(build()) or something else entirely?
2015/02/13
[ "https://Stackoverflow.com/questions/28508008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3430647/" ]
Also, each of your arguments to `printf()` is working with a *different* structure, because you're calling `build()` repeatedly. You should call `build()` once before the loop, assign this to a variable, and then loop through the variable. ``` struct info* temp = build(); for (i = 0; i < 2; i++) { printf("%s %f %d %s\n", temp[i].string1, temp[i].float1, temp[i].int1, temp[i].string2); } free(temp); ```
You have to save the pointer returned by build(), and free it after the loop. It would be better style though to allocate the memory in function 1 before the loop, have build take a pointer and fill in it's data through that.
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
Simple Solution to return Distinct data for Object Array `this.studentOptions = this.students.filter((item, i, arr) => arr.findIndex((t) => t.Id=== item.Id) === i);`
You can try this like newbie way ``` let st=[]; Students.map((data)=>{ let isExist=!!st.find((data2)=>{ return data2.Id==data.Id}); if(!isExist) st.push(data); }); ```
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
Simple Solution to return Distinct data for Object Array `this.studentOptions = this.students.filter((item, i, arr) => arr.findIndex((t) => t.Id=== item.Id) === i);`
Array.from(new Set(yourArray.map((item: any) => item.id)))
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
This solution produces the result in the form you asked for. Objects need to be *stringified* before they get added to the `Set`, otherwise equal ones are not recognized (see <https://stackoverflow.com/a/29759699/2358409>). ``` const set = new Set(Students.map(s => JSON.stringify({ Id: s.Id, Name: s.Name }))); const identifiers = Array.from(set).map(i => JSON.parse(i)); ``` If you want to avoid *stringify*, you can do the following. ``` const set = new Set(Students.map(s => s.Id + ';' + s.Name)); const identifiers = Array.from(set).map(i => ({ Id: i.split(';')[0], Name: i.split(';')[1] })); ``` The same can be done in a cleaner way using `Map`. ``` const map = new Map(); Students.map(s => map.set(s.Id, { Id: s.Id, Name: s.Name })); const identifiers = Array.from(map.values()); ```
Using **rxjs**'s **map** and **distinct** operators we can achieve this. Please check the code below ```js var Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; const sourceObj = from(Students); const mappedObj=sourceObj.pipe(map((x)=>{return {Id: x.Id, Name:x.Name}})); const distictObj = mappedObj.pipe(distinct((x)=>x.Id && x.Name)); console.log(distictObj.subscribe(x=>console.log(x))); ``` Please check this [StackBlitz](https://stackblitz.com/edit/angular-mkduva). Thanks.
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
Since we're in the world of typescript, make use of the *types* provided by it. Create a class `Student`, this will be useful for easier management of your objects. ``` export class Student { Id: number; Name: string; Class?: string; Subject?: string; constructor(Id: number, Name: string) { this.Id = Id; this.Name = Name; } } ``` Create an array to hold the distinct objects: ``` distinctStud: Student[] = []; ``` Now you may: ``` from(this.Students) .pipe( map(std => new Student(std.Id, std.Name)), distinct(x => x.Id && x.Name) ) .subscribe(val => this.distinctStud.push(val)); ```
Using **rxjs**'s **map** and **distinct** operators we can achieve this. Please check the code below ```js var Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; const sourceObj = from(Students); const mappedObj=sourceObj.pipe(map((x)=>{return {Id: x.Id, Name:x.Name}})); const distictObj = mappedObj.pipe(distinct((x)=>x.Id && x.Name)); console.log(distictObj.subscribe(x=>console.log(x))); ``` Please check this [StackBlitz](https://stackblitz.com/edit/angular-mkduva). Thanks.
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
Simple Solution to return Distinct data for Object Array `this.studentOptions = this.students.filter((item, i, arr) => arr.findIndex((t) => t.Id=== item.Id) === i);`
Since we're in the world of typescript, make use of the *types* provided by it. Create a class `Student`, this will be useful for easier management of your objects. ``` export class Student { Id: number; Name: string; Class?: string; Subject?: string; constructor(Id: number, Name: string) { this.Id = Id; this.Name = Name; } } ``` Create an array to hold the distinct objects: ``` distinctStud: Student[] = []; ``` Now you may: ``` from(this.Students) .pipe( map(std => new Student(std.Id, std.Name)), distinct(x => x.Id && x.Name) ) .subscribe(val => this.distinctStud.push(val)); ```
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
This solution produces the result in the form you asked for. Objects need to be *stringified* before they get added to the `Set`, otherwise equal ones are not recognized (see <https://stackoverflow.com/a/29759699/2358409>). ``` const set = new Set(Students.map(s => JSON.stringify({ Id: s.Id, Name: s.Name }))); const identifiers = Array.from(set).map(i => JSON.parse(i)); ``` If you want to avoid *stringify*, you can do the following. ``` const set = new Set(Students.map(s => s.Id + ';' + s.Name)); const identifiers = Array.from(set).map(i => ({ Id: i.split(';')[0], Name: i.split(';')[1] })); ``` The same can be done in a cleaner way using `Map`. ``` const map = new Map(); Students.map(s => map.set(s.Id, { Id: s.Id, Name: s.Name })); const identifiers = Array.from(map.values()); ```
Array.from(new Set(yourArray.map((item: any) => item.id)))
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
Since we're in the world of typescript, make use of the *types* provided by it. Create a class `Student`, this will be useful for easier management of your objects. ``` export class Student { Id: number; Name: string; Class?: string; Subject?: string; constructor(Id: number, Name: string) { this.Id = Id; this.Name = Name; } } ``` Create an array to hold the distinct objects: ``` distinctStud: Student[] = []; ``` Now you may: ``` from(this.Students) .pipe( map(std => new Student(std.Id, std.Name)), distinct(x => x.Id && x.Name) ) .subscribe(val => this.distinctStud.push(val)); ```
You can try this like newbie way ``` let st=[]; Students.map((data)=>{ let isExist=!!st.find((data2)=>{ return data2.Id==data.Id}); if(!isExist) st.push(data); }); ```
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
Simple Solution to return Distinct data for Object Array `this.studentOptions = this.students.filter((item, i, arr) => arr.findIndex((t) => t.Id=== item.Id) === i);`
Using **rxjs**'s **map** and **distinct** operators we can achieve this. Please check the code below ```js var Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; const sourceObj = from(Students); const mappedObj=sourceObj.pipe(map((x)=>{return {Id: x.Id, Name:x.Name}})); const distictObj = mappedObj.pipe(distinct((x)=>x.Id && x.Name)); console.log(distictObj.subscribe(x=>console.log(x))); ``` Please check this [StackBlitz](https://stackblitz.com/edit/angular-mkduva). Thanks.
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
Since we're in the world of typescript, make use of the *types* provided by it. Create a class `Student`, this will be useful for easier management of your objects. ``` export class Student { Id: number; Name: string; Class?: string; Subject?: string; constructor(Id: number, Name: string) { this.Id = Id; this.Name = Name; } } ``` Create an array to hold the distinct objects: ``` distinctStud: Student[] = []; ``` Now you may: ``` from(this.Students) .pipe( map(std => new Student(std.Id, std.Name)), distinct(x => x.Id && x.Name) ) .subscribe(val => this.distinctStud.push(val)); ```
Array.from(new Set(yourArray.map((item: any) => item.id)))
56,712,634
I have a source list of objects of 4 properties with some duplicate values, want to select distinct objects of 2 properties without using a foreach loop. Source list: ``` let Students= [ {Id: 1, Name: 'A', Class: 'I', Subject: 'Math'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'Bengali'}, {Id: 1, Name: 'A', Class: 'I', Subject: 'Science'}, {Id: 2, Name: 'B', Class: 'II', Subject: 'English'} ]; ``` I want an output list like: ``` [ {Id: 1, Name: 'A'}, {Id: 2, Name: 'B'} ] ```
2019/06/22
[ "https://Stackoverflow.com/questions/56712634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8794761/" ]
Simple Solution to return Distinct data for Object Array `this.studentOptions = this.students.filter((item, i, arr) => arr.findIndex((t) => t.Id=== item.Id) === i);`
This solution produces the result in the form you asked for. Objects need to be *stringified* before they get added to the `Set`, otherwise equal ones are not recognized (see <https://stackoverflow.com/a/29759699/2358409>). ``` const set = new Set(Students.map(s => JSON.stringify({ Id: s.Id, Name: s.Name }))); const identifiers = Array.from(set).map(i => JSON.parse(i)); ``` If you want to avoid *stringify*, you can do the following. ``` const set = new Set(Students.map(s => s.Id + ';' + s.Name)); const identifiers = Array.from(set).map(i => ({ Id: i.split(';')[0], Name: i.split(';')[1] })); ``` The same can be done in a cleaner way using `Map`. ``` const map = new Map(); Students.map(s => map.set(s.Id, { Id: s.Id, Name: s.Name })); const identifiers = Array.from(map.values()); ```
27,389,955
I have an issue with a show of a parent div at onclick. As here: ``` $('#click').click(function() { $(this).parent().closest('div').slideToggle("fast"); }); http://jsfiddle.net/bk1hLoyb/ ``` I need to show the .show div at the li click, and i need to hide the first when i click another. Someone know's a method? Thanks so much
2014/12/09
[ "https://Stackoverflow.com/questions/27389955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3442656/" ]
Id's should be unique on the page. ``` $('.click').click(function() { $('.show').hide(); $(this).find('.show').slideToggle("fast"); }); ``` <http://jsfiddle.net/bk1hLoyb/11/>
First Id's must be unique so change it for: ``` <li class="click"> <a href="#">Bye</a> <div class="show">Hey</div> </li> ``` and the code change it for: ``` $('.click').click(function() { $(this).find('div').slideToggle("fast"); }); ``` [LIVE DEMO](http://jsfiddle.net/j8jhag87/)
27,389,955
I have an issue with a show of a parent div at onclick. As here: ``` $('#click').click(function() { $(this).parent().closest('div').slideToggle("fast"); }); http://jsfiddle.net/bk1hLoyb/ ``` I need to show the .show div at the li click, and i need to hide the first when i click another. Someone know's a method? Thanks so much
2014/12/09
[ "https://Stackoverflow.com/questions/27389955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3442656/" ]
Id's should be unique on the page. ``` $('.click').click(function() { $('.show').hide(); $(this).find('.show').slideToggle("fast"); }); ``` <http://jsfiddle.net/bk1hLoyb/11/>
Some suggestions: * remove all duplicate IDs * if you must use a selector on the `li` elements, use a class * `.show` is a child of the `li` that's clicked, so there's no need to use `.parent()` or `.closest()`. Code: ``` $('.click').click(function() { $('.show', this).slideToggle("fast"); }); ``` [**DEMO**](http://jsfiddle.net/bk1hLoyb/12/) **BONUS** * [`$(elm).find('.selector')` is equivalent to `$('.selector', elm)`](http://api.jquery.com/jquery/) * [Also written as `jQuery( selector [, context ] )`](http://api.jquery.com/jquery/) * [When `context` is not specified, it is assumed to be `document`](http://api.jquery.com/jquery/) * [Thus **$(elm)** is equivalent to **$(elm, document)**](http://api.jquery.com/jquery/)
27,389,955
I have an issue with a show of a parent div at onclick. As here: ``` $('#click').click(function() { $(this).parent().closest('div').slideToggle("fast"); }); http://jsfiddle.net/bk1hLoyb/ ``` I need to show the .show div at the li click, and i need to hide the first when i click another. Someone know's a method? Thanks so much
2014/12/09
[ "https://Stackoverflow.com/questions/27389955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3442656/" ]
Id's should be unique on the page. ``` $('.click').click(function() { $('.show').hide(); $(this).find('.show').slideToggle("fast"); }); ``` <http://jsfiddle.net/bk1hLoyb/11/>
On your "li"s change the id to a class so you can reference multiple divs. Then on the script looks like this: ``` $('.click a').click(function() { var item = $(this); $(this).parent().siblings().find('.show').slideUp(400,function(){ item.parent().find('.show').slideDown(400); }); }); ``` See it working on your fiddle (sorry for updating without forking)
22,113,558
I keep getting this error when I try to add an object to a retrieved `NSMutableArray`. ``` Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object' ``` Retrieve: ``` NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSMutableArray *arrayOfTitles = [userDefaults objectForKey:@"mainArraySaveData"]; NSMutableArray *arrayOfSubjects = [userDefaults objectForKey:@"subjectArraySaveData"]; NSMutableArray *arrayOfDates = [userDefaults objectForKey:@"dateArraySaveData"]; _mutableArray=arrayOfTitles; _subjectArray=arrayOfSubjects; _dateArray=arrayOfDates; [_tableView reloadData]; ``` Save: ``` NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; _mutableArray = [[NSMutableArray alloc] initWithArray:[userDefaults objectForKey:@"mainArraySaveData"]]; [userDefaults setObject:_mutableArray forKey:@"mainArraySaveData"]; [userDefaults synchronize]; _dateArray = [[NSMutableArray alloc] initWithArray: [userDefaults objectForKey:@"dateArraySaveData"]]; [userDefaults setObject:_dateArray forKey:@"dateArraySaveData"]; [userDefaults synchronize]; _subjectArray = [[NSMutableArray alloc] initWithArray: [userDefaults objectForKey:@"subjectArraySaveData"]]; [userDefaults setObject:_subjectArray forKey:@"subjectArraySaveData"]; [userDefaults synchronize]; ``` I'm confused as I thought this was designed to return an `NSMutableArray`, but it says not - `NSArray`. What's my issue?? Thanks, SebOH
2014/03/01
[ "https://Stackoverflow.com/questions/22113558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/826671/" ]
> > I'm confused as I thought this was designed to return an `NSMutableArray`, but it says not - `NSArray`. What's my issue? > > > The documentation of the `NSUserDefaults` talks specifically about this issue in the "special considerations" section of the `objectForKey:` method: > > **Special Considerations** > > > The returned object is immutable, even if the value you originally set was mutable. > > > Fixing this problem is easy - use `mutableCopy:`, `initWithArray:` or `arrayWithArray:` method to make mutable copies: ``` _mutableArray=[arrayOfTitles mutableCopy]; // You can do this... _subjectArray=[NSMutableArray arrayWithArray:arrayOfSubjects]; // ...or this _dateArray=[[NSMutableArray alloc] initWithArray:arrayOfDates]; // ...or this. ```
User defaults returns immutable objects so you need to call `mutableCopy` on each before you can modify them. When you define a variable as `NSMutableArray *` it is your responsibility to ensure that the instance you store there is of the correct type. The compiler will only tell you that you're wrong if it can tell. In this case the method returns `id` as you are requesting 'whatever object type exists for this key' from user defaults.
129,035
The implementation below works, but I'm wondering if there's a modern C++ alternative. For example: * Should I replace the raw `new` with a braced initializer? * Should I replace the `Node*` with a `shared_ptr`? Let me know if you see any other things I could improve. I know I could also use a class, but I'd like to understand how to do this with `struct`. ``` #include <iostream> struct Node { int data; Node* next; }; void insert(Node*& head, int data) { Node* new_node = new Node; new_node->data = data; new_node->next = head; head = new_node; } void print_list(Node* list) { Node* p {list}; std::cout << "Printing list: " << std::endl; if (p) { std::cout << p->data; p = p->next; while(p) { std::cout << " -> " << p->data; p = p->next; } std::cout << std::endl; } } int main(int argc, char* argv[]) { Node* my_list {}; insert(my_list, 10); insert(my_list, 20); print_list(my_list); } // Printing list: // 20 -> 10 ```
2016/05/22
[ "https://codereview.stackexchange.com/questions/129035", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/104815/" ]
First, note that the only real difference between a `struct` and a `class` is the default accessibility: in a `class` everything is `private` by default, and in a `struct` everything is `public` by default. That's literally the *only* difference between the two. In any case, some of your code can be simplified somewhat. For example, your `insert` can be reduced to just this: ``` void insert(Node*& head, int data) { head = new Node{data, head}; } ``` It's usually better to initialize rather than construct something uninitialized, and then assign a value anyway, so this is sort of a double-win. I'd also prefer to use a `for` loop to print the list, and just a new-line where you want to print a new-line: ``` void print_list(Node* list) { Node* p {list}; std::cout << "Printing list:\n"; if (p) { std::cout << p->data; for (p=p->next; p != nullptr; p=p->next) std::cout << " -> " << p->data; } std::cout << "\n"; } ``` In this case, I'd restructure the code a bit to treat the list being non-null as a pre-condition to `print_list` and enforce that up-front: ``` void print_list(Node* list) { if (list == nullptr) return; std::cout << "Printing list:\n"; std::cout << list->data; for (Node *p{list->next}; p != nullptr; p=p->next) std::cout << " -> " << p->data; std::cout << "\n"; } ``` The next steps I can see would involve the sort of re-vamping you don't seem to want right now--turning the linked list into a full-blown class of its own that supports iterators and such. This does have a tremendous advantage though: right now, your linked list only supports inserting items, then printing an entire linked list. If anybody wants to do anything else, they need to implement it entirely on their own, and know all about the internal details of the linked list to do it. Along with that, you'd probably want to make it a generic container, so you can use it to store any data type, not just `int`. This way, you can immediately support essentially all code that knows how to work with a collection that supports (in this case) forward iterators. You'd probably just eliminate `print_list` entirely, as it becomes just an application of `std::copy` from a list to (for example) an [`infix_iterator`](https://codereview.stackexchange.com/q/13176/489). This is (IMO) much cleaner in general. In particular, it separates concerns much more cleanly: the linked list can concentrate solely on linked-list "things", and not worry about things like I/O as it does now.
Design ------ I would note you have not made a linked list, but a chain of Node(s). This may seem to be the same thing but I would see this as different as a linked list would encapsulate and hide its internal structure with a class and provide methods to access the data. So you have: ``` void insert(Node*& head, int data); void print_list(Node* list) ``` I would have done this: ``` class LinkedList { public: insert(int data); print(); }; // Usage in main would then be: int main() { LinkedList my_list; my_list.insert(10); my_list.insert(20); my_list.print(); } ``` Notice there are no pointers anywhere to be seen for the user. So the user of the class does not need to worry about memory management at all when using the list. Your design on the other hand leaks the list at the end. Questions: ---------- > > Should I replace the raw new with a braced initializer? > > > I would advise it. It avoids a few corner cases where things can go wrong. > > Should I replace the Node\* with a shared\_ptr? > > > No. Two reasons. One: `std::unique_ptr` should be your first smart pointer you consider. Two: this is a container. There are two types of memory management structures. 1. Smart Pointers 2. Containers. Both have to deal with pointers internally (just not expose them to the client). But implementing a container with a smart pointer is potentially inefficient (it can be done). It is usual to do the memory management internally. Code Review. ------------ ### Don't expose implementation details This should be a private member of your linked list. ``` struct Node { int data; Node* next; }; ``` Allowing users to see the structure allows them to build code around this structure which locks you into maintaining this interface. So you can now no longer improve your linked list. Also exposing a RAW pointer leads to memory management issues. Is this an owning RAW pointer or not? i.e. who is responsible for calling delete? Sure you can write it like this: ``` void insert(Node*& head, int data) { Node* new_node = new Node; new_node->data = data; new_node->next = head; head = new_node; } ``` But that seems overly verbose. ``` void insert(Node*& head, int data) { head = new Node{data, head}; } ``` Your print only prints to `std::cout`: ``` void print_list(Node* list) { Node* p {list}; std::cout << "Printing list: " << std::endl; if (p) { std::cout << p->data; p = p->next; while(p) { std::cout << " -> " << p->data; p = p->next; } std::cout << std::endl; } } ``` It would be nice if it printed to any stream. Then you can print it to a string or a file. Even if the default is `std::cout`. ``` void print_list(Node* list, std::ostream& str = std::cout) ``` Also, the standard way to print things in C++ is to use `operator<<`. So it would be nice if you wrote the appropriate operator. ``` std::ostream& operator<<(std::ostream& s, Node* node) { print_list(node, s); return s; } ``` Const correctness ----------------- A big push in C++ is const correctness. This is marking parameters and members as const if they are not mutated/mutating. In the above code the print is not supposed to mutate the list. So it might be nice to mark the nodes as `const`.