qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
1,245,376
Hey Exchange community, We have finite-dimensional vector spaces $V$ and $W$ with ordered bases $B$ and $A$ respectively. Is it true/false that $L(V,W)=L(W,V)$? Just wondering if someone could articulate what the difference is between the two notations. Having someone write it down as if they were verbally explaining it to someone would really help. Thanks!
2015/04/21
[ "https://math.stackexchange.com/questions/1245376", "https://math.stackexchange.com", "https://math.stackexchange.com/users/233092/" ]
The symbols $\mathcal{L}(V,W)$ indicates the linear transformations from vector space $V$ into vector space $W$, and the analogous statement is made for $\mathcal{L}(W,V)$. If $V$ and $W$ are not the same space (e.g. isomorphic) then you don't in general have the same maps going from $V$ to $W$ as you do from $W$ to $V$. For instance, if $V$ were $2$-dimensional and $W$ were $3$-dimensional then the linear maps in $\mathcal{L}(V,W)$ could be represented by $3\times 2$ matrices, but the maps in $\mathcal{L}(W,V)$ would be $2\times 3$ matrices.
35,527,163
I created a simple Jekyll blog by following the instructions in the Quick-start guide in <http://jekyllrb.com/docs/quickstart/>. I changed the blog a little bit to suit my needs and was able to successfully implement these changes and view them locally. But, as soon as I deployed the blog on Github Pages, I get this <http://palpen.github.io/palpen_articles/> which is nothing like the local version of the site. What did I do wrong? I'm new to all of this, so forgive me if my mistakes are trivial. The GitHub repository for the blog lives here: <https://github.com/palpen/palpen_articles> Thank you
2016/02/20
[ "https://Stackoverflow.com/questions/35527163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3649966/" ]
By going off the assumption that you mean the styling is off. I opened the dev console in your website and noticed there was this error ``` http://palpen.github.io/palpen_articles/palpen_articles/css/main.css Failed to load resource: the server responded with a status of 404 (Not Found) ``` Notice that it's attempting to access a nested deep resource with your site host. The culprit is this line ``` <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}"> ``` <https://github.com/palpen/palpen_articles/blob/gh-pages/_includes/head.html#L9> When you prepend the base url for the site it creates a link ``` <link rel="stylesheet" href="palpen_articles/css/main.css"> ``` If you prepend the `/` to that href your site style actually looks better. Note that there are a couple of other links which are broken as well because of this reason. The issue is that your `_config.yml` file contains a bad `baseurl`. The `baseurl` should be `/palpen_articles` instead of just `palpen_articles`.
676,357
My Ubuntu Linux server has an mdadm array (RAID 5) with four 2TB SATA disks that keeps "loosing" two disks from time to time. Rebooting and re-assembling the arrays has worked out fine up until now. Hardware is a Dell PowerEdge T20 with an Exsys EX-3400 card that provides four additional SATA ports. Two of the fours disks in the RAID array are connected to the Exsys card, and the remaining two disks are connected to the onboard SATA ports (the remaining onboard SATA ports are in use for other disks). I checked for disk faults using smart utilities, they all seem good. The disks that are being "lost" from the RAID are the two connected to the add-on SATA controller, so I replaced the add-on card with another one (didn't help, same symptoms). I replaced the SATA cables of the relevant disks (didn't help, same symptoms). Does anyone have an idea what the source for these issues might be, and what else I could test?
2015/03/18
[ "https://serverfault.com/questions/676357", "https://serverfault.com", "https://serverfault.com/users/276935/" ]
You have these three commands ``` mkdir test_dir test_dir1 test_dir2 test_dir3 touch file1 file2 file3 cp -v file* test_dir*/ ``` Assuming no other files or directories in `.` before the example is started, the wildcards in that last line get expanded thus: ``` cp -v file1 file2 file3 test_dir/ test_dir1/ test_dir2/ test_dir3/ ``` (You can see this by changing `cp` to `echo cp` and observing the result.) What you didn't tell us is the diagnostic messages produced by `cp -v`, which show what it is trying to do, i.e. copy every item on the command line but the last into the last item, which must therefore be a directory: ``` ‘file1’ -> ‘test_dir3/file1’ ‘file2’ -> ‘test_dir3/file2’ ‘file3’ -> ‘test_dir3/file3’ cp: omitting directory ‘test_dir/’ cp: omitting directory ‘test_dir1/’ cp: omitting directory ‘test_dir2/’ ```
571,389
I have the following MWE of a table: ``` \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{tabularx, multirow, booktabs} \usepackage{amsmath} \begin{document} \begin{table}[t] \begin{tabularx}{\linewidth}{l@{\extracolsep{\fill}}*1c@{}*1c@{}*1c@{}*1c@{}*1c@{}*1c@{}*1c@{}*1c@{}} \toprule &\multicolumn{2}{c}{col1} &\multicolumn{2}{c}{col2} &\multicolumn{2}{c}{col3} &\multicolumn{2}{c}{col4}\\ \cmidrule{2-3} \cmidrule{4-5} \cmidrule{6-7} \cmidrule{8-9} &$a$ &$b$ &$a$ &$b$ &$a$ &$b$ &$a$ &$b$ \\\midrule \\ [-2ex] title& & & & & & & &\\ type &$\underset{(9.21)}{0.26^{*}}$ &$\underset{(8.45)}{2.34^{**}}$ &$\underset{(-9.43)}{-1.75}$ &$\underset{(-2.67)}{-2.43^{**}}$ &$\underset{(-2.13)}{-3.17}$ &$\underset{(-4.26)}{-6.58}^{***}$ &$\underset{(0.38)}{0.14}$ &$\underset{(4.12)}{5.32}$\\ \end{tabularx} \end{table} \end{document} ``` This produces the table as desired, where each entry contains two values: One above and one below in paranthesis. However, the issue is that the two values are not aligned as shown below in the blue circles. Ideally, I'd like to align them by the dots (.) Is that possible? Maybe use some quick-and-dirty trick involving `hphantom` or the like? [![enter image description here](https://i.stack.imgur.com/CzlLa.png)](https://i.stack.imgur.com/CzlLa.png)
2020/11/18
[ "https://tex.stackexchange.com/questions/571389", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/183675/" ]
You can use the special `discard` layer after you've set it up with ``` \pgfdeclarelayer{discard} ``` When it is declared as the layer to be used with `pgfonlayer`, the content will be placed on that layer but since you don't set it with ``` \pgfsetlayers{discard, main} ``` it won't show up in the picture. (Only `discard` works that way, every other name needs to be specified in `\pgfsetlayers`.) With that setup you can just do ``` \begin{pgfonlayer}{discard} \pic [local bounding box = Subtikz] {subtikz}; \end{pgfonlayer} ``` This obviously won't work if you want to use the pic as part of another path that should show up but [that can be arranged](https://tex.stackexchange.com/a/668356) as well (especially if you don't use any foreground or background code in your pic). --- I've added a simple `\pgfshowdiscardlayeranyway` command that uses that layer anyway which may be useful for debugging purposes. Since that layer is not setip with `\pgfsetlayers` it will accumulate and will not be emptied at the start of the next picture which I show off in the code below since I'm just using `\pgfshowdiscardlayeranyway` in a second TikZ picture which then contains your original pic. This had advantages but maybe it's not desirable, for this I'll add a `discard discard layer` key that can be used as an option to a `tikzpicture` (or a `scope`) to globally empty out the layer. It might be worth to do ``` \tikzset{every picture/.append style={discard discard layer}} ``` to not drag around that layer through out your whole document. --- As an additional note, the way it is setup now, your discarded pic still contributes to the bounding box in the original picture but *not* if you use the `\pgfshowdiscardlayeranyway` in another picture. (This isn't noticeable in the example below because I added a grid to show the positions better.) Code ---- ``` \documentclass[tikz]{standalone} \usetikzlibrary{calc} \pgfdeclarelayer{discard} % ← declare discard layer \makeatletter \tikzset{ discard discard layer/.style={ execute at end scope=% \global\let\pgf@layerbox@discard\pgfutil@voidb@x}} \newcommand*\pgfshowdiscardlayeranyway{\box\pgf@layerbox@discard} \makeatother \begin{document} \begin{tikzpicture}[ % discard discard layer, subtikz/.pic={\draw (0, 0) -- (1, 0);}] \draw[help lines] (-.5,-.5) grid (4.5,.5); \begin{pgfonlayer}{discard} % ← place on discard layer \pic [local bounding box = Subtikz] {subtikz}; \end{pgfonlayer} % Calculate position depending on other input. \path let \p1 = (Subtikz.north east), \p2 = (1, 2), \p3 = (3, 4) in coordinate (NorthEast) at ({max(\x1, \x2, \x3)}, \y1); % Draw pic taking into account other input. \pic at (NorthEast) {subtikz}; %\pgfshowdiscardlayeranyway % ← show layer anyway \end{tikzpicture} \begin{tikzpicture} \draw[help lines] (-.5,-.5) grid (4.5,.5); \pgfshowdiscardlayeranyway \end{tikzpicture} \end{document} ``` Outpu ----- [![enter image description here](https://i.stack.imgur.com/Xbl2P.png)](https://i.stack.imgur.com/Xbl2P.png) [![enter image description here](https://i.stack.imgur.com/3KTBv.png)](https://i.stack.imgur.com/3KTBv.png)
9,898,773
I realize there are similar posts to this out there, but rest assured, this isn't a duplicate post! I have a site on a godaddy server. I DO NOT have access to the outside of the root of my server (everything is public). I have a file delete.php that needs to run on CRON, and only by CRON. The file should not execute manually at all by anyone for any reason. Given the above, I am trying to secure my file as much as possible so let'smake this an experiment in security. So far, I have the following with the goal of making the file as secure as possible: ``` <?php $isCLI = ( php_sapi_name() == 'cli' ); if (!$isCLI) { die("cannot run!"); } else { if(!isset($_SERVER['REQUEST_METHOD'])){ // Do the task here }else{ die("cannot run!"); } } ?> ``` So, is this logically secure? How can it be made even more secure? godaddy can only allow me to set a date/time to run a file, nothing more.
2012/03/27
[ "https://Stackoverflow.com/questions/9898773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/910737/" ]
Checking for the `cli` SAPI is sufficient; a user executing it via apache (be it mod\_php or fastcgi or cgi) will never cause PHP to be called through the CLI sapi. You can get rid of the ugly `else {}` around your real code though; if you `exit;` at the end of the *then* block there is no need for an *else* block. However, not putting that kind of script in the document root at all would be much cleaner. If that's not possible, also consider using `.htaccess`: ``` Order deny,allow Deny from all ``` If the files are in a folder which shouldn't be locked down completely, wrap those lines in `<Files whatever.php>...</Files>`
41,346,681
i have a set of code that i copied from someone on youtube and i completely understand and there is some unused logic in there but basically at the moment all it is meant to do is grab the rocket.show function and draw a rectangle and i cannot for the life of me work out why it is not doing so. it is throwing out no errors and drawing the background, i can draw the rectangle if i just put the code for "rect..." in the draw function therefore there is a problem with the way that i am referring to the function but i cannot for the life of me work it out, the code is below, any help would be appreciated. ``` function setup() { createCanvas(800, 600); background(0); rocket = new rocket(); } function draw() { rocket.update; rocket.show; } function rocket() { this.pos = createVector(); this.vel = createVector(); this.acc = createVector(); this.applyforce = function (force) { this.acc.add(force); } this.update = function () { this.vel.add(this.acc); this.pos.add(this.vel); this.acc.mult(0); } this.show = function () { push(); translate(this.pos.x, this.pos.y); rotate(this.vel.heading()); rectMode(CENTER); rect(0, 0, 10, 50); pop(); } } ``` edit: I worked it out, sorry for taking up needless posting space
2016/12/27
[ "https://Stackoverflow.com/questions/41346681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6308045/" ]
You should check for the *first* property that might not exist: so don't check the `coconut.color` property before you are sure that `coconut` exists. If the property you check for should be an object (which is your case) then you can do so with the `!` operator: ``` if (!myObj.fruits.coconut) myObj.fruits.coconut = { color: 'brown' }; ```
6,658
В чем их отличие? Согласно некоторым источникам "просветительская" - принадлежащая тому, кто просвещает, - просветителю. "Просветительная" - направленная на просвещение. Путаница, да и только. Например, просветительная работа для родителей. Думаю, этот вариант верен.
2012/07/19
[ "https://rus.stackexchange.com/questions/6658", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/653/" ]
> > > > > > > > > > > > Согласно некоторым источникам "просветительская" - принадлежащая тому, кто просвещает, - просветителю. "Просветительная" - направленная на просвещение. > > > > > > > > > > > > > > > > > > Всё так. Никакой путаницы. Другое дело, что во многих случаях подходят оба варианта. "Просветительская" ведь не только принадлежащая просветителю, а ещё и свойсвенная ему, этот вариант более частый. "Просветительская деятельность" - деятельность просветителя. > > > > > > > > > > > > Просветительная работа для родителей > > > > > > > > > > > > > > > > > > > > > > > > О чем речь? Очень может быть, что и "просветительская".
46,808,446
I'm working on a responsive website. I have tried EVERYTHING and my footer won't stay down. It's because I used float:left. I don't want it to be fixed, i want it only to appear when i scroll to the bottom of the page. This is my code: EDIT: ok so i took position:absolute out and now it works on the pages it didn't before. but on the pages where i didn't use float:left it doesn't work anymore. ```css footer { position: absolute; left: 0; bottom: 0; width: 100%; height: 1.2em; background-color: #24478f; color: black; text-align: center; font-family: Calibri; font-size: 4vw; max-width: 100%; clear: both; } #container figure { width: 100%; float: left; display: block; overflow: hidden; } ... @media only screen and (min-device-width: 1000px) { #container figure { width: 33%; display: block; overflow: hidden; } } ``` ```html <section id="container"> <figure> <a href="Portfolio.html#applications"> <img src="../imgs/74599-200.png"> </a> <figcaption>Multimedia Applications</figcaption> </figure> <figure> <a href="Portfolio.html#retrieval"> <img src="../imgs/info1600.png"> </a> <figcaption>Information Retrieval</figcaption> </figure> <figure> <a href="Portfolio.html#games"> <img src="../imgs/3281-200.png"> </a> <figcaption>Computer Games</figcaption> </figure> </section> <footer> <p> Infia Abelha</p> </footer> ```
2017/10/18
[ "https://Stackoverflow.com/questions/46808446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7906130/" ]
`random.randint` only takes two arguments, a start and an end. The third argument mentioned by Python is `self`, which is done automatically. To pick a number between 1 and 3, just do `random.randint(1,3)`. Those `if` statements don't make any sense, by the way; they should look something like: ``` if userInput == "paper": # send discord messages ```
52,914,982
I'm trying to implement my own TabBar design in flutter. I was able to get a pretty good result. However, when I tap another tab to change the tab, there is a highlight create by default as shown in the image [here](https://i.stack.imgur.com/XBwMg.png). I'm wondering if there is any way I can get rid of the square highlight on tapped. I've been looking around for like almost a day not and did not find any solution. If anyone have any solution please let me know. Thanks. Edited: as CopsOnRoad suggestion I wrapped the TabBar in the Container and set the color to `Colors.transparent`, but it does not really disappear so I tried to set the color to `Theme.of(context).canvasColor` for now. ``` Container( color: Theme.of(context).canvasColor, child: TabBar( isScrollable: true, indicator: ShapeDecoration( color: Color(0xFFE6E6E6), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(99.0) ) ), tabs: List<Widget>.generate( categories.length, (index) => Tab( child: Text( categories[index], style: TextStyle( fontFamily: 'Hiragino Sans', fontWeight: FontWeight.bold, fontSize: 18.0, color: Color(0xFF4D4D4D), ), ), ) ), ) ) ```
2018/10/21
[ "https://Stackoverflow.com/questions/52914982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4914834/" ]
That's the ripple effect. You can remove it by wrapping it in a `Container` and giving transparent color to it.
22,329,950
I want to share multi images with caption on Facebook using Intent. I tried some ways but it doesn't work. I can share photos but not the caption. Can you help me, please? Thanks!!! My share function ``` private void share(String nameApp, ArrayList<String> imagePath, String text) { try { List<Intent> targetedShareIntents = new ArrayList<Intent>(); Intent share = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE); share.setType("image/*"); List<ResolveInfo> resInfo = getActivity().getPackageManager().queryIntentActivities(share, 0); if (!resInfo.isEmpty()) { for (ResolveInfo info : resInfo) { Intent targetedShare = new Intent( android.content.Intent.ACTION_SEND_MULTIPLE); targetedShare.setType("image/*"); if (info.activityInfo.packageName.toLowerCase().contains(nameApp) || info.activityInfo.name.toLowerCase().contains(nameApp)) { ArrayList<Uri> uris = new ArrayList<Uri>(); for (int i = 0; i < nImageCount; i++){ uris.add(Uri.parse("file://" + imagePath.get(i))); } targetedShare.putExtra(Intent.EXTRA_TITLE, text); targetedShare.putExtra(Intent.EXTRA_TEXT, text); targetedShare.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); targetedShare.setPackage(info.activityInfo.packageName); targetedShareIntents.add(targetedShare); } } Intent chooserIntent = Intent.createChooser( targetedShareIntents.remove(0), "Select app to share"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[] {})); startActivity(chooserIntent); } } catch (Exception e) { } } ```
2014/03/11
[ "https://Stackoverflow.com/questions/22329950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2714606/" ]
``` SELECT Car, Shop, Prices FROM `Car List` WHERE Car = 'Mercedes' ``` Depending on your DB engine you need to escape tables names containing spaces differently.
24,366,351
I have a string that contains an exe full path and exe name like so: ``` mainExePath = "c:\Folder1\Folder2\MyProgram.exe" ``` I want to get jus the path like so: ``` "c:\Folder1\Folder2\" ``` I have tried this: ``` string mainPath = System.IO.Path.GetFullPath(mainExePath); ``` but this returned the same string. How can I do this?
2014/06/23
[ "https://Stackoverflow.com/questions/24366351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2339664/" ]
Use `Path.GetDirectoryName(mainExePath)`
29,094
How does one set a flash message in the templates? I can't find any documentation about this, only for plugins or getting the message. My use-case is, I am checking if a user is allowed to access a certain page and if they cannot I want to set a flash message, then redirect them to another page. I prefer this than to keep them on the same page and is if else logic to show the message or the rest of the page. Thanks
2019/01/12
[ "https://craftcms.stackexchange.com/questions/29094", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/4993/" ]
You can set [flash messages](https://www.yiiframework.com/doc/guide/2.0/en/runtime-sessions-cookies#flash-data) using [yii\web\Session::setFlash()](https://www.yiiframework.com/doc/api/2.0/yii-web-session#setFlash()-detail). The `session` component is available to templates via `craft.app.session`. ``` {% do craft.app.session.setFlash('error', 'You’re not allowed to go there.') %} ``` For convenience, Craft’s [SessionBehavior](https://docs.craftcms.com/api/v3/craft-behaviors-sessionbehavior.html) class adds shortcut [setError()](https://docs.craftcms.com/api/v3/craft-behaviors-sessionbehavior.html#method-seterror) and [setNotice()](https://docs.craftcms.com/api/v3/craft-behaviors-sessionbehavior.html#method-setnotice) methods to the `session` component as well. ``` {% do craft.app.session.setError('You’re not allowed to go there.') %} ``` You can place that right before your `{% redirect %}` tag.
212,569
Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question. What is the difference between > > I wanted to come to your party but I couldn't > > > I would have liked to come to your party but I couldn't. > > >
2019/05/28
[ "https://ell.stackexchange.com/questions/212569", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/96204/" ]
I've answered essentially the same question over at english.stackexchange.com: [Why is “our today's meeting” wrong?](https://english.stackexchange.com/questions/251561/why-is-our-todays-meeting-wrong) Usually, a noun phrase in English must have exactly one determiner: you can say "I drove this car" or "I drove my car", but not "I drove car" or "I drove this my car". Certain nouns (such as plural nouns and proper nouns) don't need determiners: "I love bees", "I love milk", "I love Paris", "I love biology". But it's never acceptable for a noun phrase to have more than one determiner (with possible extremely rare exceptions). "Our last week's meeting" is unacceptable because the noun phrase "meeting" has two determiners, "our" and "last week's". It would also be unacceptable to say "the today's meeting" or "our the meeting". Here are some phrases which may *seem* to have multiple determiners, but don't actually: * your father's home - this noun phrase has only one determiner, namely, "your father's". Meanwhile, the phrase "your father" is also a noun phrase which only has one determiner, namely, "your". * the brass men's wristwatches - the determiner of this noun phrase is "the", and "brass" and "men's" are adjectives. * an old people's home - the determiner of this noun phrase is "an". The phrase "old people's home" is an idiom which acts as a simple noun, even though it looks like it contains a determiner.
73,829,087
I've created a control and it has a bindable property, but when I try to set its value, it does not set, when I check its setter, it's not getting hit while debugging, not sure what am I doing wrong. ``` public decimal MetricValue { get => (decimal)GetValue(MetricValueProperty); set => SetValue(MetricValueProperty, value); } public static readonly BindableProperty MetricValueProperty = BindableProperty.Create( propertyName: nameof(MetricValue), returnType: typeof(decimal), declaringType: typeof(HeightSelection), defaultBindingMode: BindingMode.TwoWay, propertyChanged: MetricValuePropertyChanged); ``` I also have a propertychanged, which is not getting raised ``` <controls:customControl CurrentSystemOfMeasure="{Binding CurrentSystemOfMeasure}" MetricValue="{Binding CurrentHeight}" TextAlignment="Start" OnHeightSelectedCommand="{Binding HeightSelectionCommand}" IsValid="True" /> ``` any inputs would be helpful
2022/09/23
[ "https://Stackoverflow.com/questions/73829087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6155965/" ]
``` LiteDB `5.x` is .NET Framework 4.5 and .NET Standard 2.0 compatible. You can work with LiteDB in any target framework that .NE TStantard 2.0 is compatible, like: - .NET 5 - .NET Core 2+ - .NET Framework 4.6.1 - Mono 5.4 - Xamarin.iOS 10.14 - Xamarin.Mac 3.8 - Xamarin.Android 8 - UWP 10.0.16299 - Unity 2018.1 https://learn.microsoft.com/pt-br/dotnet/standard/net-standard ```
6,413,842
> > **Possible Duplicate:** > > [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net) > > > I understand using the `@` symbol is like an escape character for a string. However, I have the following line as a path to store a file to a mapped network drive: `String location = @"\\192.168.2.10\datastore\\" + id + "\\";` The above works fine but now I would like to get a string from the command line so I have done this: `String location = @args[0] + id + "\\";` The above doesn't work and it seems my slashes aren't ignored. This my command: `MyProgram.exe "\\192.168.2.10\datastore\\"` How can I get the effect of the `@` symbol back?
2011/06/20
[ "https://Stackoverflow.com/questions/6413842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51649/" ]
It is used for two things: * create "verbatim" strings (ignores the escape character): `string path = @"C:\Windows"` * escape language keywords to use them as identifiers: `string @class = "foo"` In your case you need to do this: ``` String location = args[0] + id + @"\\"; ```
6,625,598
My iPhone app badly leaks when flipping back and forth between a main uiviewcontroller and a help uiviewcontroller . Here is the source of the main view, followed by source of the help view. MAIN VIEW - FLIP TO HELP..................... ``` // Changes from operational view to Help view. - (IBAction)showHelp:(id)sender { // End trial mode: self.stop_trial_if_started; self.rename_trial_if_edited; // Switch to trial help: help_view_context = 0; HelpView *controller = [[HelpView alloc] initWithNibName:@"HelpView" bundle:nil]; controller.delegate = self; controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentModalViewController:controller animated:YES]; [controller release]; } ``` HELP VIEW - INIT............................. ``` - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; help_scroll.editable = FALSE; return; } ``` HELP - RETURN TO MAIN VIEW......................... ``` // User clicked the button to return to operational view: - (IBAction)done:(id)sender { NSLog(@"help- done"); if( help_view_context == 0 ) { [self.delegate trial_help_DidFinish:self]; }else{ [self.delegate file_help_DidFinish:self]; } } ``` MAIN VIEW - RETURN FROM HELP............................... ``` // Inits operational view when user changes from Help view back to operational view. - (void)trial_help_DidFinish:(HelpView *)controller { NSLog(@"trial_help_DidFinish"); [self dismissModalViewControllerAnimated:YES]; self.init_trial_operation; } ```
2011/07/08
[ "https://Stackoverflow.com/questions/6625598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/746100/" ]
You are creating a controller with ref count of 1 and a local reference each time `showHelp:` is called: ``` HelpView *controller = [[HelpView alloc] initWithNibName:@"HelpView" bundle:nil]; ``` you are losing your reference to it at the end of this method. You happen to have references to it in `done:` (self) and `*_help_didFinish` (controller), but you never release it in either of those locations. Dismissing the controller is fine, but you also have to `release` it. (Another option would be to never create a second one, and maintain an iVar to the original.)
69,474,555
--- **Thanks everyone, especially Mr.Drew Reese. If you are newbie as me, see his [answer](https://stackoverflow.com/a/69474833/14745811).** --- I don't know why but when I console log state **data** if I use **useEffect**, it always rerender although state **generalInfo** not change :/ so someone can help me to fix it and explain my wrong? I want the result which is the **data** will be updated when **generalInfo** changes. Thanks so much! This is my **useEffect** ======================== **Problem** in here: ``` const {onGetGeneralInfo, generalInfo} = props; const [data, setData] = useState(generalInfo); useEffect(() => { onGetGeneralInfo(); setData(generalInfo); }, [generalInfo]); ``` ======================== **fix:** ``` useEffect(() => { onGetGeneralInfo(); }, []); useEffect(() => { setData(generalInfo); }, [generalInfo, setData]); ``` this is **mapStateToProps** ``` const mapStateToProps = state => { const {general} = state; return { generalInfo: general.generalInfo, }; }; ``` this is **mapDispatchToProps** ``` const mapDispatchToProps = dispatch => { return { onGetGeneralInfo: bindActionCreators(getGeneralInfo, dispatch), }; }; ``` this is **reducer** ``` case GET_GENERAL_INFO_SUCCESS: { const {payload} = action; return { ...state, generalInfo: payload, }; } ``` this is **action** ``` export function getGeneralInfo(data) { return { type: GET_GENERAL_INFO, payload: data, }; } export function getGeneralInfoSuccess(data) { return { type: GET_GENERAL_INFO_SUCCESS, payload: data, }; } export function getGeneralInfoFail(data) { return { type: GET_GENERAL_INFO_FAIL, payload: data, }; } ``` and this is **saga** ``` export function* getGeneralInfoSaga() { try { const tokenKey = yield AsyncStorage.getItem('tokenKey'); const userId = yield AsyncStorage.getItem('userId'); const params = { method: 'GET', headers: { Authorization: `Bearer ${tokenKey}`, }, }; const response = yield call( fetch, `${API_GET_GENERAL_INFO}?id=${userId}`, params, ); const body = yield call([response, response.json]); if (response.status === 200) { yield put(getGeneralInfoSuccess(body)); } else { yield put(getGeneralInfoFail()); throw new Error(response); } } catch (error) { yield put(getGeneralInfoFail()); console.log(error); } } ```
2021/10/07
[ "https://Stackoverflow.com/questions/69474555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14745811/" ]
> > the initial state in redux and state in component is an empty array. > so I want to GET data from API. and I push it to redux's state. then I > useState it. I want to use useEffect because I want to update state > when I PUT the data and update local state after update. > > > Ok, so I've gathered that you want fetch the data when the component mounts, and then store the fetched data into local state when it is populated. For this you will want to separate out the concerns into individual effect hooks. One to dispatch the data fetch once when the component mounts, the other to "listen" for changes to the redux state to update the local state. *Note that it is generally considered anti-pattern to store passed props in local state.* ``` const {onGetGeneralInfo, generalInfo} = props; const [data, setData] = useState(generalInfo); // fetch data on mount useEffect(() => { onGetGeneralInfo(); }, []); // Update local state when `generalInfo` updates. useEffect(() => { setData(generalInfo); }, [generalInfo, setData]); ```
53,497,455
I have default laravel `users` table and my custom `educations` table in my database. In `educations` table users can save education histories. Example `educations` data: ``` ------------------------------------------------------------ id | user_id | university | speciality | finish_year | level ------------------------------------------------------------ 1 | 16 | Boston | Developer | 2018 | 4 ------------------------------------------------------------ 2 | 10 | Sinergy | Designer | 2014 | 4 ------------------------------------------------------------ 9 | 16 | Sinergy | Economist | 2010 | 8 ------------------------------------------------------------ ``` Now how I can get users using laravel eloquent by education level? For example get users where education level == 4
2018/11/27
[ "https://Stackoverflow.com/questions/53497455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7496039/" ]
Considering that you have a `educations` method in your User model that represents a `HasMany` association, you can use eloquent's `has` (or `whereHas`) method: ``` $users = App\User::whereHas('educations', function ($query) { $query->where('level', 4); })->get(); ``` Here's a link to the [docs](https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence).
5,059,506
I am trying to clean up some of my projects, and one of the things that are puzzling me is how to deal with header files in static libraries that I have added as "project dependencies" (by adding the project file itself). The basic structure is like this: ``` MyProject.xcodeproj Contrib thirdPartyLibrary.xcodeproj Classes MyClass1.h MyClass1.m ... ``` Now, the dependencies are all set up and built correctly, but how can I specify the public headers for "thirdPartyLibrary.xcodeproj" so that they are on the search path when building MyProject.xcodeproj. Right now, I have hard-coded the include directory in the thirdPartyLibrary.xcodeproj, but obviously this is clumsy and non-portable. I assume that, since the headers are public and already built to some temporary location in ~/Library (where the .a file goes as well), there is a neat way to reference this directory. Only.. how? An hour of Googling turned up blank, so any help is greatly appreciated!
2011/02/20
[ "https://Stackoverflow.com/questions/5059506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292477/" ]
If I understand correctly, I believe you want to add a path containing $(BUILT\_PRODUCTS\_DIR) to the HEADER\_SEARCH\_PATHS in your projects build settings. As an example, I took an existing iOS project which contains a static library, which is included just in the way you describe, and set the libraries header files to public. I also noted that the PUBLIC\_HEADERS\_FOLDER\_PATH for this project was set to "/usr/local/include" and these files are copied to $(BUILT\_PRODUCTS\_DIR)/usr/local/include when the parent project builds the dependent project. So, the solution was to add $(BUILT\_PRODUCTS\_DIR)/usr/local/include to HEADER\_SEARCH\_PATHS in my project's build settings. ``` HEADER_SEARCH_PATHS = $(BUILT_PRODUCTS_DIR)/usr/local/include ``` Your situation may be slightly different but the exact path your looking for can probably be found in [Xcode's build settings](http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/0-Introduction/introduction.html). Also you may find it helpful to add a Run Script build phase to your target and note the values of various settings at build time with something like: ``` echo "BUILT_PRODUCTS_DIR " $BUILT_PRODUCTS_DIR echo "HEADER_SEARCH_PATHS " $HEADER_SEARCH_PATHS echo "PUBLIC_HEADERS_FOLDER_PATH " $PUBLIC_HEADERS_FOLDER_PATH . . . etc. ```
53,719,824
Say I have an array of objects like so: ``` [{"taco":"","burrito":"","scone":"","beans":"true"}, {"taco":"true","burrito":"","scone":"true","beans":""}, {"taco":"true","burrito":"","scone":"","beans":""}, {"taco":"true","burrito":"","scone":"","beans":"true"}] ``` I need to count the occurrence of each element and return in it in an array ``` [3, 0, 1, 2] ``` any ideas would be appreciated, thanks! I have attempted ``` var a = datasets.reduce(function (item, index) { if (typeof item[index] == 'undefined') { item[index] = 1; } else { item[index] += 1; } return item; }, {}); ``` could not get anything like that to work so i attempted converting it to json and then removing any key: value pairs with no value then counting remaining ones but have had no success with that either ``` function tableToJson(table) { var data = []; var headers = []; for (var i=0; i < table[0].rows[0].cells.length; i++) { headers[i] = table[0].rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,''); } for (var i=1; i< table[0].rows.length; i++) { var tableRow = table[0].rows[i]; var rowData = {}; for (var j=0; j<tableRow.cells.length; j++) { rowData[ headers[j] ] = tableRow.cells[j].innerHTML; } data.push(rowData); } return data } function removeEmpty(jsonObj) { var newObj = Object.getOwnPropertyNames(jsonObj); for (var i = 0; i < newObj.length; i++) { var value = newObj[i]; if (jsonObj[value] === null || jsonObj[value] === undefined) { delete jsonObj[value]; } } } ```
2018/12/11
[ "https://Stackoverflow.com/questions/53719824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9633658/" ]
**You can try this** You can do it with `reduce()`. What i have done is first i check is the **`object property of current element`** if it is already in **`output object`**. If it's present than i check the value of **`current element property`**. if it is true than i increment the property of **`output object`** by `1`. If the **`object property of current element`** is not available in output than i check for the value of **`current element property`**. if it is true i assign output object property with value `1`. if false i assign output object property with `0`. ```js let obj = [{"taco":"","burrito":"","scone":"","beans":"true"}, {"taco":"true","burrito":"","scone":"true","beans":""}, {"taco":"true","burrito":"","scone":"","beans":""}, {"taco":"true","burrito":"","scone":"","beans":"true"}] let op = obj.reduce((output,current)=>{ for(let key in current){ if( output[key] ){ if( current[key] ) output[key]+=1; } else { if( current[key] ){ output[key] = 1; } else{ output[key] = 0; } } } return output; },{}) console.log(op); ```
23,241
I'm sure there will be variation depending on what the contaminated item or surface is made of - linens, I could imagine, would remain dangerous for longer than a door-knob. But if the items are not decontaminated in some way, how long can the virus survive outside a host?
2014/10/17
[ "https://biology.stackexchange.com/questions/23241", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/9817/" ]
This really depends on the environment, one study (listed below as reference 1) found that the Ebola virus can survive under ideal conditions on flat surfaces in the dark for up to six days - see the figure from the same publication. ![enter image description here](https://i.stack.imgur.com/0dLLL.gif) However, the virus is quite sensitive to UV radiation (see reference 2 for all the details) and most viral particles are likely to get inactivated within relatively short time. It might still be possible to get positive tests for Ebola from really sensitive PCR-based tests, but these are most likely not infectious anymore. The CDC lists common bleach (or any other routinely used disinfected) as a good way to get rid of Ebola viruses. References: 1. [Persistence in darkness of virulent alphaviruses, Ebola virus, and Lassa virus deposited on solid surfaces](http://link.springer.com/article/10.1007/s00705-010-0791-0/fulltext.html) 2. [Sensitivity to ultraviolet radiation of Lassa, vaccinia, and Ebola viruses dried on surfaces](http://link.springer.com/article/10.1007/s00705-010-0847-1/fulltext.html)
42,232,606
I'm using Django 1.10 and trying to catch all exceptions with exception middleware. The code below causes an internal server error: ``` mw_instance = middleware(handler) TypeError: object() takes no parameters ``` views.py ``` from django.http import HttpResponse def my_view(request): x = 1/0 # cause an exception return HttpResponse("ok") ``` settings.py ``` MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'myproject.middleware.ExceptionMiddleware', ] ``` middleware.py ``` from django.http import HttpResponse class ExceptionMiddleware(object): def process_exception(self, request, exception): return HttpResponse("in exception") ``` I have seen these [object() takes no parameters in django 1.10](https://stackoverflow.com/questions/39457381/object-takes-no-parameters-in-django-1-10) and other questions talking about middleware versus middleware\_classes, but I'm not sure how that applies to this case, or what I'd actually need to change to fix the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42232606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/984003/" ]
Since you are using the new `MIDDLEWARE` settings, your Middleware class must accept a `get_response` argument: <https://docs.djangoproject.com/en/1.10/topics/http/middleware/#writing-your-own-middleware> You could write your class like this: ``` from django.http import HttpResponse class ExceptionMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_exception(self, request, exception): return HttpResponse("in exception") ``` You could also use the `MiddlewareMixin` to make your Middleware compatible with pre-1.10 and post-1.10 Django versions: <https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware> ``` from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin class ExceptionMiddleware(MiddlewareMixin): def process_exception(self, request, exception): return HttpResponse("in exception") ```
59,278,991
Alright I'm trying to allow user input to include only letters, numbers, and dashes. Any other characters would be invalid. I also only want the characters to be 1-9 characters in length. Here is what I have so far: ``` def main(): tag = input("Please enter your ID Tag: ") while(not rSeriesValidate(tag)): print("INVALID ID: Try again") tag = input("Please reenter your ID Tag: ") print("VALID ID. Move along, move along.") def rSeriesValidate(tag): isValid = True if(len(tag)<1 or len(tag)> 9): isValid = False elif(not tag.isalnum()): isValid = False return isValid main() ``` With this I am able to make sure the worker inputs letters between 1-9 and that they are letters or numbers. However I can't figure out how to also allow dashes "-" to be inputted. Any suggestions? Thank you
2019/12/11
[ "https://Stackoverflow.com/questions/59278991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you don't want to use regular expressions, try simply going character by character: ``` def rSeriesValidate(tag): if len(tag) < 1 or len(tag) > 9: return False for currChar in tag: if not currChar.isalnum() and currChar != "-": return False return True ``` This first checks for the input length requirement, and returns False if it is not met. For input of suitable length, it goes on to check each character of the input. If it finds a disallowed character (one that is not alphanumeric and not a dash), it returns False.
5,485,338
What version of Eclipse do I need for Google Web Toolkit? I see about 7 versions, but none make any references to GWT. Google doesn't mention it to. I did install the PHP version.
2011/03/30
[ "https://Stackoverflow.com/questions/5485338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340761/" ]
Definitely the Java EE version. The regular java version doesn't seem to work with the google plugin.
24,378,233
Can't find an answer anywhere in Docs... is there a way to make it so that the placeholder value for a `number_field_tag` or whatever is the value that is submitted to the `value` if the user doesn't enter anything else? I.e., in my code below: ``` <%= number_field_tag "transaction[][#{thing}]", :quantity, min: 0, placeholder: @transactionparams ? @transactionparams["#{thing}"] : 0 %> ``` I would like the equation in placeholder to evaluate and then be POSTed if the user doesn't enter anything else. Thanks!
2014/06/24
[ "https://Stackoverflow.com/questions/24378233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2731253/" ]
i was able to do it using `freopen(..);`: <http://www.cplusplus.com/reference/cstdio/freopen/>
1,441,063
I have some code like: ``` Lookup(Of String)("Testing") Lookup(Of Integer)("Testing") ``` And both of those Lookups work great. What I'm trying to is call the appropriate LookUp based on the type of another variable. Something that would look like... ``` Lookup(Of GetType(MyStringVariable))("Testing") ``` I've tried to Google this but I'm having a hard time coming up with an appropriate search. Can anyone tell me how to do what I want?
2009/09/17
[ "https://Stackoverflow.com/questions/1441063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73381/" ]
You do not specify the full signature for the method that you're calling, but my psychic powers tell me that it is this: ``` Function Lookup(Of T)(key As String) As T ``` And you want to avoid having to repeat `Integer` twice as in the example below: ``` Dim x As Integer x = Lookup(Of Integer)("foo"); ``` The problem is that type parameters are only deduced when they're used in argument context, but never in return value context. So, you need a helper function with a `ByRef` argument to do the trick: ``` Sub Lookup(Of T)(key As String, ByRef result As T) T = Lookup(Of T)(key) End Sub ``` With that, you can write: ``` Dim x As Integer Lookup("foo", x); ```
49,649,819
I am currently using this code to screen capture the panel I created, but whenever I am saving it, the quality is bad. Is there any way to maintain the good quality when saving it? I tried resizing the panel but the result is still the same. I tried doing a normal screen shot with the snipping tool and it also has the same result with the codes I use. Any suggestions? or help? ``` private void SaveControlImage(Control theControl) { snapCount++; int width = panel1.Size.Width; int height = panel1.Size.Height; Bitmap bm = new Bitmap(width, height, PixelFormat.Format64bppPArgb); panel1.DrawToBitmap(bm, new Rectangle(0, 0, width, height)); //bm.Save(@"D:\TestDrawToBitmap.bmp", ImageFormat.Bmp); bm.Save(deskTopPath + @"/Offer_" + snapCount.ToString() + "_" + DateTime.Now.ToString("yyyyMMdd") + @".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); } ``` --- Like here, it looks pixelated if you compare it to what you're reading now (like this website). I tried to screen cap the form but it looks like the uploaded picture so its useless Screenshot: ![1](https://i.stack.imgur.com/HY9Z7.jpg)
2018/04/04
[ "https://Stackoverflow.com/questions/49649819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7899801/" ]
This is what I use to save a screenshot: ``` using System.Drawing; using System.Drawing.Imaging; using System.IO; private void SaveControlAsImage(Control control, string path) { Bitmap bitmap = new Bitmap(control.Width, control.Height); control.DrawToBitmap(bitmap, control.Bounds); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) { /* using ImageFormat.Png or ImageFormat.Bmp saves the image with better quality */ bitmap.Save(fs, ImageFormat.Png); } } ``` [Control screenshot using Windows Snipping Tool](https://i.stack.imgur.com/B58J4.png) [Control screenshot using SaveControlAsImage (ImageFormat.Png)](https://i.stack.imgur.com/XtZcQ.png) [Control screenshot using SaveControlAsImage (ImageFormat.Jpeg)](https://i.stack.imgur.com/Wf9Vw.jpg) It's not the best quality (just a little blurry), but this removes the distortion around the text and keeps the right color. Sidenote: You're not using the parameter (`theControl`) passed to your method, so you might as well remove it (not recommended), or change all the calls to `panel1` inside the method to `theControl` and call the method like ``` this.SaveControlImage(this.panel1); ``` Also, when you're accessing just a property (i.e. `this.panel1.Size.Width`) it's better to just call the property instead of assign it to a variable. If you're calling a method and getting a value back (which you'll be using more than once), you must assign it to a variable (i.e. `int arrayCount = array.Count()`).
57,554,043
In my head section of my `form.layout.blade.php` I have the following: ``` <head> <script src="/js/main.js"></script> <head> ``` This is layout file is loaded before all pages are loaded. Is there a way to *not* load `main.js` for a specific route?
2019/08/19
[ "https://Stackoverflow.com/questions/57554043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5272159/" ]
you can use if statement like this. main.js will not load on this page ``` @if(!Request::is('subpage/url')) <script src="/js/main.js"></script> @endif ```
1,886,096
``` L->| A -> B ^ | |__> C -> D-> G->X--| | K |_> T | |_>Z |___________| ``` I hope this small drawing helps convey what I'm trying to do. I have a list of 7,000 locations, each with an undefined, but small number of doors. Each door is a bridge between both locations. Referencing the diagram above, how would I go about finding the quickest route through the doors to get from A to Z? I don't need full on source, just psuedo code would be fine. Obviously you can take A -> B ->C -> D -> G -> X -> L -> Z, but the shortest route is A -> B -> C -> K -> X -> Z.
2009/12/11
[ "https://Stackoverflow.com/questions/1886096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88770/" ]
Represent your locations as nodes and the doors as edges in a graph. Then apply some rather standard [shortest path algorithm(s)](http://en.wikipedia.org/wiki/Shortest_path_problem) and you're done.
1,772,475
I'm running a LAMP box with PHP running as fcgid. APC is installed and working well. However, each PHP process gets its own cache. This is a problem, because it would make far more sense to have 10 PHP processes with 300MB shared APC cache than 10 PHP processes, each with a redundant 30MB unshared APC cache. There was a prior thread on this topic 8 months ago ([How to share APC cache between several PHP processes when running under FastCGI?](https://stackoverflow.com/questions/598444/how-to-share-apc-cache-between-several-php-processes-when-running-under-fastcgi)) and I am wondering if there have been any developments in this realm since then.
2009/11/20
[ "https://Stackoverflow.com/questions/1772475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199475/" ]
As far as I know it's still not possible to use shared memory cache with any PHP cacher amongst multiple processes... anyway, unless you're under extremely heavy load you should be fine with separate caches, I suppose, since they'll be filled pretty quickly. And hey, RAM is cheap nowadays!
2,465,656
is this a valid JQuery usage pattern to : ``` <script type="text/javascript"> $("body").prepend('<input type="hidden" id="error" value="show">'); </script> ``` That is using Jquery to manipulate / insert HTML Tags **when the Document has NOT YET been loaded** (by not using document.ready for the inserting into the DOM)? (Normally I only use document.ready, but in this case I need to insert some Information into the DOM that then is present, when document.ready is called. This is some kind of "happens-before" relations ship I want to achieve so that I am shure when document.ready is called the inserted Form field is available in the document, as I depend on that information. Thank you very much jens
2010/03/17
[ "https://Stackoverflow.com/questions/2465656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/293513/" ]
Yes, you can do that, but: * You have to place the script somewhere after the closing tag of the element that you add elements to. That means that the body element is not a good candidate to prepend anything to. * Make sure that the HTML code is valid. If you are using XHTML you should self close the input element. Consider using the object creation model instead of innerHTML model: ``` $("#someElement").prepend( $('<input/>').attr({ 'type': 'hidden', 'id': 'error' 'value': 'show' }) ); ``` This will create the element as a DOM object instead of using innerHTML to parse the HTML code.
50,790
The following theorem has been mentioned (and partially proved) in the book Functions of Bounded Variation and Free Discontinuity Problems by Luigi Ambrosio et. al. Let $\mu,\nu$ be positive measures on $(X,\mathcal{E})$. Assume that they are equal on a collection of sets $\mathcal{G}$ which is closed under finite intersections. Also assume that there are sets $X\_h \in \mathcal{G}$ such that $\displaystyle{X= \bigcup\_{h=1}^\infty X\_h}$ and that $\mu(X\_h) = \nu(X\_h) < \infty$ for all $h$. Then $\mu, \nu$ are equal on the $\sigma$-algebra generated by $\mathcal{G}$. The authors prove the theorem for the case where $\mu,\nu$ are positive finite measures and $\mu(X) = \nu(X)$ and say that the general case follows easily. However, this is not at all straight forward for me. I have tried to prove this but cannot reach a valid proof. Here is my attempt at a proof: Let $G\_h = \{g \cap X\_h | g \in G\}$. Then clearly from using the finite case of the theorem, we have that $\mu,\nu$ coincide on every $\sigma (G\_h)$. My problem now is to show that this implies that they agree on $\sigma(G)$. All my attempts in this direction have been futile. I feel that the solution should be relatively easy (as the authors themselves point out). Any help in the proof is greatly appreciated. Thanks, Phanindra
2011/07/11
[ "https://math.stackexchange.com/questions/50790", "https://math.stackexchange.com", "https://math.stackexchange.com/users/13199/" ]
The collection of $A \in \mathcal{E}$ such that $\mu(A \cap X\_h) = \nu(A \cap X\_h)$ for all $h$ forms a $\sigma$-algebra containing $\sigma(G)$.
24,630,720
Is there any equivalent of strict mocks in python? Some mechanism to report unintended call of mocked methods (action.step2() in this example), just like this in GoogleMock framework. ``` class Action: def step1(self, arg): return False def step2(self, arg): return False def algorithm(action): action.step1('111') action.step2('222') return True class TestAlgorithm(unittest.TestCase): def test_algorithm(self): actionMock = mock.create_autospec(Action) self.assertTrue(algorithm(actionMock)) actionMock.step1.assert_called_once_with('111') ```
2014/07/08
[ "https://Stackoverflow.com/questions/24630720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407981/" ]
Looks like it's not supported out of the box. However there are at least two approaches on how to achieve the same result. Passing list of allowed members ------------------------------- According to mock documentation > > *spec*: This can be either a **list of strings** or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). **Accessing any attribute not in this list will raise an AttributeError**. > > > So, in order to fail your test example just replace ``` actionMock = mock.create_autospec(Action) ``` to ``` actionMock = mock.Mock(spec=['step1']) ``` Such an approach have certain drawbacks compared to passing class or instance as `spec` argument, as you have to pass all the allowed methods and than set up expectations on them, effectively registering them twice. Also, if you need to restrict a subset of methods you have to pass list of all methods execept those. This can be achieved as follows: ``` all_members = dir(Action) # according to docs this is what's happening behind the scenes all_members.remove('step2') # remove all unwanted methods actionMock = mock.Mock(spec=all_members) ``` Setting exceptions on restricted methods ---------------------------------------- Alternative approach would be to excplicitly set failures on methods you don't want to be called: ``` def test_algorithm(self): actionMock = mock.create_autospec(Action) actionMock.step2.side_effect = AttributeError("Called step2") # <<< like this self.assertTrue(algorithm(actionMock)) actionMock.step1.assert_called_once_with('111') ``` This have some limitations as well: you've got to set errors as well as expectations. As a final note, one radical solution to the problem would be to patch `mock` to add `strict` parameter to `Mock` constructor and send a pull request. Than either it would be accepted or `mock` maintainers will point out on how to achieve that. :)
20,531,272
In my php program, I have to insert variables into one of my sql tables. Every time I go to test this out though, the values don't get posted to the table. Is there something wrong with these statements? or is the problem bigger than these 2 lines ``` $sqli = mySQLi_connect("localhost","root","root","myProject"); mysqli_query("insert into purchases (id, productID, quantity) values ($id, $productID, $quantity)"); ```
2013/12/11
[ "https://Stackoverflow.com/questions/20531272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3093085/" ]
Look at [my white paper on Drools Design Patterns](http://www.google.at/url?q=http://www.redhat.com/rhecm/rest-rhecm/jcr/repository/collaboration/sites%2520content/live/redhat/web-cabinet/home/resourcelibrary/whitepapers/brms-design-patterns/rh%3apdfFile.pdf) especially the section on Data Validation. The section explains a strategy that circumvents the straightforward creation of one Drools rule per rule in the requirements. Simply put, you use data to describe these rules, insert the data as facts, along with the facts representing actual data, and write rules relating the descriptions to the data. You might say that the rules "interpret" the descriptions against the data. There are adavantages and disadvantages to this approach, but it ought to be considered before launching into handwritten or spreadsheet rules.
24,768,747
I don't quite understand how escape the character works in .awk scripts. I have this line in the file I want to read: ``` #Name Surname City Company State Probability Units Price Amount ``` If I just write: ``` awk < test.txt '/\#/ {print $1}' ``` in the command line, then everything is fine and the output is #Name. However, if I try to do the same inside an .awk file the following way: ``` /\#/ {print $1}; ``` I get no output for this. Also, gEdit won't recognize "\" as an escape character inside .awk for some reason. Why is this happening and is there a workaround?
2014/07/15
[ "https://Stackoverflow.com/questions/24768747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3614293/" ]
Join your queries with a `UNION`. The way you've got it now, it'll return two results sets. ``` SELECT [col1], [col2] FROM Contact UNION ALL SELECT [col1], [col2] FROM Numar_contact ``` As DJ KRAZE pointed out in a comment, it might not be a bad idea to wrap this in a sproc or a TVF. But this will work too. **Edit:** I just learned via comments that the two tables are actually unrelated. In light of that, I'd be tempted to use two `SqlCommand`s with two, distinct `foreach` loops. But if you're sold on this way, ``` SELECT id_contact, nume_contact, prenume_contact FROM Contact UNION ALL SELECT id_contact, numar, NULL FROM Numar_contact ``` This will align the data from the two tables, but where the second table doesn't have a `[prenume_contact]` it will select `NULL`. I might have mixed up the column positions here, since I don't really understand what those names are meant to represent. **Edit 2:** ``` string connString = @"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI"; using (SqlConnection conn = new SqlConnection(connString)) { try { conn.Open(); using (SqlCommand cmd = new SqlCommand("SELECT * FROM Contact", conn)) using (SqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { listBox1.Items.Add(rdr[0].ToString() + " " + rdr[1].ToString() + " " + rdr[2].ToString()); } } using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM Numar_contact", conn)) using (SqlDataReader rdr2 = cmd.ExecuteReader()) { while (rdr2.Read()) { listBox1.Items.Add(rdr2[0].ToString() + " " + rdr2[1].ToString()); } } } catch { } } ``` **Edit 3, thanks to insight from Scott Chamberlain:** On the other hand, you might want to perform a [`JOIN`](http://technet.microsoft.com/en-us/library/ms191517(v=sql.105).aspx) of some kind, most commonly an `INNER JOIN`. Note that this is an entirely different operation from any we've talked about before. ``` SELECT Contact.id_contact, Contact.nume_contact, Contact.prenume_contact, Numar_contact.numar FROM Contact INNER JOIN Numar_contact on Contact.id_contact = Numar_contact.id_contact ``` This will tie the two tables together, returning a record for each contact-numar\_contact. Again, this is definitely *not* the same as doing a `UNION`. Make sure you're aware of the difference before you pick which you want. Use this if your second table contains data that relates many-to-one to the first table.
48,302,244
I can transpose a square matrix, but now I'd like to transpose a non square matrix (in my code 3\*2) with user input. Other sources recommended me to create a new matrix first, which I have done. I manage to make the matrix, but when transposing, it stops from the 4th value. I have looked at other topics but I can't find the error. Here is my code so far, can someone tell me where I went wrong? Thanks! ``` //const const int ROWS = 3; const int COLS = 2; //first matrix int[,] matrix1 = new int[ROWS, COLS]; for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { Console.Write("Enter num: "); matrix1[i, j] = int.Parse(Console.ReadLine()); } } //output Console.WriteLine("Eerste matrix: "); for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { Console.Write(matrix1[i, j] + " "); } Console.WriteLine(" "); } //transposed matrix Console.WriteLine("Tweede matrix: "); int[,] matrix2 = new int[COLS, ROWS]; for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { matrix2[j, i] = matrix1[j, i]; Console.Write(matrix2[j, i] + " "); } Console.WriteLine(" "); } ``` This is what I get when running the program: ``` //output Enter num: 1 Enter num: 2 Enter num: 3 Enter num: 4 Enter num: 5 Enter num: 6 first matrix: 1 2 3 4 5 6 transposed matrix: 1 3 2 4 //--->> Only went up to 4th value? ```
2018/01/17
[ "https://Stackoverflow.com/questions/48302244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9229665/" ]
So, at the beginning you load a matrix with fields : "i,j" => "row, column" On the last step, you try accessing the matrix with a "j,i" => "column, row" order. You're inverting the i,j indexes.- Let me help you by just changing the variable names : //const ``` const int ROWS = 3; const int COLS = 2; //first matrix int[,] matrix1 = new int[ROWS, COLS]; for (int row = 0; row < ROWS; row++) { for (int column = 0; column < COLS; column ++) { Console.Write("Enter num: "); matrix1[row, column] = int.Parse(Console.ReadLine()); } } ``` //output ``` Console.WriteLine("Eerste matrix: "); for (int row = 0; row < ROWS; row++) { for (int column = 0; column < COLS; column++) {`enter code here` Console.Write(matrix1[row, column] + " "); } Console.WriteLine(" "); } ``` //transposed matrix ``` Console.WriteLine("Tweede matrix: "); int[,] matrix2 = new int[COLS, ROWS]; for (int row = 0; row < ROWS; row++) { for (int column = 0; column < COLS; column++) { matrix2[column, row] = matrix1[row, column]; Console.Write(matrix2[column, row] + " "); } Console.WriteLine(" "); } ``` // EDIT : actually noticed the sample didn't traspose it properly. fixed it.
65,235,190
I am thinking of setting up a bitnami mongodb replicaset in K8s, as explained [here](https://github.com/bitnami/charts/tree/master/bitnami/mongodb#architecture). However, as a note they mention this while upgrading: > > Note: An update takes your MongoDB replicaset offline if the Arbiter is enabled and the number of MongoDB replicas is two. Helm applies updates to the statefulsets for the MongoDB instance and the Arbiter at the same time so you loose two out of three quorum votes. > > > I am not sure what does it actually mean "taking the replicaset offline": 1. Is it that the whole mongo service goes offline/down and therefore there is downtime on the service when performing helm upgrades? 2. Is it that, while performing the upgrade, the replicaset will have only one mongodb server working, while both, the other mongo db server and arbiter, are offline and being upgraded?. In this case, it will not imply downtime, just that momentarily, there is just one server available (instead of two), so similar to a standalone setup.
2020/12/10
[ "https://Stackoverflow.com/questions/65235190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848107/" ]
Bitnami developer here > > Is it that, while performing the upgrade, the replicaset will have > only one mongodb server working, while both, the other mongo db server > and arbiter, are offline and being upgraded? > > > That will depend on how many replicas you have. If you install the chart with 2 replicas + 1 arbiter, yes it means that. However, if you install the chart with 4 replicas + 1 arbiter, you'll have only 1 replica and the arbiter being restarted simultaneously, having the other 3 replicas up. > > In this case, it will not imply downtime, just that momentarily, there > is just one server available (instead of two), so similar to a > standalone setup. > > > As it's mentioned in the previous response, it does imply a small downtime indeed if the minimum quorum of alive replicas it's not meet.
8,968,133
I have added a view to a layout which occupies a part of my screen. To this layout I want to add another layout which will be transparent. On this layout there should be only two lines which will scroll over the background layout. This I am doing so that my background layout is not invalidated and only the foreground is invalidated. How can I add another layout which will be transparent?
2012/01/23
[ "https://Stackoverflow.com/questions/8968133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463039/" ]
Use `FrameLayout` as a parent layout and stack it up with as many layouts as you want. Thats one part of the answer. To make a layer (a layout in this case) transparent, set the alpha value in its background (a color) to 0. For instance `android:background="#00777777"` sets a background which is translucent with a dull gray. You get the idea.
229,878
This is part of a series of questions. *Context*: a friend of mine is writing a novel about a rogue planet around the mass of Mars passing by the solar system before continuing its journey in interstellar space (it must not be captured by the Sun). Given sufficient heads-ups, Earth sends a research mission to land on it, study it for as long as possible, and return. We would like Earthians to have as much time as possible on the rogue planet. **How slow and close could a Mars-like planet pass near the Solar System to be plausible and not cause catastrophic Earth orbit perturbation?** I am guessing that there is no theoretical lower speed limit, as it can barely have the escape velocity of its birth system, then be slowed down by more stars behind it that in front of it. (right?) Or maybe a theoretical limit is the solar system escape velocity, which is around 700km/s, as even an almost stale object relative to the solar system will fall at that speed?
2022/05/12
[ "https://worldbuilding.stackexchange.com/questions/229878", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/76461/" ]
"Passing through the solar system" I guess means in this case "passing through the inner solar system". If it only passes the Kuiper belt or the Oort cloud, there would be no serious perturbations (no "showering the inner solar system" or the like"). When passing through the inner solar system there will be no perturbation either, unless it passes close to a planet, which is not likely. The trajectory of the object will in most cases be highly inclined to the plane of the solar system which diminishes the probability of a close encounter. The escape velocity depends on the distance from the Sun. The value of 700 km/s refers to escape velocity from the surface of the Sun. At Earth's orbit it is something around 42 km/s. An interstellar object will typically enter the solar system with a delta-v of 20-30 km/s, but the value can be much larger - 200 km/s and more - or smaller. As it approaches the Sun it will accelerate due to the Sun's gravity and pass by in a hyperbolic trajectory. How fast it is at any point is the (vectorial) sum of its initial velocity and its acceleration by the Sun. Its maximum velocity will therefore depend on how close it gets to the Sun - the closer it gets the faster it will become. Unless its initial delta-v was close to zero it will almost always have escape velocity. The capture of interstellar objects by the Sun is possible but certainly very rare. **How close could a Mars-like planet pass near the Solar System to be plausible and not cause catastrophic Earth orbit perturbation?** As close as you like.
29,457,315
I have 3 tables, like so: ``` release (release_id, name, ...) medium (medium_id, release_id, name, ...) track (track_id, medium_id, title, ...) ``` Having only the release\_id, i want to be able delete both the track and the medium associated with that release\_id in one shot using one query. Is it possible? If yes, can I get a rough template, I'll figure out the rest. Do I need multiple delete queries?
2015/04/05
[ "https://Stackoverflow.com/questions/29457315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/888139/" ]
Strictly speaking, yes, you need three separate delete statements. However, if you always want the associated rows deleted from the other two tables when you delete a row from the 'release' table, you can use foreign keys and an ON DELETE CASCADE constraint on the 'release' table. See, e.g. <http://www.mysqltutorial.org/mysql-on-delete-cascade/>
61,338,861
I'm trying to increment an index in a loop for but my program does not work. I have a simple array with 10 elements and I want to sum all elements of this array. I'm having problem, because I consider two loop, first I want to calculate the five first elements and than the five last, but my counter i\_i does not change in the program, the code is ``` import numpy as np from matplotlib.pylab import * x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10] i_i = 0 i_j = 5 sum_t = 0.0 for i in range(2): for ii in range(i_j): sum_t += x[i] i_i += 5 i_j += 5 print(sum_t) ``` The valeu of the sum must be 55, but I'm have problem with the index i\_i. Any suggestion is welcome to make the program work in this way.
2020/04/21
[ "https://Stackoverflow.com/questions/61338861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6457422/" ]
You used the wrong variable in the second loop, it is `ii`, not `i`. Secondly the last loop must go from `i_i` to `i_j` so your range is also wrong: ``` import numpy as np from matplotlib.pylab import * x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10] i_i = 0 i_j = 5 sum_t = 0.0 for i in range(2): for ii in range(i_i, i_j): sum_t += x[ii] i_i += 5 i_j += 5 print(sum_t) ```
8,147,696
I can't find this information online or in the documentation, does anyone know what versions of Android and iOS the AIR 3.0 captive runtime is compatible with? I'm assuming there is some restriction there, but short of actually compiling a program and trying it on iPhone for example, which I don't have, how can I tell which OS versions are supported? I know that you can compile an Adobe AIR 2.7(?) application to target say Android 2.2, but what about the captive runtime with AIR 3.0? Also I don't see anywhere to find out the iOS version restriction with AIR, as you have to pay $100 to Apple to even get the SDK which would allow me to make an iOS project in the first place.
2011/11/16
[ "https://Stackoverflow.com/questions/8147696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/997477/" ]
System requirements using captive runtime are the same as without - in other words, quoting from the [reqs page](http://www.adobe.com/products/air/tech-specs.html): * Android™ 2.2, 2.3, 3.0, 3.1, and 3.2 * iPod touch (3rd generation) 32 GB and 64 GB model, iPod touch 4, iPhone 3GS, iPhone 4, iPad, iPad 2 * iOS 4 and above Incidentally, note that captive runtime is not a new option for iOS - it's how AIR has always worked there, since iOS doesn't allow using a separate runtime. So really, captive runtime is a matter of doing on Android (or elsewhere) what's been done on iOS all along.
28,762,226
i need sql query for report from table item per day(fix day1-day31 as column) of the month when i input **month and year**. This is my table (item)   ID   |   NAME  |   DATE ---------------------------------------------------    1   |   ITEM A |   2015-2-25 13:37:49    2   |   ITEM A |   2015-2-25 14:37:49    3   |   ITEM A |   2015-2-26 13:30:55    4   |   ITEM B |   2015-2-26 15:37:49    5   |   ITEM B |   2015-2-26 17:57:49    6   |   ITEM C |   2015-2-27 13:00:33 --- (input month=02 and year=2015) What I need to achieve with a view is the following: NAME | 1| 2| 3|…|25|26|27|28|29|30|31|Total ------------------------------------------------------ ITEM A| 0| 0| 0|…| 2 | 1 | 0 | 0 | 0 | 0 | 0 | 3 ITEM B| 0| 0| 0|…| 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2 ITEM C| 0| 0| 0|…| 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 --- Any ideas would be very much appreciated. Thanks in advance. Sorry this is my first post.
2015/02/27
[ "https://Stackoverflow.com/questions/28762226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4613455/" ]
You can do this using a PIVOT in your query ``` SELECT name, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31], ([1] + [2] + [3] + [4] + [5] + [6] + [7] + [8] + [9] + [10] + [11] + [12] + [13] + [14] + [15] + [16] + [17] + [18] + [19] + [20] + [21] + [22] + [23] + [24] + [25] + [26] + [27] + [28] + [29] + [30] + [31]) as total FROM ( SELECT Name, id, Datepart(day, [date]) day FROM item WHERE MONTH([date]) = 2 AND YEAR([date]) = 2015 ) x PIVOT ( count(id) FOR day IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31]) ) p ```
13,695,522
I am having trouble trying to loop through a multidimensional array using PHP. When I use the `print_r()` function, here is my output: ``` Array ( [0] => Array ( [fname] => [sname] => [address] => [address2] => [city] => [state] => Select State [zip] => [county] => United States [phone] => [fax] => [email] => [use_email] => on ) ``` I have tried several techniques but none seem to work. Any help is appreciated!
2012/12/04
[ "https://Stackoverflow.com/questions/13695522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317740/" ]
easiest would just use a foreach statement: ``` foreach($yourarray as $array_element) { $address = $array_element['address']; $fname = $array_element['fname']; ... } ```
310,807
I have a malfunctioning hard drive that is full of thousands of files. All the files are still shown as 'there' when explored (with both Windows and Linux). Some of the files can be recovered by moving them to another hard drive, files with CRC errors cannot be moved. Everything that can be recovered has been moved; the files that could not be moved have been left on the hard drive. I would like to create a 'text file' that lists all the files on the broken hard drive so that I have a list of files for future reference. Are there any applications that allow me to do this?
2011/07/15
[ "https://superuser.com/questions/310807", "https://superuser.com", "https://superuser.com/users/90368/" ]
You can resize it but thats all that you can do Go to the space between the the address bar and the search bar to resize Or you can disable both explorer and start menu by following [this](http://www.howtogeek.com/howto/10246/how-to-disable-search-in-windows-7/) (Though i understand that this isn't what you really want)
4,274,388
``` string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. " d = string.match(/(jack|jill)/i) # -> MatchData "Jill" 1:"Jill" d.size # -> 1 ``` This only match the first occurrence it seems. `string.scan` does the job partially but it doesn't tell anything about the index of the matched pattern. How do i get a list of all the matched instances of the pattern and their indices (positions)?
2010/11/25
[ "https://Stackoverflow.com/questions/4274388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/499097/" ]
You can use `.scan` and `$`` global variable, which means *The string to the left of the last successful match*, but it doesn't work inside usual `.scan`, so you need this *hack* (stolen from [this answer](https://stackoverflow.com/a/2257073/322020)): ```ruby string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. " string.to_enum(:scan, /(jack|jill)/i).map do |m,| p [$`.size, m] end ``` output: ``` [0, "Jack"] [9, "Jill"] [57, "Jack"] [97, "Jill"] ``` **UPD:** Note the behaviour of lookbehind – you get the index of the really matched part, not the *look* one: ```none irb> "ab".to_enum(:scan, /ab/ ).map{ |m,| [$`.size, $~.begin(0), m] } => [[0, 0, "ab"]] irb> "ab".to_enum(:scan, /(?<=a)b/).map{ |m,| [$`.size, $~.begin(0), m] } => [[1, 1, "b"]] ```
10,458,660
I'm trying to compare these three but it seems only `array_map` works. ``` $input = array( ' hello ','whsdf ',' lve you',' '); $input2 = array( ' hello ','whsdf ',' lve you',' '); $input3 = array( ' hello ','whsdf ',' lve you',' '); $time_start = microtime(true); $input = array_map('trim',$input); $time_end = microtime(true); $time = $time_end - $time_start; echo "Did array_map in $time seconds<br>"; foreach($input as $in){ echo "'$in': ".strlen($in)."<br>"; } //////////////////////////////////////////////// $time_start = microtime(true); array_walk($input2,'trim'); $time_end = microtime(true); $time = $time_end - $time_start; echo "Did array_walk in $time seconds<br>"; foreach($input2 as $in){ echo "'$in': ".strlen($in)."<br>"; } //////////////////////////////////////////////// $time_start = microtime(true); foreach($input3 as $in){ $in = trim($in); } $time_end = microtime(true); $time = $time_end - $time_start; echo "Did foreach in $time seconds<br>"; foreach($input3 as $in){ echo "'$in': ".strlen($in)."<br>"; } ``` What Am I Doing Wrong? Here's the output: ``` Did array_map in 0.00018000602722168 seconds 'hello': 5 'whsdf': 5 'lve you': 7 '': 0 Did array_walk in 0.00014209747314453 seconds ' hello ': 10 'whsdf ': 41 ' lve you': 37 ' ': 30 Did foreach in 0.00012993812561035 seconds ' hello ': 10 'whsdf ': 41 ' lve you': 37 ' ': 30 ``` It's not trimming for `array_walk` and the `foreach` loop.
2012/05/05
[ "https://Stackoverflow.com/questions/10458660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1099531/" ]
[`array_walk`](http://php.net/manual/en/function.array-walk.php) doesn't look at what result function gives. Instead it passes callback a reference to item value. So your code for it to work needs to be ``` function walk_trim(&$value) { $value = trim($value); } ``` `foreach` doesn't store changed values itself either. Change it to ``` foreach ($input3 as &$in) { $in = trim($in); } ``` [Read more about references](http://www.php.net/manual/en/language.references.whatdo.php).
524,086
I would appreciate if somebody could help me with the following problem Q. Finding ~~maximum~~ minimum $$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$
2013/10/13
[ "https://math.stackexchange.com/questions/524086", "https://math.stackexchange.com", "https://math.stackexchange.com/users/59343/" ]
By letting $u = \frac xy$ , $v = \frac yz$, and $w = \frac zx$ , our expression becomes $(u + \frac1u) + (v + \frac1v) + (w + \frac1w)$ , whose minimum is thrice that of $f(t) = t + \frac1t$ , which is to be found among the roots of its first order derivative: $f'(t) = 1 - \frac1{t^2}$ , which vanishes for $t = \pm1$ . Since *t* is positive, the only viable solution thus becomes $t = 1$ , for which $f(t) = 1 + \frac11 = 2$ , which yields a minimum value of $3\cdot2 = 6$.
2,193,984
[This page](http://www.ironruby.net/Documentation/.NET/Assemblies) on the IronRuby help website talks about being able to 'require' some well-known assemblies such as System.Windows.Forms without needing to crank out the entire '*ah-come-on-gimme-a-break-here-you-cannot-be-serious*' strong name of the assembly. In the docs it says this: ``` >>> require "System.Windows.Forms" => true ``` But when I try the same 'require', I get this: ``` >>> require "System.Windows.Forms" IronRuby.Libraries:0:in 'require': no such file to load -- System.Windows.Forms (LoadError) from :0:in 'Initialize##1' ``` What might I be doing wrong? Could it be a setup problem? I can't see this "libs directory on the load path" that gets mentioned in the documentation. Is the documentation wrong? Thanks.
2010/02/03
[ "https://Stackoverflow.com/questions/2193984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25457/" ]
Well, it *was* a setup problem - there were two copies of ir.exe in the IronRuby download, and I was using the wrong one.
7,231,649
Let me use an example for what I'm looking for. On my phone I have a music player widget, when active and the phone times out, the player continues working (iPod style I get that). BUT when you turn the phone back on, the player is visible and active above the unlocking slide bar. Is this easy to do in java? giving the user access to the application above the unlock slider (before password). Now I know we can easily put code to avoid sleep mode. But the app that I'm working on only needs to be viewed/modified every 10 or 20 minutes and keeping the phone on is a waste of battery.
2011/08/29
[ "https://Stackoverflow.com/questions/7231649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/693526/" ]
This is a contentious issue: * There are apps that do this. See [How to customize Android's LockScreen?](https://stackoverflow.com/questions/5829671/how-to-customize-androids-lockscreen) e.g. [WidgetLocker](https://play.google.com/store/apps/details?id=com.teslacoilsw.widgetlocker) - so it is not entirely impossible. * However, Google does not recommend playing around with Android Lock Screens. Google has removed functionality for interacting with their OS lock screens (particularly as 2.2). More info on that [here](https://stackoverflow.com/a/5529805/383414). But some useful effects can be managed. There are tricks involved. * One trick is to replace the Android lock screen with a custom lock screen - essentially a Home Screen app that implements its own locking. I think that's how WidgetLocker works, but I'm not sure. There is a Home Screen demo app shipping with the Android SDK. * Another trick is to use the `ACTION_SCREEN_ON` and `ACTION_SCREEN_OFF` Intent actions, coupled with `WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED` permission on your app. You can use these to change what is shown BEHIND *or* instead of the lock screen - which is very close to what the question asks (they need to view some info when the lock screen is in place). I have an app that *displays information to the user when the lock screen is shown*, using the above techniques. Strictly speaking, it is not a custom Android lock screen, however, it creates the effect of customising the information shown when the phone is locked. It shows info *behind the actual stock lock screen*. But you can also replace the screen that normally shows when the phone is locked. --- **Below is a (minimal) demo app that shows how to display information when the phone is locked.** I forget where I got most of the code from, but its a mess of some demo ideas. I present it just to show what can be done - I am by no means saying this is anything like "good" production code. When you run the app, and lock the phone, the app carries on playing the video. This screen replaces the lock screen. It will take some work to turn this code into production code, but it may help readers. YouTubeActivity.java: --------------------- The important part is the last 2 lines that enable this activity to be visible when the phone is locked. ``` package com.youtube.demo; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.view.WindowManager; import android.widget.VideoView; public class YouTubeActivity extends Activity { String SrcPath = "rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQnhycnrJQ8qmRMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYPj_hYjnq6uUTQw=/0/0/0/video.3gp"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); VideoView myVideoView = (VideoView) findViewById(R.id.myvideoview); myVideoView.setVideoURI(Uri.parse(SrcPath)); myVideoView.requestFocus(); myVideoView.start(); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); } } ``` main.xml: --------- Nothing special here - just places a `VideoView` on the screen... ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <VideoView android:id="@+id/myvideoview" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> ``` AndroidManifest.xml: -------------------- Absolutely stock manifest file - nothing interesting here. ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.youtube.demo" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".YouTubeActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> ``` --- So there are **3 ways** I can think of to accomplish what the poster is looking for, or workarounds that might be useful to him: * Do what WidgetLocker does - I don't know how exactly, and the developer is not telling. * Change the background behind the stock lock screen. * Overlay an activity instead of the stock lock screen (demo code provided).
34,143,385
I'm trying to set the `textSize` in sp to `textView` to be seen correctly on all devices. This is my code: ``` <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textSize="30sp" /> ``` On a low resolution device the text is like this: [![enter image description here](https://i.stack.imgur.com/bID6e.png)](https://i.stack.imgur.com/bID6e.png) On a medium resolution device the text is like this: [![enter image description here](https://i.stack.imgur.com/bHkUQ.png)](https://i.stack.imgur.com/bHkUQ.png) On a high resolution device the text is like this: [![enter image description here](https://i.stack.imgur.com/MJdK8.png)](https://i.stack.imgur.com/MJdK8.png) I need that text to be seen correctly on all devices. I tried to use `android:textSize="30dp"` but same result. Where am i wrong? Thnaks!
2015/12/07
[ "https://Stackoverflow.com/questions/34143385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246885/" ]
After taking a short walk and then a fresh look at the code the problem / answer is the linkage of the **mock**/**spy** calls to setup the `doReturn`. Instead of: `spy(new SomeMod())` Use: `PowerMockito.spy(new SomeMod())` This will setup the test(s) according to the docs.
35,479,494
I'm editing a file in vim and my function looks like this: ``` function arrForeignCharacterMapping() { return array( '<8a>'=>'S', '<9a>'=>'s', 'Ð'=>'Dj','<8e>'=>'Z', '<9e>'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', '<83>'=>'f' ); } ``` This is roughly about translating accented characters etc into their "basic" versions. What are the `<8a>` etc though? They're single characters in vim (i.e. shown in a grey colour and the cursor "skips" over them in one movement. I've tried googling them but it's tricky for obvious reasons. If it's "correct", can someone give me a link that correlates these codes with the unicode characters they represent? Thanks!
2016/02/18
[ "https://Stackoverflow.com/questions/35479494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1058739/" ]
you can google "unicode character map", its pretty common so I'm sure you will find many tools and one you would like. this was one of the first results for me: <http://charmap.online-toolz.com/tools/character-map.php> look at the unicode character value, as such: [![enter image description here](https://i.stack.imgur.com/VjqyW.png)](https://i.stack.imgur.com/VjqyW.png)
54,621,210
I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times. *eg: `apple` becomes `aaaappleeee`* It works for every vowel, except for *e*, in which it repeats *e* an egregious amount of times. Python 3. I have tried playing with the replace function, changing the replacement value to `i+i+i+i`, `i*4`, `i(4)`, `(i+i)*2`, but nothing seems to help. ``` def exclamation(string): for i in string: if i in 'aeiou': string = string.replace(i, i*4) return string + '!' ``` `exclamation('excellent')` should return `eeeexceeeelleeeent!` however, it returns: `eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!` As stated, the function works fine for all other vowels, except *e*. Thank you!
2019/02/10
[ "https://Stackoverflow.com/questions/54621210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10951091/" ]
You shall never modify something you're iterating over, store the modified word in a new variable. Modifing your code it would be something like ``` def exclamation(string): new = '' for i in string: if i in 'aeiou': new += i*4 else: new += i return new + '!' ```
65,307,874
Hello I am looking for a way to implement a hierarchical graph in JavaFX, as is the case with a company organization. Ideally, the graph should be in a scrollable pane and the individual nodes of the graph should be able to be displayed (in a different pane) in order to get more information about an employee, etc. The whole thing runs over a database with a UUID system. I've heard of yfiles, VisFX and GraphViz, but somehow it didn't quite work with these methods, as I had imagined. Is there any API that could help me with my problem?
2020/12/15
[ "https://Stackoverflow.com/questions/65307874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11895027/" ]
That depends on what you mean by "graph". If a tree view is sufficient, you can use a JavaFX Tree control to display the hierarchical graph - like a directory structure in an explorer window. If a TreeView is not sufficient, you will have to implement some control yourself. If the information for each node in the graph can fit on a single line of one or more columns, you can also use a JavaFX TreeTableView.
97,092
I am in the process of building myself a fancy schmancy Raspberry Pi "laptop", and am trying to power it with a single cord/power supply. My strategy is to put together a small project box with 120VAC inputs, and the innards from a couple wall warts to provide 5VDC and 12VDC power. Before I start wiring crap together, I wanted to run my idea past some more experienced electri-gurus to make sure I'm not missing anything safety-wise. It seems like its the perfect solution in my mind, but want to make sure I'm not missing anything that I'd be expected to know if I wasn't self-taught. My parts: * I have an old laptop power supply that I've gutted. It's basically the cord and an empty plastic shell (2" x 3" x 5"-ish) with the male end for the plug, and the wires that were clipped from the PCB from the male cord receptacle. * I've gutted 12VDC/2A and 5VDC/10A wall warts; I'm left with PCBs that have wires leading to the board, and barrel connectors coming off the board. If I connect the three hots, the three neutrals and the three grounds from the PCB and power supply inputs, this will leave me with 120VAC feeding the box and getting shared by 2 PCBs that, upon testing SHOULD be putting out 12VDC, 2A and 5VDC, 10A. Am I thinking about that right? In my mind, it's like I've got two wall warts in a power strip, minus the power strip. Here's my power needs: * The Raspberry Pi: 5V, 700-1000mA * A powered USB hub: 5V, 1A (based on the 5V, 1000mA PS that came with it) * A powered USB WiFi interface: 5V, .5A ('cause it's USB...amperage is a TOTAL guess based on no information whatsoever). * A portable USB keyboard: 5V, .5A ('cause it's USB...amperage is a TOTAL guess based on no information whatsoever). * A 4" LCD monitor, 12V, 0.53W (which, by my math is way under 2A). The 12VDC barrel fits the 12V monitor, so that's set. The 5VDC output needs to have the barrel connector replaced, and as long as I'n stripping wires, I'll be adding 3 USB ports to the power supply for device charging, and plan to split the 5VDC output between the individual USBs and the cable that will supply power to the hub--the hub will supply power to all the Raspberry Pi devices, 3A. With 10A supplied, those 3 extra charging ports won't be an issue unless my phone decides to draw 7A+ for charging. Am I good with that concept as well? Please let me know if I'm missing any fundamental safety concepts for putting this thing together, and if appropriate, an appropriate link for where I can research & read about these concepts.
2014/01/20
[ "https://electronics.stackexchange.com/questions/97092", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/10660/" ]
I think this is not a good idea. You should use a 120V power cord attached to a fused power entry module <http://www.digikey.com/product-search/en/connectors-interconnects/power-entry-connectors-inlets-outlets-modules/1442743>, in turn connected to the right 5V/12V AC to DC converter rated for the currents you're interested in. Alternatively, just use a 12V wall wart with a high enough current rating and appropriate DC to DC converters or voltage regulators (linear or switching), with the whole deal fused.
34,659,636
i'm new to meteor framework I want to fetch single from the collection ``` AccountNames = new Mongo.Collection("AccountTypeMaster"); ``` I created a collection using ``` db.createCollection("AccountTypeMaster") this.helpers({ AccountNames: () => { return AccountNames.find({}, {fields: {name: 1}}); } }); ``` Using above query i'm unable to fetch single field "name" from collection. I'm now sure what's wrong with my code.
2016/01/07
[ "https://Stackoverflow.com/questions/34659636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5220060/" ]
You need to change how you instantiate your collection. The correct Meteor syntax would be: ``` AccountNames = new Mongo.Collection("AccountTypeMaster"); ``` Helpers also need to be attached to a template. Remember, helpers only run on client-side code. ``` if (Meteor.isClient) { // This code only runs on the client Template.body.helpers({ tasks: function () { return AccountNames.find({}, { fields: { name: 1 } }); } }); } ```
17,605,290
I have the following 3 tables. This is just a small section of the data, I left out most rows and other columns that I'm not querying against. If it would be helpful to include the full table(s) let me know and I can figure out how to post them. **infocoms** ``` id items_id itemtype value 1735 21 Software 0.0000 1736 22 Software 0.0000 1739 21 Peripheral 151.2500 1741 23 Peripheral 150.5000 1742 24 Peripheral 0.0000 1743 25 Peripheral 0.0000 ``` **locations** ``` id name 34 Anaheim 35 Kirkland 36 Palm Springs 37 Tacoma ``` **peripherals** ``` id name locations_id 11 Logitech USB Wheel Mouse 0 12 Samsung Slate Dock 17 21 USB Scan Gun with Stand 34 23 USB Scan Gun with Stand 63 24 USB Scan Gun with Stand 45 26 USB Scan Gun with Stand 39 ``` I am running the following query against these tables: ``` SELECT peripherals.name, infocoms.value, locations.name AS Branch FROM peripherals JOIN infocoms ON peripherals.id = infocoms.items_id JOIN locations ON peripherals.locations_id = locations.id WHERE (peripherals.name = 'USB Scan Gun with Stand' AND peripherals.locations_id != '0') GROUP BY peripherals.id ORDER BY locations.name ASC ``` I get the right number of rows returned however the value shows everything as 0.0000 instead of where there are actual amounts (151.25 and 150.50). Any help or insight would be greatly appreciated. Thanks.
2013/07/11
[ "https://Stackoverflow.com/questions/17605290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2573866/" ]
Comment (because I do not have the reputation) : "value" and "name" should be encased in back-ticks (``) because they are reserved words. But looking at your code a little closer I find that you are grouping by location.name even though many of the values are duplicated when you do an `JOIN ON peripherals.locations_id = locations.id.` What happens afterwards is that you `GROUP` the rest of the statements by location.name giving the first result of all of the locations that do not have a location name associated to the peripherals.locations\_id Try not using `GROUPING BY` and see what you get. In order to get the results that you want you need to either omit the JOIN ON peripherals.locations\_id = locations.id or associate every peripials.locations\_id to an appropriate locations.id
414,465
Is every $ \mathbb{R}P^{2n} $ bundle over the circle trivial? Are there exactly two $ \mathbb{R}P^{2n+1} $ bundles over the circle? This is a cross-post of (part of) my MSE question <https://math.stackexchange.com/questions/4349052/diffeomorphisms-of-spheres-and-real-projective-spaces> which has been up for a couple weeks and got 8 upvotes and some nice comments but no answers. My intuition for thinking both answer are yes is that there are exactly 2 sphere bundles over the circle. The trivial one and then the non-trivial (and non-orientable) one which can be realized as the mapping torus of an orientation reversing map of the sphere. So importing that intuition to projective spaces then the orientable $ \mathbb{R}P^{2n+1} $ should have a nontrivial (and non orientable) bundle over the circle while the non orientable $ \mathbb{R}P^{2n} $ should have only the trivial bundle. For $ n=1 $ this checks out since that projective space is orientable and thus we have exactly two bundles over the circle (the trivial one=the 2 torus and the nontrivial one=the Klein bottle).
2022/01/23
[ "https://mathoverflow.net/questions/414465", "https://mathoverflow.net", "https://mathoverflow.net/users/387190/" ]
As Sam Hopkins commented, 8 vertices are enough. Let $Q$ be the pentagon from the picture and let $\pi$ be the plane containing it. Now we can define the triangle $P$ as a triangle of less diameter than the black segment and intersecting $\pi$ at two points: one point $a\_0$ in the open blue region $B$ and one point $b\_0$ in the open green region $G$. $P$ and $Q$ are not linked, and it is intuitively clear that they are interlocked, but let´s prove it in detail. [![enter image description here](https://i.stack.imgur.com/c0Tuwm.png)](https://i.stack.imgur.com/c0Tuwm.png) Suppose there is a path of triangles $P\_t=i\_t(P)$ going to infinity, such that $P\_t$ is disjoint with $Q$ for all $t\in[0,\infty)$ and $i\_t:P\to\mathbb{R}^3$ is a continuous path of isometries (continuous in the supremum norm for functions $P\to\mathbb{R}^3$) with $i\_0=Id\_P$. Let´s try to derive a contradiction. **Lemma 1**: Let $i$ be an isometry such that $i(P)$ intersects $\pi$ at exactly two points $a,b$. Then $\forall\varepsilon>0\;\exists\delta>0$ such that for any isometry $j$ with $d(i,j)<\delta$, $j(P)$ intersects $\pi$ at two points $a',b'$, with $d(a,a')<\varepsilon$ and $d(b,b')<\varepsilon$. Proof: First of all, if $d(i,j)$ is small enough, $j(P)$ will intersect $\pi$ in two points, because the images by $j$ of at least two vertices of the triangle will be outside $\pi$. Now consider the function $F(x,y)=$ intersection of the line passing through $x,y$ and $\pi$, defined in an open subset of $\mathbb{R}^6$. This function is continuous in its domain. Suppose $a$ is not a vertex of the triangle. Then it is in the edge formed by two vertices $i(v\_1),i(v\_2)$, each in one half space of $\pi$. By continuity of $F$, if $d(i,j)$ is small enough we have a point $a'=F(j(v\_1),j(v\_2))$ in $j(P)$ at distance $<\varepsilon$ of $a$. So the lemma works when $a,b$ are not vertices of the triangle. $a$ and $b$ cannot both be vertices of the triangle, so suppose $a$ is a vertex, $a=i(v\_1)$ with $v\_1$ a vertex of $P$, and $b$ is not. Then for $d(i,j)$ small enough both $F(j(v\_1),j(v\_2))$ and $F(j(v\_1),j(v\_3))$ will be at distance $<\varepsilon$ from $a$, so the one which is in $j(P)$ will be the point $a'$. $\square$ Now that we are done with the lemma 1, we can define $$k=\sup\{t>0;P\_s\textit{ intersects $\pi$ at two points, one in $B$ and one in $G$, }\forall s\in[0,t)\}.$$ **Lemma 2**: $k>0$, and in $[0,k)$ there are paths $a\_t$, $b\_t$ such that $\{a\_t,b\_t\}=P\_t\cap A\;\forall t<k$. Proof: By lemma 1, there is some $\varepsilon>0$ such that $\forall t\in [0,\varepsilon)$, $P\_t\cap A$ consists on two points, one in $G$ and one in $B$, so $k>0$. Let $a\_t$ be the point in $B$ and $b\_t$ be the point in $B$. By lemma 1 again, $a\_t$ and $b\_t$ are continuous in $[0,\varepsilon)$. Now consider the maximum $\varepsilon$ such that the $a\_t$ and $b\_t$ are defined in $[0,\varepsilon)$. Then $\varepsilon=k$, because if not, by the same argument using lemma 1, $a\_t$ and $b\_t$ will be defined in a neighborhood of $\varepsilon$.$\square$ Now let´s see that $P\_k$ has to intersect $Q$, leading to a contradiction. First of all, $P\_k$ has to intersect $Q$ in at least two points, one point $a\_k\in\overline{B}$ and one point $b\_k\in\overline{D}$. To prove this, let $t\_n$ be an ascending sequence, $t\_n\to k$, such that $a\_{t\_n}$ is convergent. Call $p\_n=i\_{t\_n}^{-1}(a\_n)$, we can suppose that $p\_n$ converges to some point $p\in P$ after taking a subsequence. Finally, we can let $a\_k$ be $i\_k(p)=\lim\_n i\_{t\_n}(p\_n)$, and similarly with $b\_k$. Now we can consider two cases: If $P\_k$ intersects $\pi$ only at $a\_k$ and $b\_k$ we cannot have $a\_k\in A$ and $b\_k\in B$: that would contradict the definition of $k$. So either $a\_k\in\partial B\setminus Q$ and $b\_k\in\overline{G}$ or $b\_k\in\partial G\setminus Q$ and $a\_k\in\overline{B}$. Both cases are impossible, because $d(\partial B\setminus Q, G)$ and $d(\partial G\setminus Q, B)$ are both bigger than the diameter of $P$. So $P\_k$ has to intersect $\pi$ in an edge. For the last time, we will consider two cases: If $a\_k$ and $b\_k$ are both contained in the edge, then the edge intersects $Q$, which is a contradiction. If not, the whole $P$ has to be contained in $\pi$. Consider an edge of the triangle containing the point $a\_k$. As the edge doesn´t intersect $Q$, one of its vertices must be in $B$. There is also other vertex in $G$ (one of the vertices of the edge containing $b\_k$), so the edge joining those two vertices must intersect $Q$, a contradiction.$\\[20pt]$ P.S: I had some comments regarding whether there are $P,Q$ as in the question with $7$ total vertices but they were wrong (I had not considered one case). An argument that they do not exist is given in Del's answer.
58,252
I am currently doing a 3-month paid internship program - it started 3 weeks ago and will be conclusive in 3 months. This company does not promise to provide me with a position afterwards. Now I've received a full-time job offer from another company. * If it ethical to jump ship? * What might some possible consequences be?
2015/11/24
[ "https://workplace.stackexchange.com/questions/58252", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/44326/" ]
Is it a ***nice*** thing to do? **No.** Is it a ***good*** thing to do? **Depends who you're asking.** Make no mistake, you are screwing your boss over by quitting. However, as you yourself have said, the company you're with right now is offering no guarantees whatsoever. That job offer, on the other hand, is **a certainty**. Here's some advice to consider when you're in one of these tricky situations: > > **Always keep your own interests in mind.** > > > Your current employer sure as heck will do the same, and so will every other company you will ever work for - sometimes in your detriment. Don't feel that you should have loyalty to entities which will offer you none in return (aka 99% of all companies out there) My personal opinion is this: > > If you have been offered a full time position and you need it, then **go for it**. > > > The only thing I can't be certain is whether you should give 2 week's notice or not. I think it would make little difference as you've barely been there long enough to get anything done. Sticking around for another 2 weeks is probably simply going to be awkward for everyone involved.
3,672,853
The problem? ``` <UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser> ``` WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values `Doulbe.NaN`. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing. Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time? Edit : Wow, I feel ridiculous. I read about `ActualWidth` and `ActualHeight`, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :)
2010/09/09
[ "https://Stackoverflow.com/questions/3672853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369345/" ]
Try using the [FrameworkElement.ActualWidth](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualwidth.aspx) and [ActualHeight](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualheight.aspx) properties, instead.
54,442,972
I write my API documentation with Spring REST Docs. Code example: ``` @Override public void getById(String urlTemplate, PathParametersSnippet pathParametersSnippet, Object... urlVariables) throws Exception { resultActions = mockMvc.perform(get(urlTemplate, urlVariables) .principal(principal) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(print()); // do.. } ``` But the problem is that the result of the test is answered in one line. And understanding the structure of the returned data is very difficult. Response example: ``` MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/json;charset=UTF-8]} Content type = application/json;charset=UTF-8 Body = {"creator":null,"modifier":null,"modificationTime":null,"creationTime":null,"id":100,"deleted":false,"name":"Name","description":null,"report":[{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"name":"Form name","reportType":{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"deleted":false,"name":"Raport"},"unmodifiable":true}]} Forwarded URL = null Redirected URL = null Cookies = [] ``` Further, I generate documentation from the answer received and in the documentation also unformatted JSON What am I doing wrong? How to enable formatting for json?
2019/01/30
[ "https://Stackoverflow.com/questions/54442972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10499368/" ]
If you're not in a position to configure your application to produce pretty-printed responses, you can have REST Docs do it for you prior to them being documented. This is described in the [Customizing Requests and Responses](https://docs.spring.io/spring-restdocs/docs/2.0.x/reference/html5/#customizing-requests-and-responses) section of the documentation: > > Preprocessing is configured by calling document with an `OperationRequestPreprocessor`, and/or an `OperationResponsePreprocessor`. Instances can be obtained using the static `preprocessRequest` and `preprocessResponse` methods on `Preprocessors`. For example: > > > > ``` > this.mockMvc.perform(get("/")).andExpect(status().isOk()) > .andDo(document("index", preprocessRequest(removeHeaders("Foo")), > preprocessResponse(prettyPrint()))); > > ``` > > In the case above the request is being preprocessed to remove a `Foo` header and the response is being preprocessed so that it appears pretty-printed.
239,478
I have the following tables: [![Part-Product Line relationship](https://i.stack.imgur.com/M6teW.png)](https://i.stack.imgur.com/M6teW.png) Each `ProductLine` will encompass many `Part`s. For this reason, it initially seemed to me that the `Part` table is a child of the `ProductLine` table. However, a part is not simply an extension of a product line, and when I asked myself if it is possible to a part to exist without a product line, the answer seems to be yes. So I'm wondering if the above design appears to be correct or if there is a better design. In the `Part` table, `PartBase` can be thought of as the unique identifier for each part (the part number if you will.) As a somewhat unrelated question, I have these tables set up as a one to many relationship. Since each `Part` must belong to a `ProductLine` but cannot belong to more than one, is it more correct to have this as a one-and-only-one to many relationship? Is the only difference that a `Part` must contain a not null `ProductLineNumber` in the actual database? Is that different from requiring that `ProductLineNumber` be not null? To follow up to @HandyD's comment, as a business rule, every part must belong to exactly one product line. However, when I was thinking about a part as a physical object, it shouldn't need a product line to exist (a product line is just a label after all.) I'm comparing here to how a sale needs a customer to make sense, so that a `Sale` table would more clearly be the child of a `Customer` table. Is this distinction between `Part`-`ProductLine` and `Sale`-`Customer` a false one?
2019/05/30
[ "https://dba.stackexchange.com/questions/239478", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/180524/" ]
If the business requirement is > > a business rule, every part must belong to exactly one product line. > > > So if the rule is, **each part belongs to one product line** the other side of that relationship is **each product line contains zero-to-many parts** which should convince you this is a clear instance of a parent/child relationship. How a something exists in the real world versus how it exists within a business context/database are not always strongly tied. If I have a part on my desk I do not care about it's product line. But if I'm a business and I am selling the part I will probably need to categorize that part for search/reporting/sales/commission purposes. The other columns you will probably need FKs on (PartType, Grade, Family, PopularityCode, UnitClass) will have the same physical implementation (parent table, foreign key reference) even if the context might not be the same (Each Part is described by One Part Type/PartType describes zero-to-many Parts, etc). Won't get into the column types or other aspects of the design because that's not pertinent to the question but I'll be happy to provide guidance elsewhere.
36,318,280
I'm trying to create a runnable JAR from <https://bitbucket.org/madsen953/ethervisu> in Eclipse. When I try to run it I get: ``` Exception in thread "Monitor" java.lang.UnsatisfiedLinkError: no jnetpcap in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1864) at java.lang.Runtime.loadLibrary0(Runtime.java:870) at java.lang.System.loadLibrary(System.java:1122) at org.jnetpcap.Pcap.<clinit>(Unknown Source) at ethervisu.monitors.JNetPcapMonitor.run(JNetPcapMonitor.java:28) at java.lang.Thread.run(Thread.java:745) java.lang.NullPointerException at java.io.DataInputStream.readInt(DataInputStream.java:387) at processing.core.PFont.<init>(Unknown Source) at processing.core.PApplet.loadFont(Unknown Source) at jgv.graphics.JGVGraphics$GraphVisuApplet.setup(JGVGraphics.java:80) at processing.core.PApplet.handleDraw(Unknown Source) at processing.core.PApplet.run(Unknown Source) at java.lang.Thread.run(Thread.java:745) Exception in thread "Animation Thread" java.lang.RuntimeException: Could not load font /data/ArialMT-48.vlw. Make sure that the font has been copied to the data folder of your sketch. at processing.core.PApplet.die(Unknown Source) at processing.core.PApplet.die(Unknown Source) at processing.core.PApplet.loadFont(Unknown Source) at jgv.graphics.JGVGraphics$GraphVisuApplet.setup(JGVGraphics.java:80) at processing.core.PApplet.handleDraw(Unknown Source) at processing.core.PApplet.run(Unknown Source) at java.lang.Thread.run(Thread.java:745) ``` I think this is because I'm unable to preserve the directory structure when creating the JAR. The font files are at the root instead of the `data` directory. How can I fix this?
2016/03/30
[ "https://Stackoverflow.com/questions/36318280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259288/" ]
You need to use a WHERE clause in your update statement. ``` UPDATE wp_posts SET post_content = replace(post_content, 'free', 'free3' ) WHERE post_content LIKE '%blue%' ```
16,469,150
We are supposed to use the code below to print out the parameters listed in it, currently however we are unable to do so and are using a round about method. This is supposed to print out things instead of what we print out in the Game class in the playturn function ``` def __str__(self): x = self.name + ":\t" x += "Card(s):" for y in range(len(self.hand)): x +=self.hand[y].face + self.hand[y].suit + " " if (self.name != "dealer"): x += "\t Money: $" + str(self.money) return(x) ``` Here is our actual code, if you also see any other issues your input would be greatly appreciated ``` from random import* #do we need to address anywhere that all face cards are worth 10? class Card(object): def __init__(self,suit,number): self.number=number self.suit=suit def __str__(self): return '%s'%(self.number) class DeckofCards(object): def __init__(self,deck): self.deck=deck self.shuffledeck=self.shuffle() def shuffle(self): b=[] count=0 while count<len(self.deck): a=randrange(0,len(self.deck)) if a not in b: b.append(self.deck[a]) count+=1 return(b) def deal(self): if len(self.shuffledeck)>0: return(self.shuffledeck.pop(0)) else: shuffle(self) return(self.shuffledeck.pop(0)) class Player(object): def __init__(self,name,hand,inout,money,score,bid): self.name=name self.hand=hand self.inout=inout self.money=money self.score=score self.bid=bid def __str__(self): x = self.name + ":\t" x += "Card(s):" for y in range(len(self.hand)): x +=self.hand[y].face + self.hand[y].suit + " " if (self.name != "dealer"): x += "\t Money: $" + str(self.money) return(x) class Game(object): def __init__(self,deck, player): self.player=Player(player,[],True,100,0,0) self.dealer=Player("Dealer",[],True,100,0,0) self.deck=DeckofCards(deck) self.blackjack= False def blackjacksearch(self): if Game.gettot(self.player.hand)==21:#changed return True else: return False def firstround(self): #self.player.inout=True#do we need this since this is above #self.player.hand=[]#do wee need this.... #self.dealer.hand=[]#do we need this .... self.player.hand.append(DeckofCards.deal(self.deck)) for card in self.player.hand: a=card print(self.player.name + ' ,you were dealt a '+str(a)) self.dealer.hand.append(DeckofCards.deal(self.deck)) for card in self.dealer.hand: a=card print('The Dealer has '+str(a)) playerbid=int(input(self.player.name + ' how much would you like to bet? ')) self.player.money-=playerbid self.player.bid=playerbid def playturn(self): #should this be changed to inout instead of hit.....we never use inout #for player in self.player: # a=player #print(str(a)) hit=input('Would you like to hit? ') #should input be in loop? while self.player.inout==True: #and self.blackjack!=True:#changed print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets self.player.hand.append(DeckofCards.deal(self.deck)) for card in self.player.hand: a=card print('The card that you just drew is: ' + str(a)) #print(Game.gettot(self.player.hand)) hit=input('Would you like to hit? ') if hit=='yes': (self.player.hand.append(DeckofCards.deal(self.deck)))#changed self.player.inout==True# else: (self.player.hand) #changed self.player.inout==False #changed if self.player.blackjack==True: print(self.player.name + " has blackjack ") if hit=='no': print (self.player.hand.gettot()) def playdealer(self): while Game.gettot(self.dealer.hand)<17:#changed self.dealer.hand.append(DeckofCards.deal(self.deck)) dealerhand=Game.gettot(self.dealer.hand) #changed print(dealerhand) if Game.gettot(self.dealer.hand)==21:#changed self.dealer.blackhjack=True dealerhand1=Game.gettot(self.dealer.hand)#changed print(dealerhand1) def gettot(self,hand): total=0 for x in self.hand: if x==Card('H','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('D','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('S','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('C','A'): b=total+x #changed if b>21: total+=1 else: total+=11 else: total+=x return(total) def playgame(self): play = "yes" while (play.lower() == "yes"): self.firstround() self.playturn() if self.player.blackjack == True: print(self.player.name + " got BLACKJACK! ") self.player.money += self.player.bid * 1.5 print (self.player.name + " now has " + str(self.player.money)) print("\n") self.player.inout = False if self.player.score > 21: print(self.player.name + " lost with a tot of " + str(self.player.score)) self.player.money -= self.player.bid print (self.player.name + " now has " + str(self.player.money)) print ("\n\n") self.player.inout = False self.playdealer() if self.dealer.blackjack == True: print("Dealer got blackjack, dealer wins\n") self.player.money -= self.player.bid print("Round\n") print("\t",self.dealer) print("\t",self.player) print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score)) elif self.player.inout == True: print("Round\n") print("\t",self.dealer) print("\t",self.player) print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score)) if self.dealer.score > 21: print("\t Dealer lost with a total of " + str(self.dealer.score)) self.player.money += self.player.bid print(self.player.name + " now has " + str(self.player.money)) elif self.player.score > self.dealer.score: print("\t" +self.player.name + " won with a total of " + str(self.player.score)) self.player.money += self.player.bid print("\t"+self.player.name + " now has " + str(self.player.money)) else: print("\t Dealer won with a total of " + str(self.dealer.score)) self.player.money -= self.player.bid print("\t"+self.player.name + " now has " + str(self.player.money)) else: print("Round") print("\t",self.dealer) print("\t",self.player) if self.player.blackjack == False: print("\t "+ self.player.name + " lost" ) else: print("\t "+self.player.name + " Won!") if self.player.money <= 0: print(self.player.name + " out of money - out of game ") play = "no" else: play = input("\nAnother round? ") print("\n\n") print("\nGame over. ") print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n") print("Thanks for playing. Come back soon!") ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'), Card('H','J'),Card('H','Q'),Card('H','K'), Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'), Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'), Card('S','J'),Card('S','Q'),Card('S','K'), Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'), Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'), Card('C','J'),Card('C','Q'),Card('C','K'), Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'), Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'), Card('D','J'),Card('D','Q'),Card('D','K')] def main(): x = input("Player's name? ") blackjack = Game(ls,x) blackjack.playgame() main() ```
2013/05/09
[ "https://Stackoverflow.com/questions/16469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321264/" ]
The problem is that, in at least some places, you're trying to print a `list`. While printing anything, including a `list`, calls `str` on it, the `list.__str__` method calls `repr` on its elements. (If you don't know the difference between `str` and `rep`, see [Difference between `__str__` and `__repr__` in Python](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python).) If you want to print the `str` of every element in a list, you have to do it explicitly, with a `map` or list comprehension. For example, instead of this: ``` print(self.player.name + ' , your hand has:' + str(self.player.hand)) ``` … do this: ``` print(self.player.name + ' , your hand has:' + [str(card) for card in self.player.hand]) ``` But this is still probably not what you want. You will get `['8', '9']` instead of `[<__main__.Card object at 0x1007aaad0>, <__main__.Card object at 0x1007aaaf0>]`, but you probably wanted something more like `8H 9C'. To do that, you'd want something like: ``` print(self.player.name + ' , your hand has:' + ' '.join(str(card) for card in self.player.hand)) ``` You already have similar (although more verbose) code inside `Player.__str__`: ``` for y in range(len(self.hand)): x +=self.hand[y].face + self.hand[y].suit + " " ``` This code could be improved in a few ways. First, it's going to raise an `AttributeError` because you're using `face` instead of `number`. But really, you shouldn't need to do this at all—the whole reason you created a `Card.__str__` method is so you can just use `str(Card)`, right? Second, you almost never want to loop over `range(len(foo))`, especially if you do `foo[y]` inside the loop. Just loop over `foo` directly. Putting that together: ``` for card in self.hand: x += str(card) + " " ``` At any rate, you need to do the same thing in both places. The version that uses the `join` method and a generator expression is a little simpler than the explicit loop, but does require a bit more Python knowledge to understand. Here's how you'd use it here: ``` x += " ".join(str(card) for card in self.hand) + " " ``` --- Your next problem is that `Card.__str__` doesn't include the suit. So, instead of `8H 9C`, you're going to get `8 9`. That should be an easy fix to do on your own. --- Meanwhile, if you find yourself writing the same code more than once, you probably want to abstract it out. You *could* just write a function that takes a hand `list` and turns it into a string: ``` def str_hand(hand): return " ".join(str(card) for card in self.hand) ``` But it might be even better to create a `Hand` class that wraps up a list of cards, and pass that around, instead of using a `list` directly.
65,753,830
I'm trying to train Mask-R CNN model from cocoapi(<https://github.com/cocodataset/cocoapi>), and this error code keep come out. ``` ModuleNotFoundError Traceback (most recent call last) <ipython-input-8-83356bb9cf95> in <module> 19 sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version 20 ---> 21 from pycocotools.coco import coco 22 23 get_ipython().run_line_magic('matplotlib', 'inline ') ~/Desktop/coco/PythonAPI/pycocotools/coco.py in <module> 53 import copy 54 import itertools ---> 55 from . import mask as maskUtils 56 import os 57 from collections import defaultdict ~/Desktop/coco/PythonAPI/pycocotools/mask.py in <module> 1 __author__ = 'tsungyi' 2 ----> 3 import pycocotools._mask as _mask 4 5 # Interface for manipulating masks stored in RLE format. ModuleNotFoundError: No module named 'pycocotools._mask' ``` I tried all the methods on the github 'issues' tab, but it is not working to me at all. Is there are another solution for this? I'm using Python 3.6, Linux.
2021/01/16
[ "https://Stackoverflow.com/questions/65753830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14258016/" ]
The answer is summarise from [these](https://github.com/cocodataset/cocoapi/issues/172) [three](https://github.com/cocodataset/cocoapi/issues/168) [GitHub issues](https://github.com/cocodataset/cocoapi/issues/141#issuecomment-386606299) 1.whether you have installed cython in the correct version. Namely, you should install cython for python2/3 if you use python2/3 ``` pip install cython ``` 2.whether you have downloaded the whole .zip file from this github project. Namely, you should download all the things here even though you only need PythonAPI ``` git clone https://github.com/cocodataset/cocoapi.git ``` or unzip the [zip file](https://github.com/cocodataset/cocoapi/archive/refs/heads/master.zip) 3.whether you open Terminal and run "make" under the correct folder. The correct folder is the one that "Makefile" is located in ``` cd path/to/coco/PythonAPI/Makefile make ``` Almost, the question can be solved. If not, 4 and 5 may help. 4.whether you have already installed gcc in the correct version 5.whether you have already installed python-dev in the correct version. Namely you should install python3-dev (you may try "sudo apt-get install python3-dev"), if you use python3.
73,039,121
With great help from @pratik-wadekar I have the following working text animation. Now my problem is that when I test it on different screen sizes/mobile the animated word `plants` breaks into pieces. For example PLA and in the next line NTS. How can I avoid this? So it always keeps as one full word. First I tried to add `\xC2\xA0 – non-breaking space or &nbsp;` before and after the word but this doesnt help. The CSS `word-wrap` property allows long words to be able to break but unfortunately for the reverse case to make a word unbreakable there is no option. It seems that the CSS `word-break: "keep-all` property is what I need but when I apply it, it still breaks into pieces on smaller screens. The [Codepen](https://codesandbox.io/s/lucid-mclaren-qytt3q?file=/src/App.tsx:0-1271) And `App.tsx`: ``` import React from "react"; import { styled } from "@mui/material/styles"; import { Typography } from "@mui/material"; const AnimatedTypography = styled(Typography)` & { position: relative; -webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0, 0, 0, 0.2)); font-size: 60px; } & span { color: #fbbf2c; font-family: "Alfa Slab One", sans-serif; position: relative; display: inline-block; text-transform: uppercase; animation: waviy 1s infinite; animation-delay: calc(0.1s * var(--i)); } @keyframes waviy { 0%, 40%, 100% { transform: translateY(0); } 20% { transform: translateY(-20px); } } `; interface Styles extends React.CSSProperties { "--i": number; } function App() { const string = "plants"; return ( <Typography variant={"h3"} fontWeight={"bold"}> All Your <AnimatedTypography> {string.split("").map((char, idx) => { const styles: Styles = { "--i": idx + 1 }; return ( <span key={`${char}-${idx}`} style={styles}> {char} </span> ); })} </AnimatedTypography> in One Place </Typography> ); } export default App; ```
2022/07/19
[ "https://Stackoverflow.com/questions/73039121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ok I got it. I had to make the animation as own component and add the `<AnimatedTypography>` the `component={"span"}` type and `white-space: nowrap`. Additionally to my `const AnimatedTypography = styled(Typography)` I had to cast the resulting component with `as typeof Typograph`y so Typescript does not throws errors. See here: [Complications with the component prop](https://mui.com/material-ui/guides/typescript/#usage-of-component-prop) Then importing the component and addind into the Typography component between my text. Now the layout of my text is preserved and the animation does not split into single characters.
23,423,572
As title says, why does Rails prefer to use the @params variable inside of a Controller action when you are responding to the action instead of passing the individual parameters through the function arguments when we call the function? Other frameworks use this (i.e, ASP MVC) and I was just wondering if there was a reason for that design decision, because it doesn't seem very intuitive. Ie. Why does Rails do ``` def index name = params[:name] end ``` Instead of ``` def index(name) end ```
2014/05/02
[ "https://Stackoverflow.com/questions/23423572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073868/" ]
The Maven command `mvn eclipse:eclipse` generate the eclipse project files from POM. The "-D" prefix in the argument means that it's a system property. System property are defined like `http://docs.oracle.com/javase/jndi/tutorial/beyond/env/source.html#SYS` `mvn eclipse:eclipse -Dwtpversion=2.0` command convert the web based java project to maven based java project to support Eclipse IDE. You can simple use given below command to clean and build your project: `mvn clean` and `mvn install` OR **`mvn clean install`** Suggestion: Check maven is installed properly using command `mvn --version`.
40,925,951
In our WPF software, we used a `ControlTemplate` which defines a `ToggleButton` that causes the window to shrink/extend. The definition of `ToggleButton` is given below: ```xml <ToggleButton ToolTip="Standard/Extended" Grid.Column="0" x:Name="PART_MaximizeToggle" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,5,5,0" Width="14" Height="14" Cursor="Hand"> ``` We're creating a custom `DockPanel` which contains this button at the upper right corner. Our application can contain up to three of this `DockPanel`s at the same time: [![DockPanel screenshots](https://i.stack.imgur.com/FFsTH.png)](https://i.stack.imgur.com/FFsTH.png) The small rectangle on the right of each `DockPanel` is shown in the image above. Notice from the definition that all three of the rectangles have same name: `"PART_MaximizeToggle"`. This causes trouble when writing CodedUI programs to automate testing. CodedUI captures all of their FriendlyNames as `"PART_MaximizeToggle"` with Name field empty. The locations and sequence of the `DockPanel`s can change based or what the user want. How can we make CodedUI capture exact the button where a click is expected? I was thinking of making the `Name` of each toggle button dynamic but fixed for a specific `DockPanel`. How can I do that? Is there a better approach?
2016/12/02
[ "https://Stackoverflow.com/questions/40925951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68304/" ]
You could assign ([and register](https://msdn.microsoft.com/en-us/library/system.windows.frameworkcontentelement.registername.aspx)) the names automatically via an [AttachedProperty](https://msdn.microsoft.com/en-us/library/ms749011(v=vs.110).aspx) that increments a counter for each prefix. (This is just a proof of concept, you should also check that the names are valid) ``` public static class TestingProperties { private static readonly Dictionary<string, int> _counter = new Dictionary<string, int>(); public static readonly DependencyProperty AutoNameProperty = DependencyProperty.RegisterAttached( "AutoName", typeof(string), typeof(TestingProperties), new PropertyMetadata(default(string), OnAutoNamePropertyChanged)); private static void OnAutoNamePropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs eventArgs) { string value = (string) eventArgs.NewValue; if (String.IsNullOrWhiteSpace(value)) return; if (DesignerProperties.GetIsInDesignMode(element)) return; if (!(element is FrameworkElement)) return; int index = 0; if (!_counter.ContainsKey(value)) _counter.Add(value, index); else index = ++_counter[value]; string name = String.Format("{0}_{1}", value, index); ((FrameworkElement)element).Name = name; ((FrameworkElement)element).RegisterName(name, element); } public static void SetAutoName(DependencyObject element, string value) { element.SetValue(AutoNameProperty, value); } public static string GetAutoName(DependencyObject element) { return (string)element.GetValue(AutoNameProperty); } } ``` Usage in XAML: ```xml <!-- will be Button_0 --> <Button namespace:TestingProperties.AutoName="Button"/> <!-- will be Button_1 --> <Button namespace:TestingProperties.AutoName="Button"/> <!-- will be Button_2 --> <Button namespace:TestingProperties.AutoName="Button"/> ``` Resulting Visual-Tree: ![VisualTree of Example](https://i.stack.imgur.com/sKahi.jpg)
20,810,059
Is it good practice to declare variables to be used across a program in a Module then populate them in one form and use what you have populated to these variables in another form? I plan on closing the population form after the data has been populated to the variables so I see this as the only method that would work. Am I right in thinking that passing parameters from the population form to the display form wouldn't be appropriate in this situation, if even possible?
2013/12/28
[ "https://Stackoverflow.com/questions/20810059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2177940/" ]
I guess it **depends** on your application and the kind of data you're talking about. Think of a `User Login form` that saves the user information after logging in. You can then keep this information in a Module shared across your entire application because it's not expected to change during the session. So you can quickly check the Permission, the Role, the Username from all your program Forms. On the other end if you're querying a database you are probably asking for the latest data available and you do that in the specific Form you're using, without the need to share it across other Forms in the program.
60,803,621
I'm having a little trouble figuring out a nested for loop here. Here's the problem: > > 3. The population of Ireland is 4.8 million and growing at a rate of 7% per year. Write a program to determine and display the population > in 10 years time. Your program should also display a count of the > number of years that the population is predicted to exceed 5 million. > > > And here's what I've coded so far: ``` double pop = 4.8; int years = 0; for (int i = 0; i < 10; i++) { pop += (pop / 100) * 7; for (int j = 0; pop >5; j++) { years += j; } } Console.WriteLine("Pop in year 2030 is " + Math.Round(pop, 2) + " million and the population will be over 5 million for " + years + " years."); } ``` Now to be clear, I need the sum of the years in which population exceeds 5(million) (the answer is 10) and I must only use for loops to solve this problem. I'm thinking the answer is a nested for loop, but have tried and tried with no success. Can anyone help me on where I've screwed this up?
2020/03/22
[ "https://Stackoverflow.com/questions/60803621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13105750/" ]
Look at your inner loop. ``` for (int j = 0; pop >5; j++) { years += j; } ``` Your condition being `pop > 5`, you need `pop` to shrink if you ever want to exit the loop. But the body of the loop never alters `pop`, so if it's greater than 5, you'll loop forever. The problem definition suggests that you don't need an inner loop at all. Just check `pop`, and if it's greater than 5, increment `years`. ``` if (pop > 5) { ++years; } ``` If you're really under such an insane restriction that you can't use `if`, you could do something boneheaded like create a `for` loop that only runs once if your other condition is right. ``` for (int j = 0; j < 1 && pop > 5; ++j) { ++years; } ``` but no sane person does this.
16,688,245
I'm trying to deploy my app on heroku. But everytime I try to push my database, I get the following error: ``` heroku db:push Sending schema Schema: 100% |==========================================| Time: 00:00:16 Sending indexes refinery_page: 100% |==========================================| Time: 00:00:02 refinery_page: 100% |==========================================| Time: 00:00:01 refinery_page: 100% |==========================================| Time: 00:00:01 refinery_page: 100% |==========================================| Time: 00:00:04 refinery_role: 100% |==========================================| Time: 00:00:01 refinery_user: 100% |==========================================| Time: 00:00:01 refinery_user: 100% |==========================================| Time: 00:00:00 seo_meta: 100% |==========================================| Time: 00:00:01 schema_migrat: 100% |==========================================| Time: 00:00:00 Sending data 14 tables, 49 records refinery_arti: 0% | Saving session to push_201305220223.dat.. !!! Caught Server Exception HTTP CODE: 500 Taps Server Error: LoadError: no such file to load -- sequel/adapters/ ["/app/.bundle/gems/ruby/1.9.1/gems/sequel-3.20.0/lib/sequel/core.rb:249:in `require'", ... ``` I use Rails 3.2.13, Ruby 1.9.3, refinerycms and mysql lite. I also tried to install missing gems ... Is this a fault of heroku? Or am I just stupid? :-) my gem file: ``` source 'https://rubygems.org' gem 'rails', '3.2.13' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' group :development, :test do gem 'sqlite3' end group :production do gem 'pg' end # Gems used only for assets and not required # in production environments by default. group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', :platforms => :ruby gem 'uglifier', '>= 1.0.3' end gem 'jquery-rails', '~> 2.0.0' # To use ActiveModel has_secure_password # gem 'bcrypt-ruby', '~> 3.0.0' # To use Jbuilder templates for JSON # gem 'jbuilder' # Use unicorn as the app server # gem 'unicorn' # Deploy with Capistrano # gem 'capistrano' # To use debugger # gem 'debugger' # Refinery CMS gem 'refinerycms', '~> 2.0.0', :git => 'git://github.com/refinery/refinerycms.git', :branch => '2-0-stable' # Specify additional Refinery CMS Extensions here (all optional): gem 'refinerycms-i18n', '~> 2.0.0' # gem 'refinerycms-blog', '~> 2.0.0' # gem 'refinerycms-inquiries', '~> 2.0.0' # gem 'refinerycms-search', '~> 2.0.0' # gem 'refinerycms-page-images', '~> 2.0.0' gem 'refinerycms-articles', :path => 'vendor/extensions' ``` database.yml: ``` # SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000 production: adapter: sqlite3 database: db/production.sqlite3 pool: 5 timeout: 5000 ```
2013/05/22
[ "https://Stackoverflow.com/questions/16688245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458773/" ]
I too had same problem, but i solved with these lines. To my knowledge we cannot request a session for new permissions which is already opened. ``` Session session = new Session(this); Session.setActiveSession(session); session.openForRead(new Session.OpenRequest(this).setCallback(callback).setPermissions(Arrays.asList("your_permissions"))); ``` I hope you already added below line in `onActivityResult()` ``` Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data); ```
15,469,904
I need to set up a listener that can call a method every time a `show()` method is invoked to display a window. How can I do this?
2013/03/18
[ "https://Stackoverflow.com/questions/15469904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2172496/" ]
You'd probably be interested in `WindowListener`. From [the tutorial, "How to Write Window Listeners"](http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html): > > The following window activities or states can precede a window event: > > > * Opening a window — Showing a window for the first time. > * Closing a window — Removing the window from the screen. > * Iconifying a window — Reducing the window to an icon on the desktop. > * Deiconifying a window — Restoring the window to its original size. > * Focused window — The window which contains the "focus owner". > * Activated window (frame or dialog) — This window is either the focused window, or owns the focused window. > * Deactivated window — This window has lost the focus. For more information about focus, see the AWT Focus Subsystem specification. > > > If you don't want to have to implement all of them, you could use a [`WindowAdapter`](http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowAdapter.html), as follows: ``` myFrame.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent we) { System.out.println("this window was opened for the first time"); } @Override public void windowActivated(WindowEvent we) { System.out.println("this window or a subframe was focused"); } }); ```
60,747,796
I have a simple table ``` **targeted_url_redirect targeted_countries msg_type non_targeted_url** http://new.botweet.com india,nepal,philippines NEW http://twisend.com http://expapers.com United States,Canada OLD http://all.twisend.com https://tweeasy.com india,england OLD http://all.twisend.com ``` I receive traffics on my website `followerise.com` and I want to redirect users to specific urls based on their countries as defined in the above table. I am able to write query to get rows for the users who coming from the countries that are target stored in my database. But I am looking for a solution to get all the rows if the `targeted_countries` condition not return any rows. I written below queries. ``` SELECT * FROM tweeasy_website_redirection WHERE message_type='OLD' AND targeted_countries LIKE '%@country%' ``` This query gives me desired rows if visitor coming from the countries `india`,`england`,`United States`,`Canada` But I want all rows (2nd and 3rd) should be fetched if a user coming from the countries not specified in `targeted_countries` column. Also let me know if I need to restructure this table into 2 or more tables to get desired result.
2020/03/18
[ "https://Stackoverflow.com/questions/60747796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2014130/" ]
One option uses `not exists`: ``` SELECT t.* FROM tweeasy_website_redirection t WHERE t.message_type = 'OLD' AND ( t.targeted_countries LIKE '%@country%' OR NOT EXISTS ( SELECT 1 FROM tweeasy_website_redirection t1 WHERE t1.targeted_countries LIKE '%@country%' ) ) ``` When it comes to the structure of your table: one design flaw is to store list of values as CSV list. You should have two separate tables: one to store the urls, and the other to store the 1-N relationship between urls and countries. Something like: ``` table "url" id targeted_url_redirect msg_type non_targeted_url 1 http://new.botweet.com NEW http://twisend.com 2 http://expapers.com OLD http://all.twisend.com 3 https://tweeasy.com OLD http://all.twisend.com table "url_countries" url_id country 1 india 1 nepal 1 philippines 2 united states 2 canada 3 india 3 england ```
42,549,008
what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ... ``` @Injectable() export class AppGlobals { public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null); setLoginStatus(isLoggedIn) { this.isUserLoggedIn.next(isLoggedIn); } setCurrentUser(currentUser) { this.currentUser.next(currentUser); } } ``` In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login ``` login() { this.authenticationService.login(this.model.username, this.model.password) .subscribe( data => { this.appGlobals.setLoginStatus(true); this.appGlobals.setCurrentUser(data); this.router.navigate([this.returnUrl]); }, error => { this.alertService.error(error); this.loading = false; }); } ``` and accessing the value in other component .... ``` export class ProductsComponent { currentUser: User; isLoggedIn: boolean; constructor(private productService: ProductService, private router:Router, private confirmationService: ConfirmationService, private auth: AuthenticationService, private appGlobal: AppGlobals) { appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data ..... } ..... } ``` In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks.
2017/03/02
[ "https://Stackoverflow.com/questions/42549008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1653027/" ]
Simply, follow the instructions given in the error: Download miniconda, then run the script file by typing following command: `bash <file_name.sh>` e.g. `bash Miniconda3-latest-Linux-x86_64.sh`. Now reopen the terminal for the changes to take effect. If conda is already installed on your system, you can reinstall it with the `-f` force option, for example, `bash Miniconda3-latest-Linux-x86_64.sh -f` To test your installation, enter the command `conda --version`. If installed correctly, you will see the version of conda installed. miniconda: <https://conda.io/en/latest/miniconda.html> conda troubleshooting: <https://conda.io/docs/troubleshooting.html>
56,197,545
I have Tab navigator that handles data changing of itself and other two sibling component. **Main parent Component** that does data fetching and manipulation based on three sentiments: positive, negative and neutral as request body parameter in *http post request*. **Second parent component** that stores all positive data, negative data and neutral data from main parent component. Then **three** **Child Components**: **Table one and Tab Navigation**. The Tab navigation has three three tabs namely: *Positive, Negative and Neutral*. As soon as the page renders on first load, by default (without clicking positive tab button), it fetches positive data and displays it in all three child components. Then on clicking on Negative tab, it should display negative data in all three child components i.e. Table one and under negative tab of tab navigation. Same thing follows for Neutral Tab. In short, Tab navigation handles data rendering of it's self and sibling components based on its active state and getting that data from parent component. I tried passing the active event from tab navigation to its upper container but it doesn't seem to work fine. Tab.js ``` import React, { Component } from 'react'; export default class Tab extends Component { constructor(props) { super(props); this.state = { active: 'positive', } } toggle = (event) => { this.setState({ active: event }) this.props.sendEvent(this.state.active); } get_tab_content =()=> { switch(this.state.active) { case 'positive': return <div><SomeDataComponent1 positiveprops={} /></div>; case 'negative': return <div><SomeDataComponent2 negativeprops={}/></div>; case 'neutral': return <div><SomeDataComponent3 neutralprops={} /></div>; default : } } render() { const tabStyles = { display: 'flex', justifyContent: 'center', listStyleType: 'none', cursor: 'pointer', width: '100px', padding: 5, margin: 4, fontSize: 20, color: 'green' } const tabStyles2 = { display: 'flex', justifyContent: 'center', listStyleType: 'none', cursor: 'pointer', width: '100px', padding: 5, margin: 4, fontSize: 20, color: 'red' } const tabStyles3 = { display: 'flex', justifyContent: 'center', listStyleType: 'none', cursor: 'pointer', width: '100px', padding: 5, margin: 4, fontSize: 20, color: 'yellow' } const linkStyles = { display: 'flex', justifyContent: 'center', color: '#000', listStyleType: 'none' } const divStyle = { border: '1px solid #34baa2', width: '450px' } const box = this.get_tab_content() return ( <div style={divStyle} > <ul style={linkStyles}> <li style={tabStyles} onClick={function(){this.toggle('positive')}.bind(this)}>Positive</li> <li style={tabStyles2} onClick={function(){this.toggle('negative')}.bind(this)}>Negative</li> <li style={tabStyles3} onClick={function(){this.toggle('neutral')}.bind(this)}>Neutral</li> </ul> <div> {box} </div> </div> ); } } ``` Second Parent Component.js ``` import React,{Component} from 'react'; import Tab from '../tab/tab'; import MentionTable from '../table/table'; class DataCharts extends Component{ constructor(props){ super(props); this.state = { childEvent: '' } } getEvent = (childevent) => { this.setState({ childEvent: childevent }); console.log(this.state.childEvent) } render(){ const {positivetable,positivewords, negativetable, negativewords, neutraltable, neutralwords } = this.props; return( <div style={{display:'flex', flexDirection: 'row'}}> <Table /> <Tab sendEvent={this.getEvent}/> </div> ) } } export default DataCharts; ```
2019/05/18
[ "https://Stackoverflow.com/questions/56197545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11349591/" ]
You need **urgently** research about SQL injection, and **STOP USING** string concatenation for building your SQL insert statement **RIGHT NOW**. You need to use the proper technique - **parametrized queries** -- always - **NO** exceptions! And also, it's a commonly accepted Best Practice to list the columns in your `INSERT` statement, to avoid trouble when tables change their columns (read more about this here: [Bad habits to kick: using SELECT \* / omit the column list](http://sqlblog.org/2009/10/10/bad-habits-to-kick-using-select-omitting-the-column-list.aspx) ). Use this code as a sample/template: ``` string insertQuery = @"INSERT INTO dbo.Table1 (FirstName, LastName, City) VALUES (@FirstName, @LastName, @City);"; using (SqlCommand cmd = new SqlCommmand(insertQuery, con)) { cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstname.Text; cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = lastname.Text; cmd.Parameters.Add("@City", SqlDbType.VarChar, 50).Value = city.Text; con.Open(); cmd.ExecuteNonQuery(); con.Close() } ```
72,862,776
I am trying to put together a diagram in CSS of a flow chart. I have attached below a picture. Is there a simple way to do this? I've been Googling around quite a bit looking for examples, but I don't know what to call this. Can you please let me know how to do this? Or if this is something common, what I can Google to find more information. [![enter image description here](https://i.stack.imgur.com/K2QXT.png)](https://i.stack.imgur.com/K2QXT.png)
2022/07/04
[ "https://Stackoverflow.com/questions/72862776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7053813/" ]
By using [CSS Flex](https://developer.mozilla.org/en-US/docs/Web/CSS/flex) you could achieve something like: ```css body {font: 16px/1.4 sans-serif;} .chart-row, .chart-col { display: flex; gap: 1em; } .chart-row { flex-direction: row; } .chart-col { flex-direction: column; } .chart-pill, .chart-rect{ padding: 1em; text-align: center; border: 2px solid #999; } .chart-pill { flex: 1; border-radius: 1em; border-style: dashed; } .chart-rect{ flex: 0; margin: auto 0; background: #eee; } .chart-line-h { height: 2px; min-width: 3em; background: #999; margin: auto -1em; } ``` ```html <div class="chart-row"> <div class="chart-pill chart-col"> <div class="chart-rect">alpha</div> </div> <div class="chart-line-h"></div> <div class="chart-pill chart-col"> <div class="chart-rect">beta</div> <div class="chart-rect">gamma</div> <div class="chart-rect">delta</div> </div> <div class="chart-line-h"></div> <div class="chart-pill chart-col"> <div class="chart-rect">gamma</div> </div> </div> ```
41,318,581
I'm using a random number generator and IF Statements to switch between activities. It iterates through the first if statement and stops there. I don't think my random number generator is generating any random numbers. Thanks in advance. ``` package app.com.example.android.oraclethedeciscionmaker; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import java.util.Random; public class HomeScreen extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_screen); } public void onClick(View view){ Random guess = new Random(); int guesser0 = guess.nextInt(0) + 1; int guesser1 = guess.nextInt(0) + 1; int guesser2 = guess.nextInt(0) + 1; int guesser3 = guess.nextInt(0) + 1; int guesser4 = guess.nextInt(0) + 1; int result = guesser0 + guesser1 + guesser2 + guesser3 + guesser4; // 0 out of 0 if(result == 0){ Intent intent = new Intent(HomeScreen.this, ZeroOfFive.class); startActivity(intent); // If this statement is true go to this activity } // 1 out of 5 else if(result == 1){ Intent intent = new Intent(HomeScreen.this, OneOfFive.class); startActivity(intent); // If this statement is true go to this activity } //2 out of 5 else if(result == 2){ Intent intent = new Intent(HomeScreen.this, TwoOfFive.class); startActivity(intent); // If this statement is true go to this activity } //3 out of 5 else if(result == 3){ Intent intent = new Intent(HomeScreen.this, ThreeOfFive.class); startActivity(intent); // If this statement is true go to this activity } //4 out of 5 else if(result == 4){ Intent intent = new Intent(HomeScreen.this, FourOfFive.class); startActivity(intent); // If this statement is true go to this activity } //5 out of 5 else { Intent intent = new Intent(HomeScreen.this, FiveOfFive.class); startActivity(intent); } } } ```
2016/12/25
[ "https://Stackoverflow.com/questions/41318581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6191311/" ]
The only thing I did was instead of using a path like ``` c:\xyz\desktop\practice ``` and starting http-server, I did the following: step 1: ``` c:\ ``` step 2: ``` http-server c:\xyz\desktop\practice ``` It started working. Thanks for everyone's help.
1,451,281
I'm just starting, and yes, i haven't written any tests yet (I'm not a fundamentalist, I don't like compile errors just because there is no test), but I'm wondering where to get started on doing a project that parses fixed length flat file records according to an XML mapping, into a class that represents the superset of all file layouts, before writing (with transformation) the class details to a DB table. There are so many external factors, and I don't want to mock them all, so where or how would be a good way to start test driving this project?
2009/09/20
[ "https://Stackoverflow.com/questions/1451281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
It's all about decomposing the problem into parts. Some examples: * File/stream reader * Input mapper * Input mapper loader * File layout * File layout collection * Data access layer Try to give each class a single responsibility, determine its dependencies, and inject those in. That, with the help of mocks/stubs, will permit you to test each class in isolation.
71,793,245
Is there a standard algorithm in the library that does the job of the following for-loop? ``` #include <iostream> #include <vector> #include <iterator> #include <algorithm> int main( ) { const char oldFillCharacter { '-' }; std::vector<char> vec( 10, oldFillCharacter ); // construct with 10 chars // modify some of the elements vec[1] = 'e'; vec[7] = 'x'; vec[9] = '{'; const char newFillCharacter { '#' }; for ( auto& elem : vec ) // change the fill character of the container { if ( elem == oldFillCharacter ) { elem = newFillCharacter; } } // output to stdout std::copy( std::begin( vec ), std::end( vec ), std::ostream_iterator<char>( std::cout, " " ) ); std::cout << '\n'; /* prints: # e # # # # # x # { */ } ``` I want to replace the above *range-based for-loop* with a **one-liner** if possible. Is there any function that does this? I looked at [std::for\_each](https://en.cppreference.com/w/cpp/algorithm/for_each) but I guess it's not suitable for such a scenario.
2022/04/08
[ "https://Stackoverflow.com/questions/71793245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13407802/" ]
This loop will replace every occurrence of `oldFillCharacter` with `newFillCharacter`. If you don't want to do something more fancy [`std::replace`](https://en.cppreference.com/w/cpp/algorithm/replace) looks good: ``` std::replace(std::begin(vec), std::end(vec), oldFillCharacter, newFillCharacter); ``` Or a bit simpler with [`std::ranges::replace`](https://en.cppreference.com/w/cpp/algorithm/ranges/replace): ``` std::ranges::replace(vec, oldFillCharacter, newFillCharacter); ```
1,648,939
i ran jconsole, i see some live threads count and daemon threads count .... i run no other java app/classes .... i could see the list of live threads but not daemon thread .... is there a way to know what is the list of deamon threads ?
2009/10/30
[ "https://Stackoverflow.com/questions/1648939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can create a thread dump (using the `jstack` tool), which will show for each thread whether it is a daemon or not. Instead of using `jstack` on the command line, you can also trigger a thread dump using visualvm (<http://visualvm.dev.java.net>), and look at the threads over time.
64,601,439
I am new to HTML and CSS. I want to achieve rounded-corner for my table and it is not working. Any ideas how can I make it work? Here is my CSS for table: ``` table { border: 1px solid #CCC; border-collapse: collapse; font-size:13px; color:white; } td { border: none; } ``` Currently, it looks like this: [![enter image description here](https://i.stack.imgur.com/Ce5NO.png)](https://i.stack.imgur.com/Ce5NO.png) And I want the corner of the table to be rounded. Many thanks.
2020/10/30
[ "https://Stackoverflow.com/questions/64601439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11471461/" ]
You can make the rounded table using the `border-radius` CSS attribute based on `border-collapse: separate` as follows. ```css table { border: 1px solid #CCC; font-size: 13px; color: white; background: red; border-collapse: separate; border-radius: 10px; -moz-border-radius: 10px; } td { border: none; } ``` ```html <table border="1"> <tr> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <tr> <tr> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <tr> <tr> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <tr> <tr> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <td>Hello World</td> <tr> </table> ```
16,875,356
I am successfully detecting faces using JavaCV, it's not totally accurate but good enough for the moment. However, for testing purposes and with a look at the future (this is only part of a bigger group project), I want to write rectangles onto the faces using BufferedImage and Graphics.drawRect(). I am aware of the fact that you can draw rects to faces using JavaCV with the static methods, but it's not what I need / want to do. If I, after the scanning process, try to load the image using ImageIO and try to write rects to it, the application ends with a native error. **Is there any way I can command openCV to "release" the image (because I think that's the soruce of the problem, that opencv does not release the image file.) ?** Thanks in advance edit: error code: ``` # A fatal error has been detected by the Java Runtime Environment: # # SIGSEGV (0xb) at pc=0x00007fc705dafac4, pid=8216, tid=140493568964352 # # JRE version: 7.0_21-b02 # Java VM: OpenJDK 64-Bit Server VM (23.7-b01 mixed mode linux-amd64 compressed oops) # Problematic frame: # C [libjpeg.so.8+0x1eac4] jpeg_save_markers+0x84 ``` edit: ``` cvReleaseImage(inputImage); cvReleaseImage(grayImage); cvClearMemStorage(storage); ``` didnt help too
2013/06/01
[ "https://Stackoverflow.com/questions/16875356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1342579/" ]
Quoting from the [paperjs.org tutorial on rasters](http://paperjs.org/tutorials/images/working-with-rasters/): > > Images need to already be loaded when they are added to a Paper.js project. Working with local images or images hosted on other websites may throw security exceptions on certain browsers. > > > So you need an image somewhere that is preferably [visually hidden](https://github.com/h5bp/html5-boilerplate/blob/a20a3c76d541d40ffb75a8f02c8c0f7b05773e51/css/main.css#L127-L136): ``` <img id="mona" class="visuallyhidden" src="mona.jpg" width="320" height="491"> ``` And the [PaperScript](http://paperjs.org/tutorials/getting-started/working-with-paper-js/) code could look like this: ``` // Create a raster item using the image tag with id="mona" var raster = new Raster('mona'); ``` Then you can reposition, scale or rotate like so: ``` // Move the raster to the center of the view raster.position = view.center; // Scale the raster by 50% raster.scale(0.5); // Rotate the raster by 45 degrees: raster.rotate(45); ``` And here is a [paperjs.org sketch](http://sketch.paperjs.org/#S/VY9BbwIhEIX/yoSkcZtU8KAXG0/GYy965YIw3UV3gcDoxjT97wXWbmK48Jj3vnn8MKcGZFt2uiLpjn0w7U3RdxXBDi3swHh9G9AR1xEV4aHHohrJ8liy90/p8oWnqLNXso4obIUIKmC8JO5jK+hGPlrVJ2EH1WISo49X69rlaKlbRpUIYxKDd4pfQkY+idZUYHmXTLq5xtmbB1choDP7zvamyebSohwhYF9bgoIJDJZwgFvK+4A6hFoBSLVQtoM1u0XZsJCu/PiZ2YHDEY5VNNN82pD5X/6OlfT0kq9K52pZ+e+q7hZH6SYHDz5Zst5lbHnnk/Wfd9KqfwGeH7BZvc3pVObNim/mBkdP5YevkfUGDLYRMW3naKzGZp2j7PcP) to play with.
12,907,167
> > **Possible Duplicate:** > > [How can I pass command-line arguments in IronPython?](https://stackoverflow.com/questions/5949735/how-can-i-pass-command-line-arguments-in-ironpython) > > > I am new to ironpython and sharpdevelop and I am trying to run the following code, ``` from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third ``` How do I pass the arguments to the command line ?
2012/10/16
[ "https://Stackoverflow.com/questions/12907167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523960/" ]
In [SharpDevelop](http://www.icsharpcode.net/opensource/sd/) you * *right-click* on the python *project* * choose *Properties* in the context-menu * choose the *Debug*-tab * append your arguments in the *Command line arguments* field
13,728,084
I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database.
2012/12/05
[ "https://Stackoverflow.com/questions/13728084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879764/" ]
To do web-based databases, the best practice\*\*\* is to use HTTP requests to a PHP script. That way you will not have to establish a database connection from the app, leaving Usernames and Passwords excluded from the actual project. Create some PHP scripts that will do what you need by sending POST and GET variables. \*\*\*In my experience and preference
133,107
How can I reduce the size of a `\psdiabox`, for instance: ``` \documentclass[10pt,a4paper,twoside]{scrbook} \usepackage{pstricks} \usepackage{pst-all} \begin{document} \psset{unit=0.35} \begin{pspicture}(9.261250,-52.662503)(52.977702,-0.950000) \begin{psmatrix}[rowsep=1cm,colsep=.5cm] & \rput[tc](30.5,-19.5){\psdiabox { \begin{tabular}{c} ?`$Pueden \, estar \, repetidos$ \\ $los \, p \, que \, vaya \, a \, tomar?$ \\ \end{tabular} }} \end{psmatrix} \end{pspicture} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/HeD73.png)
2013/09/13
[ "https://tex.stackexchange.com/questions/133107", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/35541/" ]
Your best bet would be to convert the pdf to a series of images probably using [imagemagick](http://www.imagemagick.org/script/index.php)'s convert routine, then use [ffmpeg](http://www.ffmpeg.org/) to assemble them into a video. Both tools are free and cross-platform. [Stack Overflow has more detail](https://stackoverflow.com/a/10612261/2583476) - you could basically run the contents of the 2 php `exec` commands in the answer from the command line. **Edit:** I think it would be necessary to use a script to figure out where to insert the video - either: * In my limited use of Beamer (simple static slides) I would be able to count the `\begin{frame}`s to count the slides, then look out for the command that includes the video. You could then use this to drive `ffmpeg`. * It also looks possible to parse the `.nav` file - this may be simpler, but I can't get `media9` working here at the moment, so don't know whether it inserts anything into the `.nav` or the `.aux`. The common point is that ffpmeg can do the heavy lifting by combining images and (dissimilar) video files. However, if this was a one-off, without too many videos, I would be inclined to split the PDF, and use ffmpeg to combine PDF1, video1, PDF2, video2 etc. by hand, despite my inclination to script as much as possible.
2,333,897
**EDIT** - Rewrote my original question to give a bit more information --- **Background info** At my work I'm working on a ASP.Net web application for our customers. In our implementation we use technologies like Forms authentication with MembershipProviders and RoleProviders. All went well until I ran into some difficulties with configuring the roles, because the roles aren't system-wide, but related to the customer accounts and projects. I can't name our exact setup/formula, because I think our company wouldn't approve that... **What's a customer / project?** Our company provides management information for our customers on a yearly (or other interval) basis. In our systems a customer/contract consists of: * one Account: information about the Company * per Account, one or more Products: the bundle of management information we'll provide * per Product, one or more Measurements: a period of time, in which we gather and report the data **Extranet site setup** Eventually we want all customers to be able to access their management information with our online system. The extranet consists of two sites: * Company site: provides an overview of Account information and the Products * Measurement site: after selecting a Measurement, detailed information on that period of time The measurement site is the most interesting part of the extranet. We will create submodules for new overviews, reports, managing and maintaining resources that are important for the research. Our Visual Studio solution consists of a number of projects. One web application named Portal for the basis. The sites and modules are virtual directories within that application (makes it easier to share MasterPages among things). **What kind of roles?** The following users (read: roles) will be using the system: * *Admins: development users :) (not customer related, full access)* * *Employees: employees of our company (not customer related, full access)* * Customer SuperUser: top level managers (full access to their account/measurement) * Customer ContactPerson: primary contact (full access to their measurement(s)) * Customer Manager: a department manager (limited access, specific data of a measurement) **What about ASP.Net users?** The system will have many ASP.Net users, let's focus on the customer users: * Users are not shared between Accounts * SuperUser X automatically has access to all (and new) measurements * User Y could be Primary contact for Measurement 1, but have no role for Measurement 2 * User Y could be Primary contact for Measurement 1, but have a Manager role for Measurement 2 * The department managers are many individual users (per Measurement), if Manager Z had a login for Measurement 1, we would like to use that login again if he participates in Measurement 2. **URL structure** These are typical urls in our application: * <http://host/login> - the login screen * <http://host/project> - the account/product overview screen (measurement selection) * <http://host/project/1000> - measurement (id:1000) details * <http://host/project/1000/planning> - planning overview (for primary contact/superuser) * <http://host/project/1000/reports> - report downloads (manager department X can only access report X) We will also create a document url, where you can request a specific document by it's GUID. The system will have to check if the user has rights to the document. The document is related to a Measurement, the User or specific roles have specific rights to the document. **What's the problem? (finally ;))** Roles aren't enough to determine what a user is allowed to see/access/download a specific item. It's not enough to say that a certain navigation item is accessible to Managers. When the user requests Measurement 1000, we have to check that the user not only has a Manager role, but a Manager role for Measurement 1000. Summarized: 1. How can we limit users to their accounts/measurements? (remember superusers see all measurements, some managers only specific measurements) 2. How can we apply roles at a product/measurement level? (user X could be primarycontact for measurement 1, but just a manager for measurement 2) 3. How can we limit manager access to the reports screen and only to their department's reports? All with the magic of asp.net classes, perhaps with a custom roleprovider implementation. **Similar Stackoverflow question/problem** [ASP.NET, how to manage users with different types of roles](https://stackoverflow.com/questions/1367483/asp-net-how-to-manage-users-with-different-types-of-roles)
2010/02/25
[ "https://Stackoverflow.com/questions/2333897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136819/" ]
What you are seeking from the various posts that I see, is a custom role mechanism or said another way, a custom Authorization mechanism. Authentication can still use the standard SqlMembershipProvider. I'm not sure that the standard role provider will provide you with what you want as authorization requires that you have the context of the Project. However, you might investigate writing a custom RoleProvider to see if you can create some custom methods that would do that. Still, for the purposes of answering the question, I'm going to assume you cannot use the SqlRoleProvider. So, here's some potential schema: ``` Create Table Companies ( Id int not null Primary Key , ... ) Create Table Projects ( Id int not null Primary Key , PrimaryContactUserId uniqueidentifier , ... , Constraint FK_Projects_aspnet_Users Foreign Key ( PrimaryContactUserId ) References dbo.aspnet_Users ( UserId ) ) Create Table Roles ( Name nvarchar(100) not null Primary Key , ... ) Create Table ProjectCompanyRoles ( CompanyId int not null , ProjectId int not null , RoleName nvarchar(100) not null , Constraint FK_... ) ``` As I said before, the reason for including PrimaryContact in the Projects table is to ensure that there is only one for a given project. If you include it as a role, you would have to include a bunch of hoop jumping code to ensure that a project is not assigned more than one PrimaryContact. If that were the case, then take out the PrimaryContactUserId from the Projects table and make it a role. Authorization checks would entail queries against the ProjectCompanyRoles. Again, the addition of the contexts of Project and Company make using the default role providers problematic. If you wanted to use the .NET mechanism for roles as well as authentication, then you will have to implement your own custom RoleProvider.
57,972,255
I'm convinced someone else must have had this same issue before but I just can't find anything. Given a table of data: ``` DECLARE @Table TABLE ( [COL_NAME] nvarchar(30) NOT NULL, [COL_AGE] int NOT NULL ); INSERT INTO @Table SELECT N'Column 1', 4 UNION ALL SELECT N'Col2', 2 UNION ALL SELECT N'Col 3', 56 UNION ALL SELECT N'Column Four', 8 UNION ALL SELECT N'Column Number 5', 12 UNION ALL SELECT N'Column Number Six', 9; ``` If I use SSMS and set my output to text, running this script: ``` SELECT [COL_AGE], [COL_NAME] AS [MyCol] FROM @Table ``` Produces this: ``` COL_AGE MyCol ----------- ----------------- 4 Column 1 2 Col2 56 Col 3 8 Column Four 12 Column Number 5 9 Column Number Six ``` Note that the data is neatly formatted and spaced. I want to display the contents like SQL does when you post your results to text: ``` 'Column 1 ' 'Col2 ' 'Col 3 ' 'Column Four ' 'Column Number 5 ' 'Column Number Six' ``` The following is just to describe what I want, I understand it's obviously a horrible piece of script and should never make its way into production: ``` SELECT N'''' + LEFT( [COL_NAME] + SPACE( ( SELECT MAX(LEN([COL_NAME])) FROM @Table ) ) , ( SELECT MAX(LEN([COL_NAME])) FROM @Table ) ) + N'''' FROM @Table ``` Originally, I tried this script, which is what I'm trying to get right: ``` SELECT N'''' + LEFT( [COL_NAME] + SPACE(MAX(LEN([COL_NAME]))) , MAX(LEN([COL_NAME])) ) + N'''' FROM @Table ``` But it returns the following error: > > Msg 8120, Level 16, State 1, Line 28 Column '@Table.COL\_NAME' is > invalid in the select list because it is not contained in either an > aggregate function or the GROUP BY clause. > > > The script is part of a much bigger script and it all has to happen within the SELECT statement, I can't use external variables to first look up the MAX(LEN()) because the bigger script iterates through other tables. Any help would be appreciated.
2019/09/17
[ "https://Stackoverflow.com/questions/57972255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
I just used a quick CROSS APPLY to get the length of the buffer you want to use: ``` select N'''' + LEFT( [COL_NAME] + SPACE( t2.MLEN ) , t2.MLEN ) + N'''' from @Table CROSS APPLY ( SELECT MAX(LEN([COL_NAME])) MLEN FROM @Table ) t2 ```
27,188,342
I have a random crash in UIKit that happend a couple of times already. It crashes with `EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x0000000d` ``` Thread : Crashed: com.apple.main-thread 0 libobjc.A.dylib 0x30e08f46 objc_msgSend + 5 1 UIKit 0x26d1790d -[_UIWebViewScrollViewDelegateForwarder forwardInvocation:] + 140 2 CoreFoundation 0x23654def ___forwarding___ + 354 3 CoreFoundation 0x23586df8 _CF_forwarding_prep_0 + 24 4 UIKit 0x26b5a6fd -[UIScrollView _getDelegateZoomView] + 84 5 UIKit 0x26b5a635 -[UIScrollView _zoomScaleFromPresentationLayer:] + 24 6 UIKit 0x26b5a5ed -[UIWebDocumentView _zoomedDocumentScale] + 64 7 UIKit 0x26b5a13d -[UIWebDocumentView _layoutRectForFixedPositionObjects] + 104 8 UIKit 0x26b59f97 -[UIWebDocumentView _updateFixedPositionedObjectsLayoutRectUsingWebThread:synchronize:] + 38 9 UIKit 0x26b5c3e5 -[UIWebDocumentView _updateFixedPositioningObjectsLayoutAfterScroll] + 28 10 UIKit 0x26b5c3c1 -[UIWebBrowserView _updateFixedPositioningObjectsLayoutAfterScroll] + 56 11 CoreFoundation 0x2360a281 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12 12 CoreFoundation 0x2356652d _CFXNotificationPost + 1784 13 Foundation 0x24296189 -[NSNotificationCenter postNotificationName:object:userInfo:] + 72 14 UIKit 0x27171dd7 -[UIInputWindowController postEndNotifications:withInfo:] + 554 15 UIKit 0x271732ed __77-[UIInputWindowController moveFromPlacement:toPlacement:starting:completion:]_block_invoke595 + 368 16 UIKit 0x26b44b05 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 308 17 UIKit 0x26b4471d -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 184 18 UIKit 0x26b4462f -[UIViewAnimationState animationDidStop:finished:] + 66 19 QuartzCore 0x2653d2d9 CA::Layer::run_animation_callbacks(void*) + 236 20 libdispatch.dylib 0x3135c7a7 _dispatch_client_callout + 22 21 libdispatch.dylib 0x3135ffa3 _dispatch_main_queue_callback_4CF + 718 22 CoreFoundation 0x236179d1 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8 23 CoreFoundation 0x236160d1 __CFRunLoopRun + 1512 24 CoreFoundation 0x23564211 CFRunLoopRunSpecific + 476 25 CoreFoundation 0x23564023 CFRunLoopRunInMode + 106 26 GraphicsServices 0x2a95d0a9 GSEventRunModal + 136 27 UIKit 0x26b701d1 UIApplicationMain + 1440 28 MY_PROJECT 0x000842cf main (main.m:16) ``` It looks like it is related to UIWebView, but I have no clue what happened - any help is appreciated The crash seems to be known in China ...
2014/11/28
[ "https://Stackoverflow.com/questions/27188342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4206060/" ]
I think that ``` height: auto; ``` in you CSS declaration could do what you want. Updated fiddle: <http://jsfiddle.net/3122mts4/4/>
12,992,432
thanks for looking at my question. Basically what I'm trying to do is find all images that look like the first and the third image here: <http://imgur.com/a/IhHEC> and remove all the ones that don't look like that (2,4). I've tried several libraries to no avail. Another acceptable way to do this is to check if the images contain "Code:", as that string is in each one that I have to sort out. Thank you, Steve EDIT: Although the 1st and 3rd images seem like they are the same size, they are not.
2012/10/20
[ "https://Stackoverflow.com/questions/12992432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/679184/" ]
If those are the actual images you're going to use, it looks like histogram similarity will do the job. The first and third are very contrasty, the second and fourth, especially the fourth, have a wide range of different intensities. You could easily make a histogram of the shades of grey in the image and then apply thresholds to the shape of the histogram to classify them. EDIT: To actually do this: you can iterate through every pixel and create an array of pixel value => number of times found. As it's greyscale you can take either the R, G or B channel. Then divide each number by the number of pixels in the image to normalise, so it will work for any size. Each entry in the histogram will then be a fraction of the number of pixels used. You can then measure the number of values above a certain threshold. If there are lots of greys, you'll get a large number of small values. If there aren't, you'll get a small number of large values.
1,952,126
How do I prove that $\displaystyle{\sum\_{i=1}^{\infty}{\frac{2^n(n!)^2}{(2n)!}}=1+\frac{\pi}{2}}$
2016/10/03
[ "https://math.stackexchange.com/questions/1952126", "https://math.stackexchange.com", "https://math.stackexchange.com/users/166193/" ]
Challenging question. You may notice that $\frac{n!^2}{(2n)!}=\binom{2n}{n}^{-1}$, then prove that by integration by parts and induction we have $$ \int\_{0}^{\pi/2}\sin(x)^{2n-1}\,dx = \frac{4^n}{2n\binom{2n}{n}} \tag{1}$$ It follows that $$ S=\sum\_{n\geq 1}2^n\binom{2n}{n}^{-1} = \int\_{0}^{\pi/2}\sum\_{n\geq 1}\frac{2n}{2^n}\sin(x)^{2n-1}\,dx = \int\_{0}^{\pi/2}\frac{4\sin(x)}{(2-\sin^2 x)^2}\,dx.\tag{2}$$ Now it is not difficult to check that the last integral equals $\frac{\pi+2}{2}$: for instance, by integration by parts, since it equals: $$ S = \int\_{0}^{1}\frac{4\,dt}{(1+t^2)^2}.\tag{3}$$
5,841,740
I am trying to do some **method inspection** (in Squeak - Smalltalk). I wanted to ask what is the way **to check if a method is an abstract method**? Meaning I want to write, A method which gets a **class** and a **symbol** and will check if there is such a symbol in the list of methods in an object which is of this class type and if found will return true if abstract (else not). **How can I check if a method is an abstract method or not?** *Thanks in advance.*
2011/04/30
[ "https://Stackoverflow.com/questions/5841740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/550413/" ]
A method is abstract (in the sense Java or C++ people mean) if it looks like this: ``` myMethod self subclassResponsibility. ``` So all you need to do to answer "is `MyObject>>#myMethod` abstract?" is to answer "is `MyObject>>#myMethod` a sender of `#subclassResponsibility`?" You can answer *that* question by adding this method to Object: ``` isMethodAbstract: aSelector on: aClass ^ (self systemNavigation allCallsOn: #subclassResponsibility) anySatisfy: [:each | each selector == aSelector and: [each classSymbol == aClass name]] ``` or simply evaluating this in a Workspace (with suitable replacements for `#samplesPerFrame` and `SoundCodec` of course): ``` (SystemNavigation default allCallsOn: #subclassResponsibility) anySatisfy: [:each | each selector == #samplesPerFrame and: [each classSymbol == SoundCodec name]] ```
1,089,644
I've just upgraded from Outlook 2013. When I opened my To-Do List view, all flagged emails were displayed in a narrow list on the left hand side. The currently selected email were opened in a reading pane on the right hand side. Now, after the upgrade to Outlook 2016, the previously narrow list view takes up the whole screen unnecessarily. I don't get to see any of my emails. [![enter image description here](https://i.stack.imgur.com/EVbc8.png)](https://i.stack.imgur.com/EVbc8.png) How can I regain my reading pane on this page?
2016/06/15
[ "https://superuser.com/questions/1089644", "https://superuser.com", "https://superuser.com/users/389544/" ]
Couple suggestions: 1) Ensure the Reading Pane is enabled for the Tasks/To-Do view. Check *View* tab -> *Reading Pane* -> Ensure it's set to something other than "*Off*". 2) Try *View* tab -> *Reset View* while looking a the Tasks/To-Do list.
44,881,991
Currently I'm coding a project which has a BunifuProgressBar, but I'm having trouble coding it. Basically it says: `'Increment' is not a member of 'BunifuProgressBar'`, any ideas how to fix that issue (Please put the code in the comment section, which will make it so I don't get that error and the prog bar will work.) CODE: ``` Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick BunifuProgressBar1.Increment(1) If BunifuProgressBar1.Value = BunifuProgressBar1.Maxium Then End Sub ``` Regards, -Zualux P.S Like I always say, just comment if you need more information..
2017/07/03
[ "https://Stackoverflow.com/questions/44881991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7898892/" ]
`BunifuProgressBar` does not have a `Increment` method,see the [reference page](https://devtools.bunifu.co.ke/bunifu-ui-winforms-docs/). What it does have is a `Value` property, so what you probably need to do is just: ``` BunifuProgressBar1.Value+=1 ```
14,494,293
I found this question [How to store and retrieve different types of Vertices with the Tinkerpop/Blueprints graph API?](https://stackoverflow.com/questions/8142613/how-to-store-and-retrieve-different-types-of-vertices-with-the-tinkerpop-bluepri) But it's not a clear answer for me. How do I query the 10 most recent articles vs the 10 most recently registered users for an api for instance? Put graphing aside for a moment as this stack must be able to handle both a collection/document paradigm as well as a graphing paradigm (relations between elements of these TYPES of collections). I've read everything including source and am getting closer but not quite there. Closest document I've read is the multitenant article here: <http://architects.dzone.com/articles/multitenant-graph-applications> But it focuses on using gremlin for graph segregation and querying which I'm hoping to avoid until I require analysis on the graphs. I'm considering using cassandr/hadoop at this point with a reference to the graph id but I can see this biting me down the road.
2013/01/24
[ "https://Stackoverflow.com/questions/14494293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1255825/" ]
Answering my own question to this - The answer is indices. <https://github.com/tinkerpop/blueprints/wiki/Graph-Indices>
6,301,506
I need a working script for prohibiting users from saving images on their machine. (Is it only possible through disabling right-click?) Yes, I know that it is impossible, and yes I know that it is a bad practice. Yes, I also know that I am an idiot. But I need this solution for some specific purposes. Thanks!
2011/06/10
[ "https://Stackoverflow.com/questions/6301506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194076/" ]
You could try to replace all the `<img>` elements with `<div>` elements that have the same size and use the image as a background: ``` $('img').each(function() { var $img = $(this); var $div = $('<div>').css({ width: $img.width(), height: $img.height(), backgroundImage: 'url(' + $img.attr('src') + ')', display: 'inline-block' }); $img.after($div).remove(); }); ``` I'm using jQuery because DOM manipulation like this is a bit of a nightmare in raw JavaScript (and because this isn't a free code writing service). This won't stop anyone but it will keep them from dragging the images off your page or doing a "Save As..." from the context menu. This sort of thing also won't do anything if your users disable JavaScript. Example: <http://jsfiddle.net/ambiguous/4Hca3/> I'll leave translating this to whatever JavaScript libraries (if any) you're using as an exercise for the reader. You can try disabling the context menu but not all browsers (such as Firefox) will pay attention to that sort of chicanery.
65,224,241
It is my first time using PHP. I am using XAMPP on a mac. MySQL, Apache, and localhost:8080 are all working right now. I created this file called test.php and saved it inside lampp/htdocs: ``` <!DOCTYPE html> <html lang="en"> <head> <title>Connection</title> </head> <body> <?php $servername = "localhost:8080"; $username = "root"; $password = "root"; // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error($conn)); } else { echo "Connected successfully"; } ?> </body> </html> ``` However, when I go to localhose:8080/test.php a blank page opens but nothing shows up
2020/12/09
[ "https://Stackoverflow.com/questions/65224241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14545805/" ]
Okay, partially my bad. I did re-compile the **EMPTY** sample project and found that despite the compiler error, the solution does build. ``` 1>------ Rebuild All started: Project: Microdesk.BIMrxCommon.Infrastructure, Configuration: Debug2020 Any CPU ------ 1> Microdesk.BIMrxCommon.Infrastructure -> C:\Work\Microdesk.BIMrx\bin\Debug2020\Microdesk.BIMrxCommon.Infrastructure.dll 2>------ Rebuild All started: Project: Microdesk.BIMrxCommon.DbApp, Configuration: Debug2020 Any CPU ------ 2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1720,5): error : Internal MSBuild error: Non-CrossTargeting GetTargetFrameworks target should not be used in cross targeting (outer) build 2> Microdesk.BIMrxCommon.DbApp -> C:\Work\Microdesk.BIMrx\bin\Debug2020\Microdesk.BIMrxCommon.DbApp.dll ========== Rebuild All: 2 succeeded, 0 failed, 0 skipped ========== ``` **BUT** if you try to USE anything from the Infrastructure project in the referencing DbApp project then the Solution will NOT compile ``` Rebuild started... 1>------ Rebuild All started: Project: Microdesk.BIMrxCommon.Infrastructure, Configuration: Debug2020 Any CPU ------ 2>------ Rebuild All started: Project: Microdesk.BIMrxCommon.DbApp, Configuration: Debug2020 Any CPU ------ 2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1720,5): error : Internal MSBuild error: Non-CrossTargeting GetTargetFrameworks target should not be used in cross targeting (outer) build 2>C:\Work\Microdesk.BIMrx\BIMrxCommon\Microdesk.BIMrxCommon.DbApp\DerivedClass.cs(1,29,1,4 ): error CS0234: The type or namespace name 'Infrastructure' does not exist in the namespace 'Microdesk.BIMrxCommon' (are you missing an assembly reference?) 2>C:\Work\Microdesk.BIMrx\BIMrxCommon\Microdesk.BIMrxCommon.DbApp\DerivedClass.cs(5,33,5,42): error CS0246: The type or namespace name 'BaseClass' could not be found (are you missing a using directive or an assembly reference?) ========== Rebuild All: 1 succeeded, 1 failed, 0 skipped ========== ``` I did upload a second sample project named "Microdesk.BIMrx (2).zip" to the previous OneDrive directory
15,343,487
I have a css conflict, so I have to go against an absolute positioning property that deals with some class `.myclass`. But in one case, I want a div with `.myclass` class to have a no absolute positioning. So I put `position: initial`, which works in Chrome, but is it cross-browser? I googled it and found nothing really precise.
2013/03/11
[ "https://Stackoverflow.com/questions/15343487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275959/" ]
The default for position is `position: static;`
39,583,980
I am making a listing system that updates checking new data from a json file every **3 seconds** by appending the **response.list[i].firstname** to document.getElementById("list"). but i am getting unlimited loop. **output:** name1 name2 name1 name2 name1 name2 (to infinity..) ``` <script> list(); setInterval(list, 3000); function list() { $.getJSON('list.php',function(response){ for(var i = 0; i < response.list_count; i++){ var newElement = document.createElement('div'); newElement.innerHTML = response.list[i].firstname; document.getElementById("list").appendChild(newElement); } document.getElementById("list_count").innerHTML = "" + response.list_count; + ""; }); }; ```
2016/09/20
[ "https://Stackoverflow.com/questions/39583980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6246854/" ]
This is happening because every 3 seconds you read JSON file and append it to the already rendered (with all the data appended in previous runs) list with ``` document.getElementById("list").appendChild(newElement); ``` If you want to show only the content of the file once, then you should clean the target list div with one of the methods described in here: [Remove all child elements of a DOM node in JavaScript](https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript) for example: $('#list').empty(); Alternatively, you need to keep track of what you have already added to the list, and append only the new entries, but that might be a bit more tricky, if there is no unique identifiers in the json data that you render. So, with the first solutioin it will be something like: ``` list(); setInterval(list, 3000); function list() { $.getJSON('list.php',function(response){ $('#list').empty(); for(var i = 0; i < response.list_count; i++){ var newElement = document.createElement('div'); newElement.innerHTML = response.list[i].firstname; document.getElementById("list").appendChild(newElement); } document.getElementById("list_count").innerHTML = "" + response.list_count; + ""; }); }; ```
36,572,968
I'm trying to write a program to return the amount of rows and columns in a csv file. Below is the code I currently have: ``` #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream myfile("ETF_Corrsv2.csv"); if (myfile.is_open()) { int counter = 0; while (getline(myfile, line)) { // To get the number of lines in the file counter++; cout << counter; } //int baz[5][5] = {}; while (getline(myfile, line, ',')) { int count = 0; cout << line; for (int i = 0; i < line.size(); i++) if (line[i] == ',') count++; cout << count; } myfile.close(); } else cout << "Unable to open file"; return 0; } ``` The first part works fine and counter returns the number of rows appropriately. However count does not return the correct amount of commas. When using `cout` to display the lines it shows that the commas seem to have been replaced by zeros however when I open the file with Notepad++ the commas are there. What is going on? EDIT: Changed code to have all operations in one while loop: ``` #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream myfile("ETF_Corrsv2.csv"); if (myfile.is_open()) { int counter = 0; while (getline(myfile, line, ',')) { // To get the number of lines in the file counter++; cout << counter; int count = 0; cout << line; for (int i = 0; i < line.size(); i++) if (line[i] == ',') count++; cout << count; } myfile.close(); } else cout << "Unable to open file"; return 0; } ``` Still however getting the issue that the commas are replaced by zeros though so count isn't returning the correct number of columns
2016/04/12
[ "https://Stackoverflow.com/questions/36572968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4845418/" ]
In fact you can reference the corresponding `ElementRef` using `@ViewChild`. Something like that: ``` @Component({ (...) template: ` <div #someId>(...)</div> ` }) export class Render { @ViewChild('someId') elt:ElementRef; ngAfterViewInit() { let domElement = this.elt.nativeElement; } } ``` `elt` will be set before the `ngAfterViewInit` callback is called. See this doc: <https://angular.io/docs/ts/latest/api/core/ViewChild-var.html>.
73,787
1. I couldn't afford that **big a** car. 2. It was so **warm a** day that I could hardly work. The sentences stated above have been taken from *Practical English Usage* by Michael Swan. If I write- 3. I couldn't afford that big car. 4. It was so warm day that I could hardly work. These make sense. But placement of article *a* makes these sentences awkward to me. Please say why and when articles are placed after adjectives. And what are the differences among 1, 2 and 3, 4.
2015/11/20
[ "https://ell.stackexchange.com/questions/73787", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
**Short answer** ---------------- If an adjective is being modified by a deictic degree adverb such as *so, too, as, this* or *that* then the adjective and adverb must go before, not after, the indefinite article. They can also appear as a postmodifier after the noun: * a day so warm **Full answer** --------------- There are several grammatical points about this construction. Firstly, note that the adjective *precedes* the article here. The adjective is modifying a whole noun phrase, not a nominal (a nominal is just the smaller phrase within a noun phrase that occurs after the determiners or articles). So we see: * so warm a day and not: * a so warm day Secondly you will have noticed that this adjective is itself modified by an adverb. Now this adverb must (a) be an adverb of degree and (b) must be a deictic word, in other words it is understood by reference to the immediate environment of the speaker, or through some other element of the discourse itself. Simply using a normal degree adverb will not work here: * \*He was very good a footballer as ... * \*He was extremely good a footballer that ... The adverbs that can be used like this are *so, too*, *as*, *this*, *that* as well as *how*. Some grammarians have also included *more, less* and *enough* in this list, but the grammar of these adverbs is in fact significantly different. Notice that *this* and *that* are adverbs here, not determiners. The adverbs *so*, *too*, *as*, *how*, *this*, *that* and *how* are degree adverbs that cannot themselves give us any idea of actual *degree* or *extent* involved. We could think of them as a kind of 'pro - degree adverb'. These adverbs require some kind of benchmark for us to appreciate the actual degree involved. If this information is not provided by the context this normally entails there being a Complement phrase which indicates the actual extent or degree involved. We can consider such sentences in this way: * It was (X)big a problem [that we gave up the whole project] Here (X) represents the degree involved. On its own (X) does not tell us the actual degree of the bigness of the problem. It is the clause in brackets which explains the actual extent of the size of the problem. The adverb involved will dictate what kind of phrase or clause can function as the Complement. The adverb *so* can take preposition phrases headed by the preposition *as* or finite clauses typically using the subordinator *that*. In the sentence above the only possible adverb we could use instead of (X) is the adverb *so*. The adverb *as* typically takes phrases headed by *as*. It cannot take clauses headed by *that*. The adverb *too* takes *to*-infinitival clauses, headed by *for* if they include a Subject: * He was **so** big an idiot [that he wasn't allowed to speak in public without his advisors]. * It was **so** forceful a blow [as to fell his opponent]. * He is **as** great an actor [as has ever graced this stage]. * He is **as** good a footballer [as the next]' * He was **too** valuable an asset [to let go]. * It was **too** dangerous a project [for us to take it on]. The preposition *as* (as opposed to the degree adverb) introduces equality with what follows it. More precisely it indicates some kind of benchmark which is met *or* exceeded. Notice that the deictic degree adverbs *this*, *that* and *how* usually don't require a following phrase to provide the benchmark. It is normally clear from the discourse itself. However *that* sometimes takes finite clauses with *that* to provide a benchmark when it isn't available from the discourse: * It was that big [that I couldn't fit it through the door]. Lastly, when *how* is interrogative as opposed to exclamative then it is not deictic - in the sense that the degree expressed is left unresolved and in direct questions may be expected to be supplied by the respondent: * I wondered how long a journey it actually was. * How long a rope do we need? Notice that we cannot generally put adjectives before articles, the following are badly formed: * \*big a footballer * \*clever an idea This only occurs when the adjective is being modified by a deictic degree adverb. Why? I don't know. I've been looking into this for quite a long time but haven't been able to find out. **The Original Poster's Examples**: Sentences (1) and (2) are grammatical. Sentence (3) is also grammatical, but this is because the adjective *big* is not being modified by any adverb. The word *that* here is a Determiner. Sentence (4) is completely ungrammatical. Because *day* is singular we must use a Determiner here. If we used an indefinite article then because *warm* is being modified by a deictic degree adverb, the adverb adjective combination should precede the article - as in sentence (2). --- **Note**: Thanks to Edwin and fdb for helpful observations, which have been edited into the answer.