qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
172,847
This is a minor problem but when putting units on graphics I sometimes get italics and sometimes not. I get italics when there are superscripts. Thus ``` Plot[Sin[x], {x, 0, 2 π}, Frame -> True, FrameLabel -> {" m \!\(\*SuperscriptBox[\(m\), \(2\)]\)\* StyleBox[\( \!\(\* StyleBox[\" \",\nFontSlant->\"Italic\"]\)\)]\!\(\* StyleBox[SuperscriptBox[\"m\", \"3\"],\nFontSlant->\"Italic\"]\)", "m \!\(\*SuperscriptBox[\(m\), \(2\)]\)"}, BaseStyle -> {FontFamily -> Times, FontSize -> 24}] ``` ![Mathematica graphics](https://i.stack.imgur.com/eleGj.png) The `m` without the superscript is upright. The `m^2` is italic. In the SI system units should not be italic. In this example things are muddled ``` Graphics[{ Style[Text[ "y = a +\!\(\*SubscriptBox[\(a\), \(0\)]\) + \ \!\(\*SubscriptBox[\(a\), \(1\)]\) x + \!\(\*SubscriptBox[\(a\), \ \(2\)]\) \!\(\*SuperscriptBox[\(x\), \(2\)]\)", {0, 0}], FontSize -> 24, FontFamily -> Times]}] ``` ![Mathematica graphics](https://i.stack.imgur.com/ZIdgq.png) The font without subscripts or superscripts is upright while the font with superscripts or subscripts is italic. Even worse there seems to have been a change in font between "a" and "a subscript". Sometimes one wants italics everywhere, sometimes nowhere. How can this be managed? Version 11.3 **Edit** Following helpful suggestions from Carl Woll I am now trying out using Standard form and no strings. I don't understand this as `FrameLabel` must contain a string for description as well as units. This does not work as seen in this example ``` Plot[Sin[x], {x, 0, 2 π}, Frame -> True, FrameLabel -> {Stress / ( N/ m^2 ) , Acceleration / (m/s^2)}, BaseStyle -> {FontFamily -> Times, FontSize -> 12}, FormatType -> StandardForm] ``` ![Mathematica graphics](https://i.stack.imgur.com/sEPPI.png) I don't want everything multiplied out and I want Times font. Am I missing something here? A better solution is ``` Plot[Sin[x], {x, 0, 2 π}, Frame -> True, FrameLabel -> {"Stress / ( N/ \!\(\*SuperscriptBox[\(m\), \(2\)]\) \ )" , "Acceleration / (m/\!\(\*SuperscriptBox[\(s\), \(2\)]\))"}, BaseStyle -> {FontFamily -> Times, FontSize -> 12}] ``` ![Mathematica graphics](https://i.stack.imgur.com/CtJOc.png) This is the correct way to put units on plots according to the SI system except there should be no italics. The mess in StackExchange with all the backslashes is not a mess in a notebook; I guess this is a problem with the uploader. One of the comments suggested using `FontSlant -> Plain` but this does not work : ``` Plot[Sin[x], {x, 0, 2 π}, Frame -> True, FrameLabel -> Style[{"Stress / ( N/ \!\(\*SuperscriptBox[\(m\), \(2\)]\) )" , "Acceleration / (m/\!\(\*SuperscriptBox[\(s\), \(2\)]\))"}, FontSlant -> Plain], BaseStyle -> {FontFamily -> Times, FontSize -> 12}] ``` ![Mathematica graphics](https://i.stack.imgur.com/Xu6xZ.png) However this does not work out either because it prevents labeling of both axes. So I am still at a loss.
2018/05/08
[ "https://mathematica.stackexchange.com/questions/172847", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/12558/" ]
[`Plot`](http://reference.wolfram.com/language/ref/Plot) by default uses `FormatType->TraditionalForm`, and in [`TraditionalForm`](http://reference.wolfram.com/language/ref/TraditionalForm) single letter *variables* are italicized. Consider: ``` {"m", m, m^2} // TraditionalForm ``` [![enter image description here](https://i.stack.imgur.com/Hy0fo.png)](https://i.stack.imgur.com/Hy0fo.png) The string is not italicized, but the two symbols are. Your [`FrameLabel`](http://reference.wolfram.com/language/ref/FrameLabel) includes the string "m" as well as the *boxes* `"\!\(\*SuperscriptBox[\(m\), \2\)]\)"`, this is why there is a mix of italic and non-italic letters. *As an aside, there is no reason to use incomprehensible linear syntax, just use [`Row`](http://reference.wolfram.com/language/ref/Row) objects with expressions instead, e.g.:* ``` Row[{"m ", Superscript[m, 2]}] ``` *instead of* ``` " m \!\(\*SuperscriptBox[\(m\), \(2\)]\)" ``` Now, in [`StandardForm`](http://reference.wolfram.com/language/ref/StandardForm), Mathematica doesn't italicize single letters, so one possibility is to just use `FormatType->StandardForm`. ``` Plot[Sin[x], {x, 0, 2 π}, Frame -> True, FrameLabel -> {" m \!\(\*SuperscriptBox[\(m\), \(2\)]\)\* StyleBox[\( \!\(\* StyleBox[\" \",\nFontSlant->\"Italic\"]\)\)]\!\(\* StyleBox[SuperscriptBox[\"m\", \"3\"],\nFontSlant->\"Italic\"]\)", "m \!\(\*SuperscriptBox[\(m\), \(2\)]\)"}, BaseStyle -> {FontFamily -> Times, FontSize -> 24}, FormatType->StandardForm] ``` [![enter image description here](https://i.stack.imgur.com/tIbIt.png)](https://i.stack.imgur.com/tIbIt.png) *(the $m^3$ is still italicized because you explicitly set the FontSlant)* Another possibility is to use strings ("m") instead of symbols (m): ``` Plot[Sin[x], {x, 0, 2 π}, Frame -> True, FrameLabel -> {" m \!\(\*SuperscriptBox[\(\"m\"\), \(2\)]\)\* StyleBox[\( \!\(\* StyleBox[\" \",\nFontSlant->\"Italic\"]\)\)]\!\(\* StyleBox[SuperscriptBox[\"m\", \"3\"],\nFontSlant->\"Italic\"]\)", "m \!\(\*SuperscriptBox[\(\"m\"\), \(2\)]\)"}, BaseStyle -> {FontFamily -> Times, FontSize -> 24}] ``` *(I don't include the output because it looks the same as the previous image)*. Another possibility is to just include specific [`Style`](http://reference.wolfram.com/language/ref/Style) wrappers to enforce `FontSlant -> Plain`. At any rate, a good first step is stop using strings with linear syntax! **(updated to address OP revsions)** I said you should use [`Row`](http://reference.wolfram.com/language/ref/Row), but you instead used [`Times`](http://reference.wolfram.com/language/ref/Times). At any rate, since you're interested in units, I would use the [`Quantity`](http://reference.wolfram.com/language/ref/Quantity) framework (this also produces the in-line fractions that you wanted): ``` Plot[ Sin[x], {x, 0, 2 Pi}, Frame->True, FrameLabel->{ Row[{"Stress (", Quantity[None, "Newtons"/"Meters"^2],")"}], Row[{"Acceleration (", Quantity[None, "Meters"/"Seconds"^2],")"}] }, BaseStyle->{FontFamily->"Times", FontSize->12} ] ``` [![enter image description here](https://i.stack.imgur.com/TV754.png)](https://i.stack.imgur.com/TV754.png)
An example, just to summarize the main points: ``` test = Text[ Style[#, FontSlant -> Plain, FontSize -> 32], {0, 0}] & /@ {Indexed[P, {i, j}], P} Graphics /@ test ``` [![italic](https://i.stack.imgur.com/OGCAP.jpg)](https://i.stack.imgur.com/OGCAP.jpg) ``` Graphics[#, FormatType -> StandardForm] & /@ test ``` [![enter image description here](https://i.stack.imgur.com/Sl7PO.jpg)](https://i.stack.imgur.com/Sl7PO.jpg) Thanks for the question and the answers.
34,915,769
I am trying to retrieve categories from the `category` taxonomy of the `custom post` type By the below codes : ``` $categories = get_categories(array( 'type' => 'ad_listing', 'child_of' => 0, 'parent' => '', 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 1, 'hierarchical'=> 1, 'exclude' => '', 'include' => '', 'number' => '', 'taxonomy' => 'ad_cat', 'pad_counts' => false )); echo"<pre>"; print_r($categories); echo"</pre>"; ``` But it is not showing nothing in category though there are 3 categories. i think i am doing something wrong :(
2016/01/21
[ "https://Stackoverflow.com/questions/34915769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4740633/" ]
It will work, ``` $cat_args = array( 'parent' => 0, 'hide_empty' => 0, 'order' => 'ASC', ); $categories = get_categories($cat_args); foreach($categories as $category){ echo get_cat_name($category->term_id); } ```
Here is the code work for me. ``` global $wpdb; $all_cats = array(); $args = array( 'taxonomy' => 'product_cat', 'orderby' => 'name', 'field' => 'name', 'order' => 'ASC', 'hide_empty' => false ); $all_cats = get_categories($args); echo '<pre>'; print_r($all_cats); ```
40,228,718
Not sure how how to fomulate the question, but this is the case: ``` interface X { some: number } let arr1: Array<X> = Array.from([{ some: 1, another: 2 }]) // no error let arr2: Array<X> = Array.from<X>([{ some: 1, another: 2 }]) // will error ``` ([code in playground](http://www.typescriptlang.org/play/index.html#src=interface%20X%20%7B%0D%0A%20%20some%3A%20number%0D%0A%7D%0D%0A%0D%0Alet%20arr1%3A%20Array%3CX%3E%20%3D%20Array.from(%5B%7B%20some%3A%201%2C%20another%3A%202%20%7D%5D)%20%2F%2F%20no%20error%0D%0Alet%20arr2%3A%20Array%3CX%3E%20%3D%20Array.from%3CX%3E(%5B%7B%20some%3A%201%2C%20another%3A%202%20%7D%5D)%20%2F%2F%20will%20error)) The error: ``` Argument of type '{ some: number; another: number; }[]' is not assignable to parameter of type 'ArrayLike<X>'. Index signatures are incompatible. Type '{ some: number; another: number; }' is not assignable to type 'X'. Object literal may only specify known properties, and 'another' does not exist in type 'X'. ``` Why in first case there is no error (no type comparability check), is it by design or there is an issue for this?
2016/10/24
[ "https://Stackoverflow.com/questions/40228718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733596/" ]
> > But whenever the page attempts to load, it crashes with the error "Failed to assign to property 'Windows.UI.Xaml.EventTrigger.RoutedEvent'." Why does this not work? > > > As @Clemens said, problem is in Windows Runtime XAML, the default behavior for event triggers and the only event that can be used to invoke an EventTrigger is FrameworkElement.Loaded. I'm writing this answer here to call another problem of your code, as you said: > > It also fails if I change the RoutedEvent property to Loaded, FrameworkElement.Loaded, Image.Loaded > > > This is because you didn't specify the `Storyboard.TargetName` in your `DoubleAnimation`, it will throw the exception when it runs. To solve this problem, you will need to give a name to your `Image` in the `DataTemplate` and modify your storyboard like this: ``` <Image x:Name="myImage" Source="{Binding SmallUri}" Stretch="UniformToFill"> <Image.Triggers> <EventTrigger RoutedEvent="Image.Loaded"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="00:00:5" Storyboard.TargetName="myImage" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Image.Triggers> </Image> ```
I know it's too late for answering the question but for those who will be having the same issue. you can use this XAML code: ``` <Image x:Name="TumbImage" Opacity="0" ...> <i:Interaction.Behaviors> <core:EventTriggerBehavior EventName="ImageOpened"> <media:ControlStoryboardAction Storyboard="{StaticResource ImageOpacityStoryBoard}" ControlStoryboardOption="Play"/> </core:EventTriggerBehavior> </i:Interaction.Behaviors> ``` The Sample storyboard I used here: ``` <Storyboard x:Key="ImageOpacityStoryBoard"> <DoubleAnimation Storyboard.TargetName="TumbImage" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.33" /> </Storyboard> ``` and the XML namespaces used: ``` xmlns:i="using:Microsoft.Xaml.Interactivity" xmlns:core="using:Microsoft.Xaml.Interactions.Core" xmlns:media="using:Microsoft.Xaml.Interactions.Media" ```
14,870,046
Hi I am new to Hadoop and NoSQL technologies. I started learning with world-count program by reading file stored in HDFS and and processing it. Now I want to use Hadoop with MongoDB. Started program from [here](http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-hadoop/) . **Now here is confusion with me that it stores mongodb data on my local file system, and read data from local file system to HDFS in map/reduce and again write it to mongodb local file system. When I studied HBase, we can configure it to store it's data on HDFS, and hadoop can directly process it on HDFS(map/reduce). How to configure mongodb to store it's data on HDFS.** *I think it is better approach to store data in HDFS for fast processing. Not in the local file system. Am I right? Please clear my concept if I am going in wrong direction.*
2013/02/14
[ "https://Stackoverflow.com/questions/14870046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1004981/" ]
It seems Chrome is in error. The [CSS 2.1 spec](http://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align) says > > The baseline of an 'inline-block' is the baseline of its last line box > in the normal flow, unless it has either no in-flow line boxes or if > its 'overflow' property has a computed value other than 'visible', in > which case the baseline is the bottom margin edge. > > > Since the overflow property computes to something other than 'visible' the inline-block's baseline is the bottom margin edge, which sits on the baseline of the containing line box, and therefore must raise up the contained text to allow space for the descenders of that text.
Try This ``` <!doctype html> <html> <head> <style> .a { display: inline; overflow: hidden; color: red; } </style> </head> <body> baseline__<div class="a">test</div>__baseline </body> </html> ```
5,595,469
I am new to the kohana php framework. In the modules folder in kohana 3.1, there are many empty files extending the existing classes. Should I write my code in those empty files? If yes, do I have to make any changes in bootstrap? If not, where should I place these files? Should they be in a subfolder inside the Application directory or inside the modules directory? Which all files will I have to copy from the modules to application?
2011/04/08
[ "https://Stackoverflow.com/questions/5595469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691288/" ]
You have to check if it was clean request or not. Otherwise you will fall into infinite loop Here is an *example* from one of my projects: .htaccess ``` RewriteEngine On RewriteRule ^game/([0-9]+)/ /game.php?newid=$1 ``` game.php ``` if (isset($_GET['id'])) { $row = dbgetrow("SELECT * FROM games WHERE id = %s",$_GET['id']); if ($row) { Header( "HTTP/1.1 301 Moved Permanently" ); Header( "Location: /game/".$row['id']."/".seo_title($row['name'])); } else { Header( "HTTP/1.1 404 Not found" ); } exit; } if (isset($_GET['newid'])) $_GET['id'] = $_GET['newid']; ``` So, you have to verify, if it was direct "dirty" call or rewritten one. And then redirect only if former one. You need some code to build clean url too. And it is also very important to show 404 instead of redirect in case url is wrong.
If you are running Apache you can use the mod\_rewrite module and set the rules in a .htaccess file in your httpdocs folders or web root. I don't see any reason to invoke a PHP process to do redirection when lower level components will do the job far better. [An example from Simon Carletti](http://www.simonecarletti.com/blog/2009/01/apache-query-string-redirects/): ``` RewriteEngine On RewriteCond %{REQUEST_URI} ^/page\.php$ RewriteCond %{QUERY_STRING} ^id=([0-9]*)$ RewriteRule ^(.*)$ http://mydomain.site/page/%1.pdf [R=302,L] ```
7,933,505
How can create a mask input for number that have percent by jQuery? Do I make input just accept until three numbers and put percent sign after numbers while user finished typing(`keyup`)? **I don't use plugins.** Example: **1%** Or **30%** Or **99%** Or **100%** Or **200%** ``` <input name="number" class="num_percent"> ```
2011/10/28
[ "https://Stackoverflow.com/questions/7933505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1004952/" ]
You're better off not using JavaScript for this. Besides the problems that come with using `onkeyup` for detecting text input, you also have the hassle of parsing the resulting string back to a number in your client/server scripts. If you want the percent sign to look integrated, you could do something like this: ``` <div class="percentInput"> <input type="text" name="number" class="num_percent"> <span>%</span> </div> ``` ``` .percentInput { position:relative; } .percentInput span { position: absolute; right: 4px; top:2px; } .num_percent { text-align: right; padding-right: 12px; } ``` <http://jsfiddle.net/BvVq4/> I'm rushing slightly, so you may have to tweak the styles to get it to look right cross-browser. At least it gives you the general idea.
```js function setPercentageMask() { let input = $('.percent'); input.mask('##0,00', {reverse: true}); input.bind("change keyup", function() { isBetweenPercentage($(this)); }); } function isBetweenPercentage(input) { let myNumber = (input.val()) ? parseFloat(input.val()) : 0; (myNumber.isBetween(0, 100.00)) ? myNumber : input.val('100,00'); } if (typeof(Number.prototype.isBetween) === "undefined") { Number.prototype.isBetween = function(min, max, notBoundaries) { var between = false; if (notBoundaries) { if ((this < max) && (this > min)) between = true; } else { if ((this <= max) && (this >= min)) between = true; } return between; } } setPercentageMask(); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <input name="text" class="percent"> ```
3,777
First of all, if you didn't know (and I can only hope you did), Programmers Stack Exchange has it's [own community blog](http://programmers.blogoverflow.com/) that anybody can contribute to. So, if you haven't been reading it, start now :-)! Anyways, currently we have very few solid contributors to the blog. We started with about 7 posts, and that number is quickly falling. Basically, if we don't get more community help with this, we are going to be on the verge of dying. So if you want to contribute, now is the time to start. Currently, we are in need of mainly writers, although if you would like to sign-up as an editor or proofreader, that would be fine. To sign up, set up your answer as so: > > Name > ==== > > > ***Position (either editor/proofreader or writer or both)*** > > > Description. > > > If you are a writer, your description area is where you should put how many posts you'll be able to dish out per month or another time span. For example, `1 post every 1-2 months`. If you only want to write one post, and then stop helping, that's also fine, although we would love to see you stay. Once you sign up, we will contact you with your Wordpress account details and Trello account details. For more info on those services, and on how you will be helping, [see here](https://softwareengineering.meta.stackexchange.com/questions/3044/contributing-to-the-blog). If you have any questions, ping me in the [Programmers Blog Room](http://chat.stackexchange.com/rooms/2359/programmers-blog), or leave a comment. That's about it! Enjoy the blog, and start signing up :-)! **Addendum** > > Register on Trello with the handle you use here. I'll invite you once > you ping me in the programmers blog chatroom. WP access can be gained > by listing your email either in that chat or in your post here. If you > want to be private about it send it to programmer.se.blog (at) > gmail.com with the subject line: Programmer Blog Sign-up. Please > indicate your handle in the message as well. > > >
2012/07/12
[ "https://softwareengineering.meta.stackexchange.com/questions/3777", "https://softwareengineering.meta.stackexchange.com", "https://softwareengineering.meta.stackexchange.com/users/34364/" ]
Justin Kohlhepp --------------- **Writer, 1 post every 1-2 months** I maintain my own blog at the moment at [RationalGeek.com](http://rationalgeek.com/blog). The topics I write about are pretty well aligned to the subject matter of Programmers.SE. I'd be glad to contribute some posts to P.SE blog as long as I can also post them on my site. Not sure if that is allowed.
Le Do Hoang Long ================ *Writer, 1 post every 1,2 months & proofreader* I maintain a simple blog at <https://ledohoanglong.wordpress.com>. My English writing skill may be not very good, but I'm willing to learn.
490,939
I am using the following lines to create two columns ``` \begin{columns} \begin{column}{0.5\textwidth} some text here some text here some text here some text here some text here \end{column} \begin{column}{0.5\textwidth} some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here \end{column} \end{columns} ``` I'd like to set the heights of both columns to same value. How can this be done? `0.5\textwidth` fixes the column width. I tried, `\begin{column}{0.5\textwidth,0.2\paperheight}`. It didn't work. Could someone help?
2019/05/15
[ "https://tex.stackexchange.com/questions/490939", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/161646/" ]
**1. multicol** Here is a solution using [multicols](https://ctan.org/pkg/multicol), because initially I had no reference to the package that has the definition of the environment `column` and `columns`. I have added a `minipage` of fixed height and width inside the columns, and the text inside the `minipage`. You can just copy and paste the `minipage`-code inside your "column", and it should work. Uncomment the `%\vspace{-\topskip}` if you want the content to align at the absolute top of the `minipage`. You may also change `\columnwidth`to `0.5\textwidth` if you want the text closer. `\paperheight` also works. ``` \documentclass{article} \usepackage{multicol} \begin{document} \begin{multicols}{2} \noindent\begin{minipage}[t][.2\textheight][t]{\columnwidth} %\vspace{-\topskip}% some text here some text here some text here some text here some text here \end{minipage} \columnbreak \noindent\begin{minipage}[t][.2\textheight][t]{\columnwidth} %\vspace{-\topskip}% some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here \end{minipage} \end{multicols} New text outside the columns starts here and as you see the text is below both columns. \end{document} ``` [![enter image description here](https://i.stack.imgur.com/HF85U.png)](https://i.stack.imgur.com/HF85U.png) **2. beamer** It also works with [beamer](https://ctan.org/pkg/beamer) and `columns`. I had to increase the text height to 0.5, because your text was more than `0.2\textheight` (and also more than `0.2\paperheight`): ``` \documentclass{beamer} \begin{document} \begin{frame} \begin{columns}[T] \begin{column}{0.5\textwidth} \begin{minipage}[t][.5\textheight][t]{\textwidth} some text here some text here some text here some text here some text here \end{minipage} \end{column} \begin{column}{0.5\textwidth} \begin{minipage}[t][.5\textheight][t]{\textwidth} some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here \end{minipage} \end{column} \end{columns} New text outside the columns starts here and as you see the text is below both columns. \end{frame} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/7PFyN.png)](https://i.stack.imgur.com/7PFyN.png)
If the columns are top aligned, they will look as if they have the same height (even if they don't actually have it). It makes no sense to add additional minipages inside the columns, because they are minipages themselves. ``` \documentclass{beamer} \begin{document} \begin{frame} \begin{columns}[T] \begin{column}{0.5\textwidth} some text here some text here some text here some text here some text here \end{column} \begin{column}{0.5\textwidth} some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here \end{column} \end{columns} \end{frame} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/1UgZU.png)](https://i.stack.imgur.com/1UgZU.png)
4,129,599
I want to notify a user about her being also logged in from other computer(s), with an option to close these other sessions. Unfortunately it'd not immediately obvious how to do it in Django without hacking the database directly.
2010/11/09
[ "https://Stackoverflow.com/questions/4129599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489566/" ]
Oracle and java play fairly well with each other, and this is may be a new idea if you're feeling adventerous. Java does this pretty easily, but i'm away from an oracle box and unable to test. This really hurts i'm not in front of an oracle machine at the moment. To make sure I remembered correctly, I used steps from here <http://www.dba-oracle.com/tips_oracle_sqlj_loadjava.htm> and then I googled this, which is almost word for word what we'll do below: <http://docstore.mik.ua/orelly/oracle/guide8i/ch09_03.htm> ``` /**** *java and oracle playing together. */ import java.util.Date; public class hex2Date{ //this is if you want to call the java function from a command line outside of oracle public static void main (String args[]) { System.out.println ( convert (args[0]) ); } public static Date convert(String inHexString){ try{ Date dateResult = new Date(Long.parseLong(inHexString,16)); }catch (NumberFormatException e){ // do something with the exception if you want, recommend at least throwing it. //throw(e,'some extra message'); } return dateResult; } } ``` save that file as Hex2Date.java in 'yourJava' directory, and from a cmd line in that directory type: javac Hex2Date.java now type: java Hex2Date.java 0x4A273F if you get the right dates, and the results, let's tell oracle about our little function. you'll need some user rights first: GRANT JAVAUSERPRIV TO your user here; type this: loadjava -user scott/tiger -resolve Hex2Date.class now wrap this in pl/sql, so you can call it in pl/sql.: ``` /* java function plsql wrapper: hex2Date.sf */ CREATE OR REPLACE FUNCTION hex2Date ( inHexString IN VARCHAR2) RETURN DATE AS LANGUAGE JAVA NAME 'Hex2Date.convert(java.lang.String) return Date'; / ``` now, run it from a sql prompt: SQL> exec DBMS\_OUTPUT.PUT\_LINE ( hex2Date('0x4A273F'))
If the 'HEX' values are from a Mainframe, then perhaps they are EBCDIC (Extended Binary Coded Decimal Interchange Code) and not HEX? I don't have time to reason it out right now but try this page for ideas/clues? <http://www.simotime.com/asc2ebc1.htm> Of course I may be barking up the wrong tree :) Assume 50 34 2E is 27th April 2009 ``` EBCDIC HEX DEC 5 F5 245 0 F0 240 3 F3 243 4 F4 244 2 F2 242 E C5 197 ```
48,592,613
I am switching from basic R plot tools to ggplot2 and am struggling with one issue. In basic R you can control distance to each of four axes (or the "box") by setting margins. Resulting margins are fixed and do not depend on what you plot. These allows me to produce plots for my papers with exactly same plot area sizes despite the size of tick labels and axis labels. In ggplot, I ecnountered this (minimum working example): ``` library(ggplot2) dat = data.frame(x = 1:5, y = 1e-5* (1:5) ^ 2) p = ggplot(dat, aes(x, y)) + geom_point() + geom_line() print(p) print(p + scale_y_log10()) ``` [![First figure](https://i.stack.imgur.com/PFt53.png)](https://i.stack.imgur.com/PFt53.png) [![Second figure](https://i.stack.imgur.com/jeeAv.png)](https://i.stack.imgur.com/jeeAv.png) Black arrows at the left-hand side of the plots show the difference between actual margins I get. Axis label(`y`) stays in place, while position of the `y`-axis shifts depending on the size of tick labels (text representation). It can be further escalated by changing `axis.text.y` to e.g. increase `size`. What I desire is to be able to control actual margins no matter what tick labels are drawn - in that case I can achieve same sizes of figures of different data sets.
2018/02/03
[ "https://Stackoverflow.com/questions/48592613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3458955/" ]
Following the approach suggested by [Stewart Ross](https://stackoverflow.com/users/1649060/stewart-ross) in [this message](https://stackoverflow.com/a/48595363/3458955), I ended up in the similar [thread](https://stackoverflow.com/questions/36198451/specify-widths-and-heights-of-plots-with-grid-arrange/36198587). I played around with grobs generated from my sample ggplots using [this](https://stackoverflow.com/a/36210199/3458955) method - and was able to determine how to manually control layout of your grobs individually (at least, to some extent). For a sample plot, a generated grob's layout looks like this: ``` > p1$layout t l b r z clip name 17 1 1 10 7 0 on background 1 5 3 5 3 5 off spacer 2 6 3 6 3 7 off axis-l 3 7 3 7 3 3 off spacer 4 5 4 5 4 6 off axis-t 5 6 4 6 4 1 on panel 6 7 4 7 4 9 off axis-b 7 5 5 5 5 4 off spacer 8 6 5 6 5 8 off axis-r 9 7 5 7 5 2 off spacer 10 4 4 4 4 10 off xlab-t 11 8 4 8 4 11 off xlab-b 12 6 2 6 2 12 off ylab-l 13 6 6 6 6 13 off ylab-r 14 3 4 3 4 14 off subtitle 15 2 4 2 4 15 off title 16 9 4 9 4 16 off caption ``` Here we are interested in 4 axes - `axis-l,t,b,r`. Suppose we want to control left margin - look for `axis-l`. Notice that this particular grob has a layout of 7x10. ``` p1$layout[p1$layout$name == "axis-l", ] t l b r z clip name 2 6 3 6 3 7 off axis-l ``` As far as I understood it, this output means that left axis takes one grid cell (#3 horizontally, #6 vertically). Note index `ind = 3`. Now, there are two other fields in `grob` - `widths` and `heights`. Lets go to `widths` (which appears to be a specific list of `grid`'s `unit`s) and pick up width with index `ind` we just obtained. In my sample case the output is something like ``` > p1$widths[3] [1] sum(1grobwidth, 3.5pt) ``` I guess it is a 'runtime-determined' size of some `1grobwidth` plus additional 3.5pt. Now we can replace this value by another unit (I tested very simple things like centimeters or points), e.g. `p1$widths[3] = unit(4, "cm")`. So far I was able to confirm that if you specify equal 'widths' for left axis of two diferent plots, you will get identical margins. Exploring `$layout` table might provide other ways of controlling plot layout (e.g. look at the `$layout$name == "panel"` to change plot area size).
Although there are many theme options in ggplot2, there does not appear to be an option which sets a fixed margin space for the axes (or if there is it is well hidden). The `cowplot` package has an align\_plots function which can align one or both axes in a list of plots. `align_plots` returns a list, each component of which is the original plot but with the axes specified aligned. I am using the grid.arrange function from the `gridExtra` package to output both plots so you can see the way the alignment works: ``` library(ggplot2) dat = data.frame(x = 1:5, y = 1e-5* (1:5) ^ 2) p = ggplot(dat, aes(x, y)) + geom_point() + geom_line() print(p) p1 = p + scale_y_log10() print(p1) library(cowplot) library(gridExtra) p2 = align_plots(p, p1, align = "hv") grid.arrange(p2[[1]], p2[[2]]) ``` [![enter image description here](https://i.stack.imgur.com/2YdnW.png)](https://i.stack.imgur.com/2YdnW.png) This is how the two original plots would have output: ``` grid.arrange(p, p1) ``` [![enter image description here](https://i.stack.imgur.com/PZ6Cv.png)](https://i.stack.imgur.com/PZ6Cv.png)
5,766,318
I am not sure it is me or what but I am having a problem converting a double to string. here is my code: ``` double total = 44; String total2 = Double.toString(total); ``` Am i doing something wrong or am i missing a step here. I get error `NumberFormatException` when trying to convert this. ``` totalCost.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { try { double priceG = Double.parseDouble(priceGal.getText().toString()); double valG = Double.parseDouble(volGal.toString()); double total = priceG * valG; String tot = new Double(total).toString(); totalCost.setText(tot); } catch(Exception e) { Log.e("text", e.toString()); } return false; } }); ``` I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box.
2011/04/23
[ "https://Stackoverflow.com/questions/5766318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/637146/" ]
Using Double.toString(), if the number is too small or too large, you will get a scientific notation like this: 3.4875546345347673E-6. There are several ways to have more control of output string format. ``` double num = 0.000074635638; // use Double.toString() System.out.println(Double.toString(num)); // result: 7.4635638E-5 // use String.format System.out.println(String.format ("%f", num)); // result: 0.000075 System.out.println(String.format ("%.9f", num)); // result: 0.000074636 // use DecimalFormat DecimalFormat decimalFormat = new DecimalFormat("#,##0.000000"); String numberAsString = decimalFormat.format(num); System.out.println(numberAsString); // result: 0.000075 ``` Use String.format() will be the best convenient way.
There are three ways to convert **double to String**. 1. Double.toString(d) 2. String.valueOf(d) 3. ""+d public class DoubleToString { ``` public static void main(String[] args) { double d = 122; System.out.println(Double.toString(d)); System.out.println(String.valueOf(d)); System.out.println(""+d); } ``` } **String to double** 1. Double.parseDouble(str);
28,422,989
I used javascript to hide `div` depend on `radio button` value for example I unhide `div` `#one` and fill up input fields and realize I'm in the wrong transaction and click the radio button to change the desire transaction but without clean up all input fields. is there any way to clean up input values(I mean by clean up is to empty input fields)if user select on the radio button. **script** ``` <script> function showhidediv( rad ) { var rads = document.getElementsByName( rad.name ); document.getElementById( 'one' ).style.display = ( rads[0].checked ) ? 'block' : 'none'; document.getElementById( 'two' ).style.display = ( rads[1].checked ) ? 'block' : 'none'; document.getElementById( 'three' ).style.display = ( rads[2].checked ) ? 'block' : 'none'; } </script> ``` **form** ``` <form action="aef.php" method="post"> <label>Date</label><br /> <input type="text" value="<?php echo date('Y-m-d'); ?>" name="date" /><br /><br /> <input type="radio" name="transtype" value="0" onclick="showhidediv(this);" checked /> LBC Payment <input type="radio" name="transtype" value="1" onclick="showhidediv(this);" /> Additional Funds <input type="radio" name="transtype" value="2" onclick="showhidediv(this);" /> miscellaneous expense <br /><br /> <div id="one"> <label>LBC Tracking No.</label><br /> <input type="text" value="" name="lbc" /><br /><br /> <label>Transaction Code</label><br /> <input type="text" value="" name="code" id="code" /><br /><br /> <label>Credit Amout</label><br /> <input type="text" name="credit_amout" /> </div> <div id="two" class="divhide"> <label>Debit Amout</label><br /> <input type="text" name="debit_amout" /> </div> <div id="three" class="divhide"> <label>Expenses Description</label><br /> <input type="text" id="expenses" value="" name="description" /><br /><br /> <label>miscellaneous expense</label><br /> <input type="text" name="credit_amout" /> </div> <br /><br /> <input type="submit" value="Add Expenses" name="submit" /> </form> ```
2015/02/10
[ "https://Stackoverflow.com/questions/28422989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954060/" ]
maybe this could give you idea how on the javascript ``` <script> function showhidediv( rad ) { var rads = document.getElementsByName( rad.name ); document.getElementById( 'one' ).style.display = ( rads[0].checked ) ? 'block' : 'none'; document.getElementById( 'two' ).style.display = ( rads[1].checked ) ? 'block' : 'none'; document.getElementById( 'three' ).style.display = ( rads[2].checked ) ? 'block' : 'none'; var input = new Array(); if (rads[0].checked) { input = document.querySelectorAll('#one input'); } if (rads[1].checked) { input = document.querySelectorAll('#two input'); } if (rads[2].checked) { input = document.querySelectorAll('#three input'); } clear_inputs(input); } function clear_inputs(input) { for (var i = input.length - 1; i >= 0; i--) { input[i].value = ''; }; } </script> ``` you can start modifying the code according to what you need the function clear\_inputs will clear the value of the input you can improve this code.
I've created this function to clear data from inputs, but it can also help you to read an element contained in the parent div, read the values and decide what to do.. ``` function clear_inputs(div){ parent_content=document.getElementById(div); child_elements=parent_content.getElementsByTagName('input'); co = child_elements.length;co--; /*elements goes from 0 to ∞, length goes from 1 to ∞, thats why c-- to loop thru the elements.*/ /*console.log(elementos);console.log(co); use this if you want to see the elements you are working with on browser's console*/ for (i=0;i<=co;i++) {child_elements[i].value = "";}// empty values for inputs } } ```
430,199
Let $\chi$ be a primitive character mod $p$ (prime) and $\rho = \beta + i \gamma$ be a non-trivial zero of $L(s, \chi)$. I am reading a paper by Ihara and Murty where they use following estimate : $\left|\frac{1}{\rho(1-\rho)} \right| \ll \log p \;$ for $\; |\gamma| \leq 1$. (We can assume $\rho$ is not the possible exceptional zero.) I am not sure why this is true. They just mention it is well-known, so any reference will also be helpful.
2022/09/11
[ "https://mathoverflow.net/questions/430199", "https://mathoverflow.net", "https://mathoverflow.net/users/477598/" ]
This follows from Noam's answer and the classical zero-free region for Dirichlet $L$-functions. For a specific reference, see Davenport's *Multiplicative Number Theory*, Chapter 14. The result quoted below can be found on page 93: **Theorem.** There exists a positive absolute constant $c$ with the following property. If $\chi$ is a complex character modulo $q$, then $L(s,\chi)$ has no zero in the region defined by $$ \sigma \geq \begin{cases} 1 - \dfrac{c}{\log(q |t|)} & \text{if $|t| \geq 1$},\\[1em] 1- \dfrac{c}{\log(q)} & \text{if $|t| \leq 1$}. \end{cases} $$ Note that this holds for complex characters because in this case there is no exceptional zero. A similar result holds for quadratic characters, aside from the exceptional zero, of course. We thus have, for any non-exceptional zero $\rho = \beta+i\gamma$ $$ |1-\rho| = |1-\beta - i\gamma| \geq 1-\beta \geq \frac{c}{\log(q)} $$ for $|\gamma|\leq 1$.
We must assume that $1-\rho$ is not exceptional either. Then both $|\rho|$ and $|1-\rho|$ are $\gg 1 / \log p$, and the desired inequality follows, for instance because $$ \frac1{\rho (1-\rho)} = \frac1\rho + \frac1{1-\rho}. $$
613,231
Heyo! I'm currently working on a non-lfs system from scratch with busybox as the star. Now, my login says: ``` (none) login: ``` Hence, my hostname is broken. `hostname` brings me `(none)` too. The guide I was following told me to throw the hostname to `/etc/HOSTNAME`. I've also tried `/etc/hostname`. No matter what I do, `hostname` returns `(none)` - unless I run `hostname <thename>` or `hostname -F /etc/hostname`. Now obviously, I don't want this to be done every time somebody freshly installed the distro -- so what is the real default file, if not `/etc/hostname`? Thanks in advance!
2020/10/06
[ "https://unix.stackexchange.com/questions/613231", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/382366/" ]
The `hostname` commands in common toolsets, including BusyBox, do not fall back to files when querying the hostname. They report solely what the kernel returns to them as the hostname from a system call, which the kernel initializes to a string such as "(none)", changeable by reconfiguring and rebuilding the kernel. (In systemd terminology this is the *dynamic hostname*, a.k.a. *transient hostname*; the one that is actually reported by Linux, the kernel.) There *is no* "default file". There's usually a single-shot service that runs at system startup, fairly early on, that goes looking in these various files, pulls out the hostname, and initializes the kernel hostname with it. (In systemd terminology this configuration string is the *static hostname*.) For example: * In my toolset I provide an "early" `hostname` service that runs the toolset's `set-dynamic-hostname` command after local filesystem mounts and before user login services. The work is divided into stuff that is done (only) when one makes a configuration change, and stuff that is done at (every) system bootstrap: + The external configuration import mechanism reads `/etc/hostname` and `/etc/HOSTNAME`, amongst other sources (since different operating systems configure this in different ways), and makes an amalgamated `rc.conf`. + The external configuration import mechanism uses the amalgamated `rc.conf` to configure this service's `hostname` environment variable. + When the service runs, `set-dynamic-hostname` doesn't need to care about all of the configuration source possibilities and simply takes the environment variable, from the environment configured for the service, and sets the dynamic hostname from it. * In systemd this is an initialization action that is hardwired into the code of `systemd` itself, that runs before service management is even started up. The `systemd` program itself goes and reads `/etc/hostname` (and also `/proc/cmdline`, but *not* `/etc/HOSTNAME` *nor* `/etc/default/hostname` *nor* `/etc/sysconfig/network`) and passes that to the kernel. * In Void Linux there is [a startup shell script](https://github.com/void-linux/void-runit/blob/95ad0a971eccddba4779ad153860fff3764d123a/core-services/05-misc.sh) that reads the static hostname from (only) `/etc/hostname`, with a fallback to the shell variable read from `rc.conf`, and sets the dynamic hostname from its value. If you are building a system "from scratch", then you'll have to make a service that does the equivalent. The BusyBox and ToyBox tools for setting the hostname from a file are `hostname -F "${filename}"`, so you'll have to make a service that runs that command against `/etc/hostname` or some such file. BusyBox comes with runit's service management toolset, and a simple runit service would be something along the lines of: ``` #!/bin/sh -e exec 2>&1 exec hostname -F /etc/hostname ``` Further reading =============== * Lennart Poettering et al. (2016). [`hostnamectl`](https://freedesktop.org/software/systemd/man/hostnamectl.html). systemd manual pages. Freedesktop.org. * Jonathan de Boyne Pollard (2017). "[`set-dynamic-hostname`](http://jdebp.info./Softwares/nosh/guide/commands/set-dynamic-hostname.xml)". *User commands manual*. nosh toolset. Softwares. * Jonathan de Boyne Pollard (2017). "[`rc.conf` amalgamation](http://jdebp.info./Softwares/nosh/guide/rcconf-amalgamation.html)". *nosh Guide*. Softwares. * Jonathan de Boyne Pollard (2015). "[external formats](http://jdebp.info./Softwares/nosh/guide/external-formats.html)". *nosh Guide*. Softwares. * Rob Landley. [`hostname`](http://landley.net/toybox/help.html#hostname). *Toybox command list*. landley.net. * <https://unix.stackexchange.com/a/12832/5132>
So you are building this system from scratch and you are asking where the hostname is configured? The simple answer is that it isn't. The current hostname is stored inside the kernel and like most things kernel, it doesn't read any files by default. *Something* in your system startup must read a config file (of your choosing) and set the kernel's hostname. This must happen every startup.
4,325,066
I have created a table with HTML and want to integrate a search box. How do i do that? Can you recommend a good jQuery plugin or better a complete tutorial?
2010/12/01
[ "https://Stackoverflow.com/questions/4325066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/526647/" ]
There are great answers. But [this](http://blogs.digitss.com/about/) guy did what i Really wanted. it's slighly different from previous answers HTML ``` <label for="kwd_search">Search:</label> <input type="text" id="kwd_search" value=""/> <table id="my-table" border="1" style="border-collapse:collapse"> <thead> <tr> <th>Name</th> <th>Sports</th> <th>Country</th> </tr> </thead> <tbody> <tr> <td>Sachin Tendulkar</td> <td>Cricket</td> <td>India</td> </tr> <tr> <td>Tiger Woods</td> <td>Golf</td> <td>USA</td> </tr> <tr> <td>Maria Sharapova</td> <td>Tennis</td> <td>Russia</td> </tr> </tbody> </table> ``` Javascript (Jquery) ``` // When document is ready: this gets fired before body onload <img src='http://blogs.digitss.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> $(document).ready(function(){ // Write on keyup event of keyword input element $("#kwd_search").keyup(function(){ // When value of the input is not blank if( $(this).val() != "") { // Show only matching TR, hide rest of them $("#my-table tbody>tr").hide(); $("#my-table td:contains-ci('" + $(this).val() + "')").parent("tr").show(); } else { // When there is no input or clean again, show everything back $("#my-table tbody>tr").show(); } }); }); // jQuery expression for case-insensitive filter $.extend($.expr[":"], { "contains-ci": function(elem, i, match, array) { return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0; } }); ``` Live Demo: <http://blogs.digitss.com/demo/jquery-table-search.html> Source: <http://blogs.digitss.com/javascript/jquery-javascript/implementing-quick-table-search-using-jquery-filter/>
Thanks David Thomas Good Solution. Following makes it perfect. ``` $(document).ready( function(){ $('#searchbox').keyup( function(){ var searchText = $(this).val(); if (searchText.length > 0) { $('tbody td:contains('+searchText+')') .addClass('searchResult'); $('.searchResult') .not(':contains('+searchText+')') .removeClass('searchResult'); $('tbody td') .not(':contains('+searchText+')') .addClass('faded'); $('.faded:contains('+searchText+')') .removeClass('faded'); $('.faded').hide(); $('.searchResult').show(); } else if (searchText.length == 0) { $('.searchResult').removeClass('searchResult'); $('.faded').removeClass('faded'); $('td').show(); } }); }); ``` [**JS Fiddle demo Updated**](http://jsfiddle.net/PPVcw/66/)
28,762,180
I want to sort the [select2](https://select2.org/) options in alphabetical order. I have the following code and would like to know, how can this be achieved: ``` <select name="list" id="mylist" style="width:140px;"> <option>United States</option> <option>Austria</option> <option>Alabama</option> <option>Jamaica</option> <option>Taiwan</option> <option>canada</option> <option>palau</option> <option>Wyoming</option> </select> $('#mylist').select2({ sortResults: function(results) { return results.sort(); } }); ``` I want to sort the data via 'text'.
2015/02/27
[ "https://Stackoverflow.com/questions/28762180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3592650/" ]
Select2 API v3.x (`sortResults`) ================================ You can sort elements using `sortResults` callback option with [`String.localeCompare()`](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/localeCompare): ```js $( '#mylist' ).select2({ /* Sort data using localeCompare */ sortResults: data => data.sort((a, b) => a.text.localeCompare(b.text)), }); ``` ```html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.css" integrity="sha256-ijlUKKj3hJCiiT2HWo1kqkI79NTEYpzOsw5Rs3k42dI=" crossorigin="anonymous" /><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.js" integrity="sha256-7A2MDY2eGSSUvgfbuH1IdzYk8qkEd3uzwiXADqPDdtY=" crossorigin="anonymous"></script> <select name="list" id="mylist" style="width:140px;"> <option>United States</option> <option>Austria</option> <option>Alabama</option> <option>Jamaica</option> <option>Taiwan</option> <option>canada</option> <option>palau</option> <option>Wyoming</option> </select> ``` Select2 [API v4.0 (`sorter`)](https://select2.org/configuration/options-api) ============================================================================ You can sort elements using `sorter` callback option: ```js $('#mylist').select2({ sorter: data => data.sort((a, b) => a.text.localeCompare(b.text)), }); ``` ```html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" integrity="sha256-xqxV4FDj5tslOz6MV13pdnXgf63lJwViadn//ciKmIs=" crossorigin="anonymous" /><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js" integrity="sha256-FA14tBI8v+/1BtcH9XtJpcNbComBEpdawUZA6BPXRVw=" crossorigin="anonymous"></script> <select name="list" id="mylist" style="width:140px;"> <option>United States</option> <option>Austria</option> <option>Alabama</option> <option>Jamaica</option> <option>Taiwan</option> <option>canada</option> <option>palau</option> <option>Wyoming</option> </select> ``` --- Without jQuery ============== I had another general purpose approach (you can use value or an attribute for sorting elements) without using jQuery: ```js var select = document.getElementById("mylist"); var options = []; // Get elements to sort document.querySelectorAll('#mylist > option').forEach( option => options.push(option) ); // Empty select while (select.firstChild) { select.removeChild(select.firstChild); } // Sort array using innerText (of each option node) options.sort( (a, b) => a.innerText.localeCompare(b.innerText) ); // Add the nodes again in order for (var i in options) { select.appendChild(options[i]); } ``` ```html <select name="list" id="mylist" style="width:140px;"> <option>United States</option> <option>Austria</option> <option>Alabama</option> <option>Jamaica</option> <option>Taiwan</option> <option>canada</option> <option>palau</option> <option>Wyoming</option> </select> ``` With jQuery =========== Thanks [@Narendra Sisodia](https://stackoverflow.com/users/2899618/narendrasingh-sisodia) for jQuery tip: ```js /* Get options */ var selectList = $('#mylist > option'); /* Order by innerText (case insensitive) */ selectList.sort( (a, b) => a.innerText.localeCompare(b.innerText) ); /* Re-do select HTML */ $('#mylist').html(selectList); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <select name="list" id="mylist" style="width:140px;"> <option>United States</option> <option>Austria</option> <option>Alabama</option> <option>Jamaica</option> <option>Taiwan</option> <option>canada</option> <option>palau</option> <option>Wyoming</option> </select> ```
Take a look in this code: ``` $('#your_select').select2({ /* Sort data using lowercase comparison */ sorter: data => data.sort((a,b) => a.text.toLowerCase() > b.text.toLowerCase() ? 0 : -1) }); ``` I hope it has been helped you! =)
17,544,190
I have a page that the user can upload an image to and then move around and resize using jquery draggable and jquery resizable. To save on mutilple requests to the server, would it be posible to use the locally stored version of the image to speed things up and then have a save button which would only upload the image to the server when requested. I have tried to do this unsuccessfully as I am only getting the temp location of the file ``` <? $posted=$_REQUEST['posted']; if($posted!='') { $image = $_FILES['file']['tmp_name']."/".$_FILES['file']['name']; ?><img src="<? echo $image ?>" width="480" height="360" /><? echo "posted=".$image; } ?> <form action="#" enctype="multipart/form-data" method="post"> <input type="hidden" name="posted" value="1" /> <input type="file" id="file" name="file" size="30" /> <input name="submit" type="submit" value="send" /> </form> ``` is this possible?
2013/07/09
[ "https://Stackoverflow.com/questions/17544190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1095504/" ]
Do somthing like this- ``` var url = $('a').attr('href'); if(verify url is of type image here){ //true } else{ //false } ```
Use regexp to check for strings in the href attribute: ``` var patt=/(png|jpg|gif)/g; if(patt.test($('a').attr('href'))){ //do something if image } else { //do something else } ```
50,566,868
How to change background color of `TabBar` without changing the `AppBar`? The `TabBar` does not have a `background` property, is there a workaround?
2018/05/28
[ "https://Stackoverflow.com/questions/50566868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4222924/" ]
So if you are looking for to change the specific tab color and then you can try the following code: 1. Create a variable of color: Color tabColor=Colors.green; 2. Create onTap method inside the TabBar and inside the tab bar create `setState()` method code is given below: ```dart onTap: (index) { setState(() { if(index==0) { tabColor = Colors.lightGreen;} if(index==1) {tabColor = Colors.yellow;} if(index==2) {tabColor = Colors.green;} if(index==3) {tabColor = Colors.red;} if(index==4) {tabColor = Colors.deepPurple;} }); print(index); }, ``` 3. Create an indicator and give some radius as per your requirement and change the color code is given: ```dart indicator: BoxDecoration( borderRadius: BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10)), color: tabColor ), ```
for use with SliverPersistenHeader (e.t.c collapsing with sliver appbar in nested scrollview) ``` class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { _SliverAppBarDelegate(this._tabBar); final TabBar _tabBar; @override double get minExtent => _tabBar.preferredSize.height; @override double get maxExtent => _tabBar.preferredSize.height; @override Widget build( BuildContext context, double shrinkOffset, bool overlapsContent) { return new Container( child: _tabBar, color: Colors.red, ); } @override bool shouldRebuild(_SliverAppBarDelegate oldDelegate) { return false; } } ```
68,538,522
I have a data frame of household members containing 3 integer columns, 'hid', 'sub', and 'age'. I'd like to create a new logical variable in the data frame called 'hh' representing the household head, defined as follows: 1. If there is only 1 member in the household, then the value is TRUE, 2. If there are 2 or more members in the household, then the household head is the one who is aged between 18 and 65 (inclusive) and has the smallest subject id ('sub') among those aged between 18 and 65. 3. If there are no members in the household aged between 18 and 65, then the household head is the one with the smallest subject id. There must be 1 and only 1 household head per household. My data looks something like this: ``` # A tibble: 10 x 3 hid sub age <dbl> <dbl> <dbl> 1 1 1 75 2 1 2 55 3 2 1 35 4 3 1 69 5 3 2 72 6 4 1 69 7 5 1 15 8 5 2 17 9 5 3 42 10 6 1 72 ``` And I'd like the result to be like this: ``` > result # A tibble: 10 x 4 hid sub age hh <dbl> <dbl> <dbl> <lgl> 1 1 1 75 FALSE # Not 18-65 & there is another aged 18-65 within this household. 2 1 2 55 TRUE # Aged 18-65 and the smallest sub id within this household. 3 2 1 35 TRUE # Only 1 in this household. 4 3 1 69 TRUE # Not aged 18-65, but no other member is and smallest sub id. 5 3 2 72 FALSE # Not aged 18-65, and not the smallest sub id. 6 4 1 69 TRUE # Only 1 in this household. 7 5 1 15 FALSE # Not aged 18-65 and others in this household qualify. 8 5 2 17 FALSE # Not aged 18-65 and others in this household qualify. 9 5 3 42 TRUE # Aged 18-65 and the smallest sub id among those aged 18-65 within this household. 10 5 4 62 FALSE # Aged 18-65 but not the smallest sub id among those aged 18-65 within this household. ``` Thank you! --- ``` d <- structure(list(hid = c(1, 1, 2, 3, 3, 4, 5, 5, 5, 5), sub = c(1, 2, 1, 1, 2, 1, 1, 2, 3, 4), age = c(75, 55, 35, 69, 72, 69, 15, 17, 42, 62)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame")) ```
2021/07/27
[ "https://Stackoverflow.com/questions/68538522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7514527/" ]
You can `arrange` the data in such a way that the first row of each group is the `hh` value you are looking for. ``` library(dplyr) d %>% arrange(hid, !between(age, 18, 65), sub) %>% mutate(hh = !duplicated(hid)) # hid sub age hh # <dbl> <dbl> <dbl> <lgl> # 1 1 2 55 TRUE # 2 1 1 75 FALSE # 3 2 1 35 TRUE # 4 3 1 69 TRUE # 5 3 2 72 FALSE # 6 4 1 69 TRUE # 7 5 3 42 TRUE # 8 5 4 62 FALSE # 9 5 1 15 FALSE #10 5 2 17 FALSE ``` `!between(age, 18, 65)` would arrange the data keeping the individuals aged 18-65 first before others who are outside the range.
An option with `case_when`, each case\_when is translating your conditions 1 to 3 into code: ``` library(dplyr) d %>% group_by(hid) %>% mutate(hh = case_when(max(sub) == 1 ~ TRUE, max(sub) > 1 & between(age, 18, 65) & sub == min(sub[between(age, 18, 65)]) ~ TRUE, max(between(age, 18, 65)) < 1 & sub == min(sub[max(between(age, 18, 65)) < 1]) ~ TRUE, TRUE ~ FALSE)) ``` Output: ``` hid sub age hh <dbl> <dbl> <dbl> <lgl> 1 1 1 75 FALSE 2 1 2 55 TRUE 3 2 1 35 TRUE 4 3 1 69 TRUE 5 3 2 72 FALSE 6 4 1 69 TRUE 7 5 1 15 FALSE 8 5 2 17 FALSE 9 5 3 42 TRUE 10 5 4 62 FALSE ```
32,902,360
For instance I have a database of cars, which have a field called manufacture. ``` car: { _id: <ObjectId>, manufacture: "Opel", model: "Astra" } ``` How can I get all manufactures without repeating them using the latest implementation official C# driver for MongoDB? I'd like this to be done in my request to the database, not after.
2015/10/02
[ "https://Stackoverflow.com/questions/32902360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5397012/" ]
This should do it ``` var db = database.GetCollection<BsonDocument>("cars"); FieldDefinition<BsonDocument, string> field = "car.manufacture"; FilterDefinition<BsonDocument> filter = new BsonDocument(); var a = db.DistinctAsync(field, filter).GetAwaiter().GetResult().ToListAsync().GetAwaiter().GetResult(); ```
Use the `Distinct()` method: <http://api.mongodb.org/csharp/current/html/M_MongoDB_Driver_MongoCollection_Distinct.htm> The field name should be passed as a string, some generic MongoDB examples: <http://docs.mongodb.org/manual/reference/method/db.collection.distinct/> Following [some examples](http://docs.mongodb.org/getting-started/csharp/query/), it should look like this: `var result = await collection.Distinct('manufacture');`.
109,439
I have a permanent email aliasing from my previous institute. My current academic affiliation (let's pretend it is Horvord University) does NOT give me a permanent email address. Now, I am going to submit a paper to a journal and I wonder if it is considered professionally appropriate if I list Horvord as my affiliation but list my previous email as the contact?
2018/05/09
[ "https://academia.stackexchange.com/questions/109439", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/69151/" ]
Adding an acknowledgment essentially doesn't cost anything, so there's little reason why the authors wouldn't want to do it if you helped; however it is true that there is still some awkwardness involved in asking others to credit you. One way to defuse the awkwardness could be to focus on tangible practical reasons why you think this acknowledgment could be useful to you, instead of more sensitive subjective reasons (e.g., I want to be acknowledged, I feel like I deserve the acknowledgment, etc.) E.g., > > In case my bug fixes were useful to you, do you think you could point it out in the acknowledgements section? This could be helpful later to show to [thesis committee / potential future advisor / supervisor / etc.] that I made some contribution to the paper. > > > Essentially the idea is to sidestep the embarrassment in "admitting that you noticed", or embarrassment on their part for not having thought about it themselves, having possibly hurt your feelings, etc.; and just frame the request as something motivated by a practical need. (Of course the need may be completely hypothetical -- it's just an excuse to avoid mentioning more subjective motivations.)
If I were in your place, I would not ask to be mentioned in acknowledgments, especially if you are planning to work with authors in the future. Not all battles are equally important, think in the long run :) p.s. if the authorship were discussed, I would say fight for it, but acknowledgments...I would not.
29,438,562
**Description of the Problem** As NPAPI plugins will be deprecated in Chrome (maybe in Firefox too soon) and being part of a project ([WebChimera](http://www.webchimera.org/)) that is based on an NPAPI plugin. I've been thinking of different solutions to keep NPAPI support in browsers. (as porting this plugin to NaCL is currently impossible, but the plugin can be used in a frozen version of node-webkit that currently supports NPAPIs) So I was wondering if it is possible for a browser page to open a node-webkit app on the user's PC, then using JS with/without jQuery to send data about the html element where the Node-Webkit window (with always on top set) should be to the app (maybe through a websocket) to always position it there. I know I can get a html element's size, position in JavaScript, I also know I can track the scroll of the user and browser tab changes to do the necessary changes to the window size, position and visibility. **The Question** The thing that truly stops me from even attempting this is how would I know when a browser is not fullscreen, and how would I know the browser's position on the screen if it is not fullscreen either from the on page JS or from node-webkit directly. Another thing that should be a concern is what screen is the browser window on. Am I the only one that has thought of such an endeavor with node-webkit, are there any open source projects attempting this? Any thoughts or comments on this would be greatly appreciated as a solution to this would not only save NPAPI plugins in the near future but will also open a world where Node-Webkit can also be used as a viable solution to build browser plugins too. :)
2015/04/03
[ "https://Stackoverflow.com/questions/29438562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2769366/" ]
This would involve a lot of painful hackery. You'd have to solve most of these issues on all platforms independently and rely on a lot of implementation details. As a possible alternative, check out the [plans for FireBreath 2.0](http://www.firebreath.org/x/kQCt) which will support plugins which can be loaded via NPAPI, ActiveX, and Native Messaging via a new protocol called FireWyrm. Currently there is no drawing support when using the FireWyrm interface and only Native Messaging is supported. Additionally it's not quite finished, though I'm getting close =]
Now it's possible to use libvlc to play video directly on NW.js/Electron page: <https://www.npmjs.com/package/webchimera.js> What this project is: it's low level (written in C++) addon which use libvlc and allow decode video frames to JS ArrayBuffer object. In turn this ArrayBuffer object could be drawn on HTML5 canvas directly or with WebGL. This project use Node.js/V8 API directly and not use NPAPI at all, so will live even after NPAPI deprecation. Another good thing - perfomance of this (espesially if use WebGL) is comparable with original VLC player perfomance. Simple usage example available at: <https://github.com/jaruba/wcjs-player>
74,588
I would like to install a "panic button" on my phone's home screen or lock screen that would send a predefined sms/text message to a selected group of people. I am NOT looking for a group sms app where you first need to wait for the app to start up, then need to select the group, then type a message, then handle various menus/screens/popups/confirmations to send it. It should be quick and easy (with hopefully only one or two clicks or swipes) to send the predefined message to a group in a life threatening situation. It should enable me to notify e.g. my neighbours, police, security, family, etc. immediately and simultaneously in a case of emergency. Is anyone aware of such an app or any way to customized an existing app/feature to get this type of behaviour?
2014/06/21
[ "https://android.stackexchange.com/questions/74588", "https://android.stackexchange.com", "https://android.stackexchange.com/users/64518/" ]
Yes. It is possible to have more space allocated for personal use. First, I would suggest that your download [Terminal Emulator](https://play.google.com/store/apps/details?id=jackpal.androidterm&hl=en) and run the command `df` in it to get the memory allocated for each partition (ie `/system`, `/data` etc). The space allocated to `/data` partition is only space you can use. Rest is for system/firmware that you cant use. There are three ways to get out of this problem-> 1) **Repartition** We will reduce the amount of memory allocated to `/system` and give that memory to `/data`. Manufacturers often give `/system` partition a farily good amount of space for future os upgrades. But when you use custom roms, they are relatively lighter and use much less space, so we can shrink this partition. But unfortunately, there isn't any such method made yet for xperia z ultra as far as I know. So this is a rather difficult (almost impossible, considering working of sony phones, the TA partition etc). 2) **Installing as "system app"** You know that `/system` partition has a lot of unused space. So how to use it? Install apps inside system partition! They will become system apps and you will need special app managers to uninstall them (you can use some app manager to install app and move it to `/system` partition. **Not all apps will support doing this**). Downside is that apps will still store their data in `/data` partition, so again, this isnt a very good option. (You can also just create a random folder inside `/system` partition and probably store a few things like songs inside that? Ok that might be a stupid idea, even though I do practice this on my Nexus 4, which has relatively even less memory). 3) **App2SD** This leaves you with only one efficient option as this. Use some app like [Link2Sd](https://play.google.com/store/apps/details?id=com.buak.Link2SD) to move apps and their data to external sd card. Hence more space inside internal. Again, not all apps are supported, but most are.
Well u did not specify your Android OS so let's go by the default answer 1. Basically in Android Device the operating system(jelly bean, Kit Kat) occupies a lot of space for the phone to operate(drivers for Wi-Fi, HD display etc.) and remind you its pre determined and can also vary after an update. 2. Due to which the internal memory will decrease after the update takes place. 3. To increase the internal memory there's no way without downgrading the operating system of your phone as the storage space of the operating system is reduced. 4. Another way would be to move all your applications to the SD Card storage which will boost your speed as well as memory.
5,285,572
I have a form to signup with the code below: ``` <form method="post"> Username<input type="text" size="12" maxlength="16" name="username"><br /> Password<input type="password" size="12" maxlength="32" name="password"><br /> <input type="submit" name="submit" value="Sign Up!" /> </form> ``` And then I have it too check if the username contains any special characters and if it doesn't it runs this code: ``` define("DB_SERVER", "localhost"); define("DB_USER", "will"); define("DB_PASS", "blahblah"); define("DB_NAME", "blahblah"); define("TBL_USERS", "users"); $connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error()); mysql_select_db(DB_NAME, $connection) or die(mysql_error()); function addNewUser($username, $password){ global $connection; $username =$POST['username']; $password =$_POST['password']; $password1 = md5($password); $q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password1')"; return mysql_query($q, $connection); } ``` This should add the username and password to my table with the password as an md5 hash but it doesn't, could someone please help me. Thanks!
2011/03/12
[ "https://Stackoverflow.com/questions/5285572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654182/" ]
First of all: Don't use concatenated strings to insert values to the database. This is a major security hole, it can be exploited using a technique called SQL-Injection. You can prevent this by using so called [Prepared Statements](http://www.petefreitag.com/item/356.cfm). And this should solve your problem: You probably don't really call the addNewUser function. You just connect ot the database. Try this: ``` define("DB_SERVER", "localhost"); define("DB_USER", "will"); define("DB_PASS", "blahblah"); define("DB_NAME", "blahblah"); define("TBL_USERS", "users"); function addNewUser($username, $password){ global $connection; $password1 = md5($password); $username = mysql_real_escape_string($username); $q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password1')"; return mysql_query($q, $connection); } $connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error()); mysql_select_db(DB_NAME, $connection) or die(mysql_error()); addNewUser($_POST["text"], $_POST["password"]); ```
$username =$POST['username'] is wrong. You forgot \_ . It must be $username = $\_POST['username'].
561,203
I am using a web service to query data from a table. Then I have to send it to a user who wants it as a DataTable. Can I serialize the data? Or should I send it as A DataSet. I am new to Web Services, so I am not sure the best way to do it.
2009/02/18
[ "https://Stackoverflow.com/questions/561203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67854/" ]
You can send the data as a xml string from a dataset by `DataSet.GetXml()` And than the user can deserialize it with `DataSet.ReadXml()` And get the datatable from the dataset by `DataSet.Tables` Good luck
You can transfer DataTable's over a Web Service. So that is probably your best option, becuase that is what the client asked for.
33,798,100
I am using elasticsearch dsl to search on elasticsearch : <https://elasticsearch-dsl.readthedocs.org/en/latest/> How can i filter specific fields while making a search query: I know its supported in elasticsearch: <https://www.elastic.co/guide/en/elasticsearch/reference/1.4/search-request-fields.html> Just dont know how to do the same in Elasticsearch-dsl
2015/11/19
[ "https://Stackoverflow.com/questions/33798100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3027854/" ]
When you have your `Search` object you can call the `.fields()` function on it and specify which fields you want to return: ``` s = search.Search() s = s.fields(["field1", "field2"]) ... ``` It's not explicitly mentioned in the documentation, but you can see the `fields` function in the [source for the `search.py` file](https://github.com/elastic/elasticsearch-dsl-py/blob/62898c1737c44a93c933285ad891267c5ed0a306/elasticsearch_dsl/search.py#L306) and some [test cases for the `fields` function](https://github.com/elastic/elasticsearch-dsl-py/blob/62898c1737c44a93c933285ad891267c5ed0a306/test_elasticsearch_dsl/test_search.py#L352) *UPDATE* From ES 2.x onwards, the `fields()` method has been renamed to `source()`
i use that for all fields : ``` from elasticsearch_dsl import Q, Search from elasticsearch import Elasticsearch client = Elasticsearch('localhost:9200') q = Q("multi_match", query='STRING_TO_SEARCH', fields=['_all']) result = Search(index='YOUR_INDEX').using(client).query(q).execute() ``` or for specific fields : ``` fields=['name',] ```
14,916,520
Hi Im studying for my scja exam and have a question about string passing by ref/value and how they are immutable. The following code outputs "abc abcfg". What I want to know is why is this happening? Im not understanding what happens inside of method f. String is passed by value so surely it should change to "abcde" inside the method? Because if b+="fg" appends to the string why doesnt it work inside the method? Thanks! ``` public class Test { public static void main(String[] args){ String a =new String("abc"); String b = a; f(b); b+="fg" System.out.println(a + " " + b); } public static void f(String b){ b+="de"; b=null; } } ```
2013/02/16
[ "https://Stackoverflow.com/questions/14916520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/655283/" ]
This line of code: ``` b += "de"; ``` Roughly translates to: ``` b = b + "de"; ``` Which creates a new String and stores it in the local variable 'b'. The reference outside the method is not changed in anyway by this. There are a couple of key things to remember when trying to understand how/why this works this way. 1. In Java, all method arguments are passed by value. 2. Methods have a local stack where all their data is stored, including the method arguments. When you assign a new object to a variable that was passed into a method, you are only replacing the address in the local stack, with the address of the new object created. The actual object address outside of the method remains the same.
Your creating a new object of String when you say something like b+="de" Its like saying b = new String(b+"de"); If you really want to keep the value passed in then use a stringBuilder like this: ``` StringBuilder a =new StringBuilder("abc"); StringBuilder b = a; f(b); b.append("fg"); System.out.println(a + " " + b); } public static void f(StringBuilder b){ b.append("de"); b=null; } ``` Now your output will be "abcdefg" because stringbuilder object b was passed into f as the value of the object itself. I modified the value without using "new" to point to another object. Hope its clear now.
166,694
It has beeen a long time since I've asked a question, however the narrative to my question is quite simple: How do I push back against upper management "innovations" and simple "requests"? Questions that I found tremendously helpful were: * [How can I push back against a boss who wants us to work four 16-hour days in a hotel?](https://workplace.stackexchange.com/questions/83693/how-can-i-push-back-against-a-boss-who-wants-us-to-work-four-16-hour-days-in-a-h) * [How to deal with a bad management choice about a technical solution?](https://workplace.stackexchange.com/questions/23653/how-to-deal-with-a-bad-management-choice-about-a-technical-solution) * [Should I do something unethical/possibly illegal if asked by management?](https://workplace.stackexchange.com/questions/141964/should-i-do-something-unethical-possibly-illegal-if-asked-by-management) * [How do I report an employee who is compromising security of employees and clients?](https://workplace.stackexchange.com/questions/140260/how-do-i-report-an-employee-who-is-compromising-security-of-employees-and-client) * [Implementing something your boss has asked for, even if it's potentially a bad idea](https://workplace.stackexchange.com/questions/18946/implementing-something-your-boss-has-asked-for-even-if-its-potentially-a-bad-i) * [How to correct a CEO's misunderstanding of a project?](https://workplace.stackexchange.com/questions/15436/how-to-correct-a-ceos-misunderstanding-of-a-project) However, until I can find a valid exit strategy, here is the situation. Background: I work fairly autonomously, as the sole "data person" (basically someone who knows how to write SQL queries and build self-service tableau dashboards for business intelligence dissemination) **left** (other person left as soon as they got an offer) on my team, I have considerable leeway in deciding what projects/features (among the dozens pending) that will fill my day for research, design, and implementation - as I am the only developer left who is qualified to make a working data product. However, from time to time, upper management, will "pop-in" to make demands and changes that are one or a mix of the following: * Unethical: Tying personnel scorecards (like a report card from school) to arbitrary or unreasonable metrics (imagine if your teacher was ranked based on the class average grade... or that you have an attendance grade, a metric based on the same attendance grade + X, and again another metric based on attendance grade + Y). * Amoral: If upper management doesn't get their way, in the sense that I say "yes, I will give you a email of a spreadsheet", a shouting match occurs where my tableau-based work is touted as "insufficient" or "useless" or that "they don't understand it" (other than upper management, tableau dashboards work fine for the rank and file team members) and that they can find someone to do the work and replace me. * Eyebrow Raising: Whenever a new report is made, upper management will use excel spreadsheets as a "mock-up" of **exactly** what they want, even though there is no way in heck that an excel spreadsheet is a viable delivery method for data reporting assets that is used dynamically by >220 users. The level of technological comprehension seems to be stuck solely on spreadsheets and emails as the primary means of business intelligence dissemination. * Disrespectful (? not sure the right word): while the other data person was on the team, when I said "no, with the following reasons... data stack incompatibility, refresh times, UI/UX, delivery times, etc..." upper management will order the other person to do **exactly** what they want (the other data person always enables upper management) and I am forced to incorporate and support (now inherit) spaghetti code and framework with numerous coding issues and 0 documentation (I document, other person doesn't). * Unreasonable: since upper management only pops-in from time to time, there is no overall data strategy, everything is ad-hoc and should've done yesterday. Deep Dives into operational issues are expected within 4 hours or new dashboards are demanded and minimalized as "basic spreadsheet reporting that should've been done yesterday". My direct manager is remotely aware of my role within the team, and keenly aware of the abusive nature of upper management, however my direct manager is a "people manager" and not a "data person" and as this is a 'operations' environment, the workplace culture definitely has "old school" mentality. I am currently looking for other employment for the past year, but given the economy, I had a couple of interviews, but no offer in hand. In the meantime, my 2020Q4 goal is to figure out the spaghetti and learn the workflows that I will be inheriting, but I suspect that 2020Q4 will be full of demands to do inane (send an email from a screenshot of a tableau report before 1100 AM, while the requestor for some unknown reason refuses to look at a data dashboard and self-service their business intelligence needs) tasks that the other person who left usually does. Note, once I am gone, there will be 0 knowledge left my team to build and or maintain existing assets. I used to have trouble about this (professional pride and my relationships with coworkers to ensure that what they use daily works), but after speaking in real life to some mentors I have come to accept that once I am gone, this is not my business. I have pushed for more support and levels of redundancy (I proposed to train a junior data analyst, but the response I received was that 2 hours every other week was enough, I thought this was a joke as it would've taken >2 years to train this person, but this was a serious response) to support and document what I do and its impact on the overall team, but these requests were upon deaf ears. I only have 40 hours and I am now supporting a global team solo - there is simply no time left in the day to do everything.
2020/11/11
[ "https://workplace.stackexchange.com/questions/166694", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/38289/" ]
Your question reads like a rant. Instead of pushing back, why not just go along with it? You have no stake in the success or failure of the company other than your current paycheck, and since your plan is to leave as soon as the opportunity arises, why do you care? At the end of the day, they pay you to perform work. You may not like the work, you may not agree with the work, but it's not up to you to determine what is worthwhile and what isn't. You seem to have a lot of complaints about how things are done, most of which I'm failing to find real merit with, and most of what you've stated is subjective. We can't possibly validate anything you've said, and taken with the tone of your question, strikes me as not much more than sour grapes. If you don't like the way they run the business, and if you don't like the things you're asked to do, then go start your own company and run it the way you want. Until then, I'd simply keep my opinions to myself and do the work they request of me.
Pushing back against upper management innovations and requests for improvement? Hold on. It is top management's job to know what they need. However, you can push back on how that information is collected and presented. The problem is that you, in IT, are expected to know the business objectives and work to further those objectives. You are resisting that. The problem isn't what they are asking for, but because of the disconnect between your ideas and their comprehension of their business needs, there is conflict. The better way of dealing with this is to ask for understanding of what the business needs are. When they come in with innovations and requests for improvement, we do a heck of a lot better to ask for understanding of how this fits in with the business needs. Often, we get to learn more about the company and what the real objectives of top management. (And, yes, those objectives often change.) I have a lot of requests for specific spreadsheets. By asking for more information, I have often come back with a different solution that better meets the business needs. Remember that top management needs information in a format that they can understand. Our job is to provide that. That rank and file people use one format, but top management uses spreadsheets is not a problem. We get to provide those spreadsheets. If you don't want to do that, yes, find another job.
29,810,389
I must calculate time between several dates, but this fields are not date type, this fields are varchar, so I must convert them. For example I have this values: ``` CODIGO SUMILLA_HDR1 SUMILLA_HDR2 N050044 07/01/2015 10:58 09/01/2015 12:32:36 N050044 07/01/2015 10:58 09/01/2015 11:58:10 ``` If I convert the value with the sentence: ``` SELECT CONVERT(char(8), CAST('07/01/2015 10:58:38' AS DATE),112) ``` I have: 20150701 => this is fine for me. But If I try the next: ``` SELECT CONVERT(char(8), CAST(SUMILLA_HDR1 AS DATE),112) FROM FLUJO_CS WHERE CODIGO = 'N050044' ``` I have the error: > > Conversion failed when converting date and/or time from character string. > > > I don't know why is this, the values are the same, anybody can help me please? It will be appreciated.
2015/04/22
[ "https://Stackoverflow.com/questions/29810389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4591130/" ]
`sed` is the wrong tool for any task involving multi-line blocks of input because it's line-oriented. You should be using awk as it's record-oriented and so can treat each multi-line block of input a easily as sed can handle lines of input. ``` $ awk -v RS= -v ORS='\n\n' '{sub(/xyz/,"abc"); sub(/network:[^\n]+/,"network: temp_net")}1' file name: abc ip: x.x.x.x network: temp_net gateway: def name: abc ip: x.x.x.x network: temp_net gateway: def ``` Run it as `awk '...' file > tmp && mv tmp file` to change the original file, or you can use `awk -i inplace '...' file` if you have GNU awk 4.\*.
If you're just trying to swap text I'd probably chain seds and then store the output in a temporary file and then cat it back into the original file - probably not the best solution, but its the first that comes to mind. I have this in a script.sh ``` #!/bin/bash while read line do echo $line | sed s/xyz/temp1/g | sed s/abc/temp2/g | sed s/temp1/abc/g | sed s/temp2/xyz/g done < $1 > $2 cat $2 > $1 ``` Then you can simply run: ``` chmod +x script.sh ./script.sh input.txt output.txt ``` Hope that helps.
1,103,668
I wanted to convert my TP-Link WR841N into an Openflow switch for which I followed the guide at kickstartSDN.com Since there was no instruction on which image to download, I accidentally upgraded router with the OpenWRT upgrade image and now I cannot telnet 192.168.1.1 into my router. I have enabled telnet and have also tried telnet through PuTTy. Cannot connect. I can, however, SSH into the device. When I do that I cannot find OpenFlow in the /lib which comes with OpenWRT. Please help, should I revert back to stock firmware of TP-Link? What should I do?
2016/07/21
[ "https://superuser.com/questions/1103668", "https://superuser.com", "https://superuser.com/users/619892/" ]
TP-Link WR841N router supports flash from TFTP server. If you want to revert, download latest firmware for your router with correct HW revision from TP-Link website. Then download some TFTP server. For example you can use <http://tftpd32.jounin.net/>. Run TFTP server in directory with firmware file (or in tftpd32 you can browse this dir). Then you need to rename firmware .bin file to `wr841nv11_tp_recovery.bin`. This is file name valid for router with HW revision 11.X. If you have any other HW revision replace v11 with your revision number. For example for HW revision 10.1 it is `wr841nv10_tp_recovery.bin`. Next step is unconnect all devices from router and connect just computer with TFTP server into any lan port and manually set on this computer IP address to 192.168.0.66 with mask 255.255.255.0. Then power off your router (by button next to power cable) then power on, when red led turn on press and hold `WPS/RESET` button until red led turn off. After that router will request TFTP server on your computer for `wr841nv11_tp_recovery.bin` and flash them. Wait... and Wait... and Wait... After router reboot (signalized by red led) flashing is done and you can set on your computer IP address to getting by DHCP server. Now you can access standard web interface on default gateway address (usually 192.168.0.1).
Go to Luci Web interface <http://TPLIN-IP-ADDRESS> , login (with root), and select choose the System menu, "Backup/Flash firmware", "Restore backup". There are also options to recover it via TFTP described here: <https://wiki.openwrt.org/toh/tp-link/tl-wr841nd>
3,879,607
There is this table that is being generated on a monthly basis. Basically the table structure of all *monthly* tables is the same. Since it would be a lot of work to map the same entity just with a different table name, Is it possible to change the table name of an entity as follows on runtime since they have the same table structure after all? ``` @Entity @Table(name="FOO_JAN2010") // any other ways to generate this dynamically? public class FooJan2010Table { // if we can dynamically set the table name this can be simply named FooTable ... } ``` If not, what approach can you suggest?
2010/10/07
[ "https://Stackoverflow.com/questions/3879607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392222/" ]
I cannot imagine a good way to map this. If this is a legacy database, you'll have a hard time using JPA to access it. If, however, the database layout is under your control, then I'd change it. Having multiple tables with the exact same layout is usually bad design. You could achieve the same result by having only one table with extra columns for year and month. Don't forget to put an index on the two columns.
I could not figure this one either, had a similar requirement. Since my table name changed relatively infrequently (daily) , I ended up defining a DB alias to the "active" table at the RDBMS (I am using DB2) and referenced the table alias name in the @Table annotation. I am fully aware this is not strictly what the OP asked, but thought I would share the experience.
1,551
I have seen many ways to address a bhikkhu, and I'm wondering about the proper way to address a bhikkhu, in writing?
2014/06/27
[ "https://buddhism.stackexchange.com/questions/1551", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/89/" ]
**Bhante** is the preferred mode of address if you are addressing the bhikkhu respectfully; note that it is masculine, so for bhikkhunis, **Ayye** is correct (mostly they use ayya, but I don't think that is technically correct). In English, **Venerable x** and **Reverend x** would also be suitable expressions of respect. If you are addressing them as an equal or as an outsider to the religion, **Venerable x** and **Reverend x** would still be proper, I think, but even **Brother x** would be okay. In Pali, words like **bho** and **ayasma** were also used, meaning something like "good sir" or "friend" by those who didn't hold the bhikkhus in any special esteem. In writing, using the nominative endings (e.g. `o` for `-a` stem names) is not technically correct when addressing the bhikkhu in the second person, e.g.: > > Dear Venerable Yuttadhamm**o**, > > > should really be: > > Dear Venerable Yuttadhamm**a**, > > > In Thailand this distinction has been pretty much lost, whereas in Burma and Sri Lanka they prefer the `a` endings for all references. In Pali, when referring to someone in the third person, you would use the nominative endings, but in the case of corresponding in English, the dictionary stem form is certainly acceptable, as it is with 'buddha', nibbana', etc. Just as we don't say: > > The Buddh**o** was staying in Savatthi. > > > we really shouldn't be saying: > > Venerable Yuttadhamm**o** was staying in Florida. > > > As for regional honorifics, e.g. Ajaan (Ajarn, Ajahn) in Thai, Ashin in Burmese, Hamuduruvo in Sinhala, Lakhun in Khmer, etc., I would suggest they only be used by members of the specific ethnic community; I wouldn't think them appropriate for non-members to use to refer to members (e.g. Westerners calling Thai monks Ajaan) unless speaking in the language from which the word comes. In practical usage, however, Ajaan for example has become so widely used by Thai people (even for monks who clearly aren't their or anyone's teacher) that they often insist that non-Thais use it to refer to Thai monks, which of course would be the wise choice when among such people.
Whatever identifies that specific monk. That's the purpose of a name. I tend to use only their monastic name or, if they teach, I use 'teacher' in their local idiom. Keep things simple & respectable. As for a "proper way", there are as many answers as there are people, I guess.
37,267,811
In a dataframe there are 4 columns col1,col1\_id,col2,col2\_id, I want to locate col\_2 values in col\_1 then if is there any match respective col1\_id should be append to col2\_id. ``` col_1 col1_id col_2 col2_id A 1 NaN NaN B 2 K NaN D 3 A NaN J 4 NaN NaN E 5 H NaN Z 6 NaN NaN H 7 H NaN K 8 Z NaN ``` Any help??, Thanks
2016/05/17
[ "https://Stackoverflow.com/questions/37267811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5435253/" ]
Guava has a [`Table`](http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Table.html) structure that looks like you could use, it has [`containsValue(...)`](http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Table.html#containsValue(java.lang.Object)) method to find particular value, and you can also traverse it. Here's a general [explanation](https://github.com/google/guava/wiki/NewCollectionTypesExplained#table) of the `Table`: > > Typically, when you are trying to index on more than one key at a time, you will wind up with something like `Map<FirstName, Map<LastName, Person>>`, which is ugly and awkward to use. Guava provides a new collection type, Table, which supports this use case for any "row" type and "column" type. > > > You would be most probably interested in following implementation of the `Table` interface: > > `ArrayTable`, which requires that the complete universe of rows and columns be specified at construction time, but is backed by a two-dimensional array to improve speed and memory efficiency when the table is dense. `ArrayTable` works somewhat differently from other implementations > > >
just in this case, I would use a String[][] because you can access the elements with a complexity of O(1) but as I said, only in this case. If the number of the rows or columns is dynamically modified then I'd use `List<List<String>>`, more exactly ArrayList
71,943,129
I have a two divs, Parent and Child. And I need to make Child fill all available height of Parent. But for some reason I have this padding at the bottom. I can remove it only when I use height `105%` for Child But this is obviously not the best solution. I tried to use `align-items: stretch`, but it didn't do anything. ```html <div style={{ width: 100%; height: 92%; display: flex; flex-direction: row; box-sizing: content-box; }} > <div style={{ height: '100%', backgroundColor:'red', }} > </div> </div> ``` [![enter image description here](https://i.stack.imgur.com/MJg8M.png)](https://i.stack.imgur.com/MJg8M.png)
2022/04/20
[ "https://Stackoverflow.com/questions/71943129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17564445/" ]
Use `flex-basis: 100%;` on the flex item. ```css html, body { margin: 0; height: 100%; } body>div:first-child { width: 100%; height: 100%; display: flex; flex-direction: row; box-sizing: content-box; } div>div { flex-basis: 100%; background-color: red; } ``` ```html <div> <div>foo</div> </div> ``` You can see from the second example below it works despite having a static or dynamic sized parent. ```css body>div:first-child { width: 800px; height: 400px; display: flex; flex-direction: row; box-sizing: content-box; } div>div { flex-basis: 100%; background-color: red; } ``` ```html <div> <div>foo</div> </div> ```
Here's a few basics already laid out. I reformatted it a bit too for readability. You had background-color as backgroundColor, as well as 100% to '100%'. If you take this as a basis, just change the width and height of it to 100% and you should have no problem. The larger change was setting the position, and ensuring that you'r setting a height and width. ``` <body style="position: absolute; padding: 0; margin: 0; width: 100vw; height: 100vh; background-color: aquamarine; display: flex; justify-content: center;"> <div style=" position: relative; width: 70%; height: 70%; align-self: center; box-sizing: content-box; border: 2px solid grey; background-color: aliceblue; display: flex; justify-content: center;"> <div style = " position:relative; align-self: center; height: 80%; width: 80%; background-color: red;"> </div> </div> </body> ``` I added a few styles to the body as well to help with understanding what's happening.
29,413,290
I am studying Spring MVC and I have the following doubts: 1. **What exactly is the purpose of the session scope?** Reading the documentation I know that this scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext. And also that a new instance is created once per user session. But when exactly is it used? and for what purpose? Can you make a practical example? 2. **In Spring MVC what is the default scope in the web context?** I know that in Spring the default scope for a bean is **singleton** but what about the scope of a bean in the web context?
2015/04/02
[ "https://Stackoverflow.com/questions/29413290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
1. You use spring session beans for beans which are stateful and their state differs per user. These can be for example preferences of currently logged in user. 2. Default scope of bean in spring is singleton and it is no different in Web Application context. Note than in web environment you can use also REQUEST scoped beans and their lifetime is only per one user request. You should use request scope when session is not necessary and request is sufficient. Also, in portlet environment, you can use another scope which is GLOBAL SESSION. Each portlet has its own indepenednt session and typically those portlets are preffered to have their own state encapsulated only for themselves. But if you need to share session data among different portlets, you will need to use global session scope.
I had the same problem, I was using: ``` @Component @Scope("session") ``` And this made the magic for me: ``` @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) ``` I hope it helps ;-)
8,767,004
Is there a quick and dirty way to get the value of one column from one row? Right now I use something like this: ``` $result = mysql_query("SELECT value FROM table WHERE row_id='1'"); $row = mysql_fetch_array($result); return $row['value']; ``` It seems there must be able to consolidate the second and third lines. These three lines seem like a lot just to get the value from one column from one row. I tried this: $result = mysql\_query("SELECT value FROM table WHERE row\_id='1'"); return mysql\_fetch\_array($result)['value']; But that doesn't work. I am just trying to find out if there is a simpler, more to the point, way of getting one value like this.
2012/01/07
[ "https://Stackoverflow.com/questions/8767004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/700579/" ]
use this hacker) ``` $result = mysql_result(mysql_query("SELECT value FROM table WHERE row_id='1'"), 0); ```
You can use GROUP\_CONCAT ( <http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat> ) function to make them into one field.
44,622,891
I know this kind of question is ask in many different ways, and I know that's annoying for answering so much same question, but as I google it, search in Stackoverflow I can't really find a nice answer, the answer I'm asking is based on views like easy for answering API request (which is in JSON format) and in the view of I'm designing Node.js APP --- ### So here is my case I'm building my own Node.js application somehow like a CMS or blogging platform so imagine I need a place to store all my posts data where should I store in a `MySQL` database or `External JSON file` it's quite confusing I personally prefer JSON since it's nice looking (?) but it's quite hard to use `fs.writefile` and `fs.readfilesync` to update data in the external JSON, but I don't know how to make an API that will give the post data by MySQL database since the API is in the JSON format --- If I have any misunderstood please tell me
2017/06/19
[ "https://Stackoverflow.com/questions/44622891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6616756/" ]
@Laurent's answer gave me the lead but Bazel didn't accept relative paths and required I add both `classes` and `test-classes` folders under `target` to delete the package so I decided to answer with the complete solution: ``` #!/bin/bash #find all the target folders under the current working dir target_folders=$(find . -name target -type d) #find the repo root (currently assuming it's git based) repo_root=$(git rev-parse --show-toplevel) repo_root_length=${#repo_root} #the current bazel package prefix is the PWD minus the repo root and adding a slash current_bazel_package="/${PWD:repo_root_length}" deleted_packages="" for target in $target_folders do #cannonicalize the package path full_package_path="$current_bazel_package${target:1}" classes_full="${full_package_path}/classes" test_classes_full="${full_package_path}/test-classes" deleted_packages="$deleted_packages,$classes_full,$test_classes_full" done #remove the leading comma and call bazel-real with the other args bazel-real "$@" --deleted_packages=${deleted_packages:1} ``` This script was checked in under `tools/bazel` which is why it calls `bazel-real` at the end.
Can you use your shell to find the list of packages to ignore? ``` deleted=$(find . -name target -type d) bazel build //... --deleted_packages="$deleted" ```
169,888
In the school laboratory, a friend tried the famous Cannizzaro reaction for benzaldehyde. Some $\ce{NaOH}$ was added to benzaldehyde, and the solution was stirred for 30 minutes. What came as a surprise was that, after this time interval, a big, bright yellow, gooey-looking blob appeared in the flask. As can be [seen](https://drive.google.com/file/d/1oJOuG74YdOe662LMkXuOvVfzQ7zSGP9A/view?usp=sharing), the blob does not dissolve upon shaking. Whatever reaction occurred here was probably reversible, though, as the blob burst after the solution was transferred into a separation funnel, and the experiment went on to give normal products and reasonable yields, without any obvious anomaly. Does anyone have any idea about what this strange intermediate product might be, or what might have caused it? [![enter image description here](https://i.stack.imgur.com/d6DJJm.jpg)](https://i.stack.imgur.com/d6DJJm.jpg)
2022/12/12
[ "https://chemistry.stackexchange.com/questions/169888", "https://chemistry.stackexchange.com", "https://chemistry.stackexchange.com/users/125707/" ]
Robert DiGiovanni's answer comes close. Benzyl alcohol can indeed precipitate during the intermediate stage, but [it is colorless](https://en.wikipedia.org/wiki/Benzyl_alcohol). Because benzyl alcohol has some weak acidity, it can be partially deprotonated by a base as strong as sodium hydroxide, giving $\ce{C6H5-CH2-O^-Na^+}$. This indeed can impart a yellow color according to [Sigma-Aldrich](https://www.sigmaaldrich.com/US/en/specification-sheet/aldrich/379484), which sells this salt as a solution in the alcohol. When the sodium hydroxide is neutralized upon workup, the benzyl alcohol fully resumes its neutral form $\ce{C6H5-CH2-OH}$, as if nothing untoward had happened.
Benzyl alcohol has a lower solubility (4 g/100 ml) than sodium benzoate (63 g/100 ml) or benzaldehyde (7 gram/100 ml) in water. The presence of NaOH contributed to the "salting out" of the more nonpolar benzyl alcohol, plus some other impurities, forming your "blob". Benzaldedyde and benzyl alcohol are also (surprisingly) slightly denser than water.
1,145,442
I have been trying to figure out how to get rid of these symbols that show up on my Chromebook (on only some webpages): [![symbols](https://i.stack.imgur.com/aaFZp.png)](https://i.stack.imgur.com/aaFZp.png) When I copy them and paste them, they show the correct words. How can I get rid of these words without resetting all of my settings?
2016/11/13
[ "https://superuser.com/questions/1145442", "https://superuser.com", "https://superuser.com/users/656599/" ]
By resting all of my settings it worked, I had probably clicked and changed some setting.
Take a look at the language settings under Language and Input Settings. If you have more than one language, check which is set as "Google Chrome OS is displayed in this language". Also try clearing "cached images and files" under Settings / More Tools / Clear Browsing Data.
40,509,422
As I understand, a BSP (Board Support Package) contains bootloader, kernel and device driver which help OS to work on HW. But I'm confused because OS also contains a kernel. So what is the difference between the kernel in OS and the kernel in BSP?
2016/11/09
[ "https://Stackoverflow.com/questions/40509422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831520/" ]
What a BSP comprises of depends on context; generically it is code or libraries to support a specific board design. That may be provided as generic code from the board supplier for use in a bare-metal system or for integrating with an OS, or it may be specific to a particular OS, or it may even include an OS. In any case it provides board specific support for higher-level software. A kernel is board agnostic (though often processor architecture specific), and makes no direct access to hardware not intrinsic to the processor architecture on which it runs. Typically an OS or application will require a *Hardware Abstraction Layer* (HAL); the HAL may well be built using the BSP, or the BSP may in fact be the HAL. A vendor may even package a HAL and OS and refer to that as a BSP. The term means what it means to whoever is using it - context is everything. For example in VxWorks, WindRiver use the term BSP to refer to the layer that supports the execution of a VxWorks based application on a specific hardware design. A board vendor on the other hand may provide a complete Linux distribution ported to the board and refer to that as a BSP. However and to what extent a particular vendor or developer chooses to support a board is a board support package regardless of how much or how little it may contain.
vxWorks kernel which you can run on a Board contains vxWorks core kernel and "other components" which may change from one environment. Core kernel contains essential programs such as Scheduler, Memory manager, Basic File systems, security features etc. These "other components" which are part of BSP may be optional or may vary from system to system, and helps the core kernel features.
242,830
Setup as follows: * One gateway/firewall * One switch * Two servers behind firewall with 2 NICs each. Each NIC is connected to the switch. The servers are running Ubuntu server. One of the two NICs is now used for all traffic. What I want is for all traffic between the two local servers to use the second currently-unused NICs; how can I do this? I tried to add a static route with the route command but with not so much success...
2011/03/03
[ "https://serverfault.com/questions/242830", "https://serverfault.com", "https://serverfault.com/users/72976/" ]
You're on the right track: a static route is definitely what you want to use to ensure traffic between those hosts travels on a specific interface. Here's a doc that might help: <http://www.ubuntugeek.com/howto-add-permanent-static-routes-in-ubuntu.html>
Sorry, perhaps I totally misunderstand, but can't you just use an internal DNS name to your server (using /etc/hosts) that would map to the IP of the second NIC ?
3,146,358
Ok, this may be not the most clear title, but my question is straightforward. Say we choose $n$ integers $\{ z\_1,\dots,z\_n \}$ and we construct the polynomial $$ P(x) = \prod\_{i=1}^n (x-z\_i). $$ Are the all the roots of the polynomial $P(x) + 1$ irrational?
2019/03/13
[ "https://math.stackexchange.com/questions/3146358", "https://math.stackexchange.com", "https://math.stackexchange.com/users/21719/" ]
It's very easy to show the given relations . And we are gonna work with some basic properties of a field. Let( F ,+, .) Is our field . Now it's given, 1+1=0. Now if , a belongs to F then by using the property, a.(b+c)=a.b+a.c , for all , a,b,c belongs to F , we can write, a.(1+1)=a.1+a.1 = a+a , as '1' is multiplicative identity. So, a+a=0 ,as a.0=0 ....(p) [ a.0= 0 because, 0+0=0 , as 0 is additive identity. Now if a belongs to F then, a.0 +a.0=a.0 Now as a belongs to F , -a belongs to F , as it's the additive inverse. So , -a.0+a.0+a.0=-a.0+a.0 Or, a.0=0 ] Now for some a≠0 , if a belongs to F, the (1/a) belongs to F as (1/a) is multiplicative inverse of a . Now , as a+a=0 , by using a.(b+c)=a.b+a.c , we can write (1/a).(a+a)= a.1/a+a.1/a . As, a.1/a=1 , then 1+1=0.
> > I am a bit unsure as to that the question is asking, do I assume $F$ is a field $\{0,1\}$? > > > Let's read through the requirements of the problem carefully. All that is given to us is: "Let $F$ be a field." So we know $F$ is a field -- we don't know how many elements it has, but all fields at least have a zero element (which is written $0$) and a one element (which is written $1$). > > (a) If $1 + 1 = 0$, show that $a + a = 0$ for all $a \in F$. > > > Now for this part, it does not assume that $F = \{0,1\}$ like you said; but it's just stating a fact about $0$ and $1$, which are elements of the field. So it is stating the fact that $1 + 1 = 0$. Then we have to prove that $a + a = 0$, for any $a \in F$. To do this, try multiplying by $a$ and using the field axioms. > > (b) If $a + a = 0$ for some $a \neq 0$, show that $1 + 1 = 0$ > > > For this part, try "dividing" by $a$ instead of multiplying. What axiom of the fields would let us divide by $a$? Remember that "dividing" really means multiplying by the multiplicative inverse.
54,107,105
In my current project we have permanently disabled form controls. In those cases the form element is replaced with a `span` element on the server-side. That creates code like this: ``` <label for="foo">Foo</label> <span id="foo">Bar</span> ``` **Question 1**: Is having a `label` element without any associated form element ( `input`, `select`, `textarea`) acceptable? **Question 2**: If yes, would we have to remove the `for` attribute in that case (because it references an element that is not a form element)? The spec says: > > The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable form-associated element in the same Document as the label element. > > > <https://www.w3.org/TR/2011/WD-html5-author-20110705/the-label-element.html> > > > Additonal clarification: In the above quote, what exactly is *a labelable form-associated element*?
2019/01/09
[ "https://Stackoverflow.com/questions/54107105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3744304/" ]
As the spec itself says > > The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable form-associated element in the same Document as the label element. > > > *The for attribute may be specified*, meaning it is entirely optional. *labelable form-associated element* means any form element to which a label can be associated. For eg. a label element is not valid for `input type='submit/reset/button'`. **Then why use *for* with label** The benefit is a larger clickable area. When you specify a for attribute with a label, clicking on the label area performs the same action as clicking on the form element with which the label is associated. Hope this resolves your doubts!
As mentioned in an answer referenced by one of the comments, a `<span>` tag should be used in place of a `<label>` when not referring directly to an `<input>` element. It is semantically incorrect to do otherwise. **Correct:** ``` <span>This is an image</span> <img src="https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" /> ``` **Incorrect** ``` <label for="epic-image">This is an image</label> <img src ="https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" /> ```
51,635,155
I have the need to select the last enter for each Passcode for each department. Each department has a 3 digit passcode, each person is given a code based on department. i.e. dept A has numbers 000-099, dept B has 100-199, dept C 201-299 and so on upto 999. The database holds name and passcode for each person. J smith 101 H frank 102 S saop 301 B Chesse 001 H roberts 401 K robert 402 b brety 403 I need a sorted that should loop over all results and return the last number from each dept (in the above case 102,301, 001, 403) Not having a lot of joy, should be something like ``` delimiter # BEGIN declare nmax int unsigned default 9; declare nmin int unsigned default 0; while nmin < nmax do select Passcode from main where Passcode < min*100 limit 1; set nmin = nmin+1; end while; END # delimiter ; ``` Just throws back 1064 error everytime?
2018/08/01
[ "https://Stackoverflow.com/questions/51635155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can write it shorter using `Optional` and mapping: ``` private boolean isSequenceSuccessful() { return Optional.of(doSomething()) .flatMap(result1 -> doAnotherThing(result1)) .flatMap(result2 -> doSomethingElse(result2)) .map(result3 -> doMoreStuff(result3)) .orElse(false); } ``` Or using method references even shorter: ``` private boolean isSequenceSuccessful2() { return Optional.of(doSomething()) .flatMap(this::doAnotherThing) .flatMap(this::doSomethingElse) .map(this::doMoreStuff) .orElse(false); } ``` It depends what you prefer. If you want to keep the intermediate result variables use the lambda version. Since the methods `doAnotherThing` and `doSomethingElse` do return an `Optional<byte[]>`, `Optional.flatMap` is needed to continue the mapping. Otherwise you could change the return type of these methods to return `byte[]` solely. Then you would use `Optinal.map` only, which would be more consistent. The mapping will only be performed as long as a value is present in the `Optional`. If all mappings could be applied the value of the last is returned as result. Otherwise the processing will fail fast and bypass all remainig mappings to the last statement `orElse` and return it's value. This is `false` according to your code.
You could use the `map` method: ``` private boolean isSequenceSuccessful() { Optional<byte[]> result = doSomething().map(this::doAnotherThing) .map(this::doSomethingElse); if (result.isPresent()) return doMoreStuff(result.get()); else return false; } ```
71,019,093
Seems simple to me.. I want to do something along the lines of =Countif(A2:X , "Yes") I would wrap this in an arrayformula with a simple IF(A2:A = "" ,"" ..... I want it to bring back the number of "Yes" per row So if row 2 has 12 yes' then bring back 12, row 3 has 7 so 7 etc This has worked to an extent but brings back the count across the entire range rather than split by row
2022/02/07
[ "https://Stackoverflow.com/questions/71019093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18141666/" ]
Try: ``` =ArrayFormula(IF(A2:A="",,MMult(N(A2:X="Yes"),Sequence(Columns(A2:X))^0))) ``` Or ``` =ArrayFormula(IF(A2:A="",,Len(RegexReplace(RegexReplace(Transpose(Query(Transpose(A2:X),,9^9)),"(?i)\bYes\b","~"),"[^~]",)))) ``` Or ``` =ArrayFormula(IF(A2:A="",,Len(Substitute(Transpose(Query(Transpose(IF(A2:X<>"Yes",,"~")),,9^9))," ",)))) ``` **Update** > > If I wanted to ammend this formula to do if A2:X = No AND A1:X1 contains, for instance (AG) how would I do this? > > > ``` =ArrayFormula(IF(A2:A="",,MMult((A2:X="No")*RegexMatch(A1:X1,"AG"),Sequence(Columns(A2:X))^0))) ```
Though it is a bit tedious, couldn't you do this: ``` =COUNTIF(A2:A, "Yes") + COUNTIF(B2:B, "Yes") + COUNTIF(C2:C, "Yes") + COUNTIF(D2:D, "Yes") + COUNTIF(E2:E, "Yes") + COUNTIF(F2:F, "Yes") + COUNTIF(G2:G, "Yes") + COUNTIF(H2:H, "Yes") + COUNTIF(I2:I, "Yes") + COUNTIF(J2:J, "Yes") + COUNTIF(K2:K, "Yes") + COUNTIF(L2:L, "Yes") + COUNTIF(M2:M, "Yes") + COUNTIF(N2:N, "Yes") + COUNTIF(O2:O, "Yes") + COUNTIF(P2:P, "Yes") + COUNTIF(Q2:Q, "Yes") + COUNTIF(R2:R, "Yes") + COUNTIF(S2:S, "Yes") + COUNTIF(T2:T, "Yes") + COUNTIF(U2:U, "Yes") + COUNTIF(V2:V, "Yes") + COUNTIF(W2:W, "Yes") + COUNTIF(X2:X, "Yes") ```
38,369,685
So I'm new to AngularJS and NodeJS, trying to create a simple ng-table using <http://l-lin.github.io/angular-datatables/#/angularWayDataChange> App.js ``` var app=angular.module('two_way',['datatables', 'ngResource']); ``` Here is the controller, ``` app.controller('two_way_control',function($resource,$scope,$http,$interval){ load_pictures(); load_platform_metadata(); load_platform_values(); load_metadata_map(); angularWayChangeDataCtrl(); function angularWayChangeDataCtrl($resource, DTOptionsBuilder, DTColumnDefBuilder) { var vm = this; vm.persons = $resource('data1.json').query(); vm.dtOptions = DTOptionsBuilder.newOptions().withPaginationType('full_numbers'); vm.dtColumnDefs = [ DTColumnDefBuilder.newColumnDef(0), DTColumnDefBuilder.newColumnDef(1), DTColumnDefBuilder.newColumnDef(2), DTColumnDefBuilder.newColumnDef(3).notSortable() ]; vm.person2Add = _buildPerson2Add(1); vm.addPerson = addPerson; vm.modifyPerson = modifyPerson; vm.removePerson = removePerson; function _buildPerson2Add(id) { return { id: id, firstName: 'Foo' + id, lastName: 'Bar' + id }; } function addPerson() { vm.persons.push(angular.copy(vm.person2Add)); vm.person2Add = _buildPerson2Add(vm.person2Add.id + 1); } function modifyPerson(index) { vm.persons.splice(index, 1, angular.copy(vm.person2Add)); vm.person2Add = _buildPerson2Add(vm.person2Add.id + 1); } function removePerson(index) { vm.persons.splice(index, 1); } } ``` I've added the scripts in proper order 1. Jquery 2. AngularJS 3. AngularJS Route 4. AngularResource The html file is as follows : ``` <body ng-app="two_way" ng-controller="two_way_control"> <html ng-app="two_way" ng-controller="two_way_control"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>Metadata Manager</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.js"></script> <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.5.4/angular-datatables.min.js"></script> <link rel="shortcut icon" type="image/png" href="/angular/favicon.png"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.min.css"> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.min.css"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.5.4/css/angular-datatables.min.css"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script> <script type="text/javascript" class="init"></script> <script src="angular.js"></script> <script src="app.js"></script> <script src="core.js"></script> </head> <body ng-app="two_way" ng-controller="two_way_control"> <form class="form-inline" ng-submit="showCase.addPerson()"> <table datatable="ng" dt-options="showCase.dtOptions" dt-column-defs="showCase.dtColumnDefs" class="row-border hover"> <thead> <tr> <th> <div class="form-group"> <label> <input class="form-control" type="number" name="id" ng-model="showCase.person2Add.id" value=""> </label> </div> </th> <th> <div class="form-group"> <label> <input type="text" class="form-control" name="firstName" ng-model="showCase.person2Add.firstName" value=""> </label> </div> </th> <th> <div class="form-group"> <label> <input type="text" class="form-control" name="lastName" ng-model="showCase.person2Add.lastName" value=""> </label> </div> </th> <th> <div class="form-group"> <button type="submit" class="btn btn-success"><i class="fa fa-plus"></i></button> </div> </th> </tr> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th></th> </tr> </thead> <tbody> <tr ng-repeat="person in showCase.persons"> <td>{{ person.id }}</td> <td>{{ person.firstName }}</td> <td>{{ person.lastName }}</td> <td> <button type="button" ng-click="showCase.modifyPerson($index)" class="btn btn-warning"><i class="fa fa-edit"></i></button> <button type="button" ng-click="showCase.removePerson($index)" class="btn btn-danger"><i class="fa fa-trash-o"></i></button> </td> </tr> </tbody> </table> </form> </body> </html> ``` I'm getting an error of TypeError: $resource is not a function. Not sure, what I'm missing.
2016/07/14
[ "https://Stackoverflow.com/questions/38369685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5569851/" ]
You should be implementing `ImagePickerDelegate` as well, because delegate is of type `ImagePickerDelegate`. Change as follow ``` class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UINavigationBarDelegate, ImagePickerDelegate { ``` Make sure you implement protocol methods. **EDIT 1** You need to implement following methods of `ImagePickerDelegate` ``` public protocol ImagePickerDelegate: class { func wrapperDidPress(imagePicker: ImagePickerController, images: [UIImage]) func doneButtonDidPress(imagePicker: ImagePickerController, images: [UIImage]) func cancelButtonDidPress(imagePicker: ImagePickerController) } ```
if you are implement the `ImagePickerController` then you need to add the following delegate **UINavigationControllerDelegate,UIImagePickerControllerDelegate** on your class at the same time you need to implement the following delegate methods also ``` func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imageView.contentMode = .ScaleAspectFit imageView.image = pickedImage } dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } ```
13,218,551
There's a part of the selection sort algorithm that I don't understand. In the latter part of the code (where the `temp` variable is used, why are `L[i]` and `L[minIndx]` assigned values? Aren't those values themselves? Can't only variables be assigned values? ``` def selSort(L): for i in range(len(L) - 1): minIndx = i minVal = L[i] j = i+1 while j < len(L): if minVal > L[j]: minIndx = j minVal = L[j] j += 1 # aren’t L[i] and L[minIndx] values? How can they be assigned to new values? if minIndx != i: temp = L[i] L[i] = L[minIndx] L[minIndx] = temp ```
2012/11/04
[ "https://Stackoverflow.com/questions/13218551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1552159/" ]
The significance of `static` with a class definition is not whether the class can be instantiated or not, but rather whether the class must be instantiated from within a non-static method of the outer class or not. Non-static inner class instances are tied to the instance that created them -- there's a pointer in the inner class instance back to the creating instance (which is useful in a number of ways). Static inner class instances are not tied to the creating instance. (I worked in the innards of the JVM for about 10 years and I still find this confusing.)
> > Can the class be instantiated with the static keyword in java ? eg : static class c1(){ } > > > Your terminology is incorrect. "Instantiating a class" means creating an instance of the class; i.e. *creating an object*. This is done using the `new` operation. Your example is really about *declaring* a class. Having said that, yes you can declare a class as `static`, but this can only done for a nested class; i.e. a class declared *inside* another class. > > am confused with this and the memory mapping with non static stuff's please help > > > I haven't a clue what you are talking about here. If you need more help on this point, you will need to explain yourself more clearly.
368,354
I have multiple websites on my Windows Server 2003 vps, running apache2 via xampp. I am using openssl. When I only had SSL enabled on the 1 site (I have 2 active), everything worked fine - but now I am having problems. I cannot access <https://liamwli.co.uk> (or the non-secure variant), as google chrome gives an error when I try to access it: > > SSL connection error Unable to make a secure connection to the server. This may be a problem with the server, or it may be requiring > a client authentication certificate that you don't have. Error 107 > (net::ERR\_SSL\_PROTOCOL\_ERROR): SSL protocol error. > > > I can access my other site (techmastersforum.co.uk), but it provides a very stripped down site. When I try to access techmastersforum.co.uk through https, it gives me a certificate error, as it is trying to use the certificate for my other domain. The contents of my httpd-vhosts.conf file is: ``` NameVirtualHost *:80 <VirtualHost *:80> ServerAdmin liam@liamwli.co.uk DocumentRoot "C:/xampp/xampp/htdocs" ServerName techmastersforum.co.uk ServerAlias www.techmastersforum.co.uk ErrorLog "logs/dummy-host.localhost-error.log" CustomLog "logs/dummy-host.localhost-access.log" combined </VirtualHost> <VirtualHost *:443> ServerAdmin liam@liamwli.co.uk DocumentRoot "C:\xampp\xampp\blog" ServerName liamwli.co.uk ServerAlias www.liamwli.co.uk ErrorLog "logs/liamwlissl.log" CustomLog "logs/liamwlissl.log" combined SSLEngine On SSLCertificateFile "C:\xampp\xampp\certs\www_liamwli_co_uk.crt" SSLCertificateKeyFile "C:\xampp\xampp\certs\www_liamwli_co_uk.key" SSLCACertificateFile "C:\xampp\xampp\certs\GeoTrust_CA_Bundle.crt" </VirtualHost> <VirtualHost *:443> ServerAdmin liam@liamwli.co.uk DocumentRoot "C:\xampp\xampp\htdocs" ServerName techmastersforum.co.uk ServerAlias www.techmastersforum.co.uk ErrorLog "logs/tmfssl.log" CustomLog "logs/tmfssl.log" combined SSLEngine On SSLCertificateFile "C:\xampp\xampp\certs\www_techmastersforum_co_uk.crt" SSLCertificateKeyFile "C:\xampp\xampp\certs\www_techmastersforum_co_uk.key" SSLCACertificateFile "C:\xampp\xampp\certs\GeoTrust_CA_Bundle.crt" </VirtualHost> <VirtualHost *:80> ServerAdmin liam@liamwli.co.uk DocumentRoot "C:\xampp\xampp\blog" ServerName liamwli.co.uk ServerAlias www.liamwli.co.uk ErrorLog "logs/dummy-host.localhost-error.log" CustomLog "logs/dummy-host.localhost-access.log" combined </VirtualHost> ``` Does anyone know what the problem I am having is? As I said, I am running Apache2 via XAMPP on a Windows Server 2003 VPS.
2012/03/10
[ "https://serverfault.com/questions/368354", "https://serverfault.com", "https://serverfault.com/users/110064/" ]
I found the solution. There were two gateways defined in /etc/network/interfaces while you simple can't have more then one gateway. It makes no sense. A gateway is an IP you send ALL traffic to. If you would have two, your routing table would have a double entry for dest 0.0.0.0 and the system can't handle this. The double route is what causes the RTNETLINK answer "File exists", meaning there is already a route for 0.0.0.0. I've commented out one of the gateways and now I can ifup both eth0 and eth1. tl;dr delete gateway entries until you've got only one left.
Are you sure you're not in the ILO port?
3,622,853
Rails's `script/server` is just a few lines: ``` #!/usr/bin/env ruby require File.expand_path('../../config/boot', __FILE__) require 'commands/server' ``` I wonder where the `server` file is? I tried a ``` find . -name 'server.*' find . -name 'server' ``` but can't find it
2010/09/01
[ "https://Stackoverflow.com/questions/3622853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/325418/" ]
You have to look for the files in your related gem repo. Your Ruby is located at ``` which ruby ``` Your Rails gem is ``` bundle show rails ``` You can go to the dir with ``` cd `bundle show rails`/lib/commands ``` Then, open `server.rb`
In linux they are more likely to be under ``` /usr/lib/ruby/gems/ruby_version/gems/rails_version/lib/commands ``` ruby\_version and rails\_version depends on which versions you are using. The directory structure will also depend on whether or not you are using rvm, but hopefully you can find your way once you get to the `/usr/lib/ruby/` directory
727,898
Instead of a \*.cs code behind or beside I'd like to have a \*.js file. I'm developing a MVC application an have no need for a code beside because I have controllers, but in certain cases it'd be nice to have a JavaScript code beside or some way to associate the file to the page it's being used on. I suppose I could just name them similarly, but I'm wanting to show the association if possible so there's no question about what the file is for. Typically what I'm talking about is within Visual Studio now under your Global.asax file you will have a plus sign to the left: ``` + Global.asax ``` Once you expand it you'll get ``` - Global.asax Global.asax.cs ``` I'd like the same thing to happen: ``` + Home.spark - Home.spark Home.spark.js ``` **Updated:** My existing csproj file has a path to the actual file, not sure if that's screwing it up. I've currently got: ``` <ItemGroup> <Content Include="Views\User\Profile.spark.js"> <DependentUpon>Views\User\Profile.spark</DependentUpon> </Content> </ItemGroup> <ItemGroup> <Content Include="Views\User\Profile.spark" /> </ItemGroup> ``` and it's simply just showing the files besides each other.
2009/04/07
[ "https://Stackoverflow.com/questions/727898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50711/" ]
Absolutely - but you'll have to edit the project file by hand. Find your "child" file's entry, and change it to be a non-self-closing element, and add a child element to say what it depends on. Here's an example for a .cs file being compiled: ``` <Compile Include="AssertCount.cs"> <DependentUpon>MoreEnumerable.cs</DependentUpon> </Compile> ``` And here's a version I've just mocked up for the files you've specified - although I expect `Home.spark` will have an action associated with it rather than "None": ``` <ItemGroup> <Content Include="Home.spark.js"> <DependentUpon>Home.spark</DependentUpon> </Content> </ItemGroup> <ItemGroup> <None Include="Home.spark" /> </ItemGroup> ``` Visual Studio displays it just as you'd expect it to.
You can edit by hand the project file, has John Skeed suggested, or you can also have a look on the [File Nesting Extension for Visual Studio](https://visualstudiogallery.msdn.microsoft.com/3ebde8fb-26d8-4374-a0eb-1e4e2665070c) that will do the job for you.
43,917,084
I'm facing an issue installing angular-cli locally. I'm on Ubuntu 16.04.2 LTS with following versions of node.js and npm: ``` node: v7.10.0 npm: 3.10.10 ``` I tried to install angluar-cli using the following command: ``` $npm install -g @angular/cli@1.0.0 ``` this worked fine and completed with following warnings: ``` npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/@angular/cli/node_modules/chokidar/node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"}) ``` Now when I'm trying 'ng' command: ``` module.js:472 throw err; ^ Error: Cannot find module 'abbrev' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at Object.<anonymous> (/usr/local/lib/node_modules/@angular /cli/node_modules/nopt/lib/nopt.js:10:14) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) ```
2017/05/11
[ "https://Stackoverflow.com/questions/43917084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/514434/" ]
Just do this on command line: ``` sudo npm uninstall -g @angular/cli sudo npm cache verify sudo npm install -g @angular/cli --unsafe-perm=true --allow-root ``` Found here:[Error: EACCES: permission denied, mkdir...](https://github.com/npm/npm/issues/17268)! This fix the npm EACCES permission denied which brake the angular/cli install on ubuntu 17.04 for me.
I resolve this problem by learning this article : [Fixing npm permissions](https://docs.npmjs.com/getting-started/fixing-npm-permissions#option-2-change-npms-default-directory-to-another-directory)
37,239,344
i have an rss link. sample.rss. i open it in firefox and opens well. in that page i try: ``` $('h3>a>span').each(function () { $(this).parent().after("<p>Test</p>") }) ``` it works but when i try ``` $("h3>a>span").each(function(){ url1 = 'https://www.google.co.in/search?q="'+this.textContent+'"' console.log(url1) $(this).parent().after('<p></p><a href="'+ url1 +'">other</a>') }) ``` it says SyntaxError: An invalid or illegal string was specified console.log shows the url1 variable properly. whats the problem. again the below works ``` $("h3>a>span").each(function(){ url1 = 'https://www.google.co.in/search?q="'+this.textContent+'"' console.log(url1) $(this).parent().after('<p></p><a href="#">other</a>') }) ```
2016/05/15
[ "https://Stackoverflow.com/questions/37239344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897115/" ]
The variable declaration inside `Car()` are local variables, not initializations of the member variables. To initialize the member variables, just do this (it's a [member initializer list](https://stackoverflow.com/q/1711990/3425536)): ``` Car() : carName("X"), carNumber(0) {} ``` and put the definition of `countOfInput` outside the class in a .cpp file (in global scope): ``` int Car::countOfInput = 0; ``` (If you want to reset `countOfInput` to `0` every time the `Car()` constructor is called, you can do that in the constructor body: `countOfInput = 0;`)
The error messages have nothing to do with static variables or static methods. The keyword `friend` is in front of `print()`, make it a non-member function (note the last error message) and then can't access the member variables directly. According to the usage it should be a member function, so just remove the keyword `friend`. And as @tuple\_cat suggested, `const` should be put before the beginning `{`. ``` void print() const { if(Car::countOfInput == 0){ cout << "Error: empty!"; return; } cout << "LIST OF CarS" << endl; cout << "Car Name: " << carName << "\t"; cout << "Car Number: " << carNumber << endl; } ```
9,055,990
I've taken over a wordpress e-comm (although this question is more about profiling generally) site which has a performance issue which seemingly only affects one specific area in the admin section of the CMS. When trying to edit one particular type of product, which has a large number of attributes attached to it, the page effectively causes the browser to crash 99% of the time. I expected this to be down to MySQL queries causing the bottleneck, however when I profiled the db, I got the following results: Total Queries: 174 - Total Time Of MySQL Queries: 0.11370 This suggests the bottleneck is happening elsewhere, but I'm not sure where it could be. If I run YSlow on the page, there is nothing drastic there which would explain the issue, although there are around 20 scripts and stylesheets loaded, so some optimisation could be done there. I'm going to enable an opcode cache library which will improve PHP performance, but is there anything else I can do to try to identify the issue here? Thanks.
2012/01/29
[ "https://Stackoverflow.com/questions/9055990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1176822/" ]
`$dbc = mysqli_connect` must precede all the `mysqli_real_escape_string` calls to make it work. This is because **you need an active mysqli connection to use that function.**
`$dbc = mysqli_connect` must precede all the `mysqli_real_escape_string` calls to make it work. This is because you need an active mysqli connection to use that function. What does this one means. Need it more detailed?
27,137
I'd like to take a folder of images of various sizes and have them cropped into a 600x600 grid square, cut out from the middle of the image. Is there a program that can automatically resize and crop to these dimensions, and then output as a compressed .png file? For images that are smaller than 600x600, I'd like the program to increase the size of the image to that dimension.
2012/09/12
[ "https://photo.stackexchange.com/questions/27137", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/11559/" ]
If you like programing, you can use [Python](http://www.python.org/) (computer language) and an excellent library know has [PIL](http://www.pythonware.com/products/pil/) to crop, re-size, plot histograms, get individual pixel vales, etc... on a programmatic level. Thus you can easily write a simple script to find all images in a folder and perform the operation. This code should do exactly what you want and should process a couple pictures per second, depending on the image size: ``` #Python 2.7, PIL 1.1.7 import Image import glob import os #Function to resize image, preserving aspect ratio def resizeAspect(im, size): w,h = im.size aspect=min(size[0]/float(w), size[1]/float(h)) return im.resize((int(w*aspect),int(h*aspect)),Image.ANTIALIAS) imgList=glob.glob('C:/icons/*.png') #Find all png images in a directory for img in imgList: #Loop through all found images im = Image.open(img) #open the image print "resizing:",os.path.basename(img) w,h = im.size #Get image width and height if min(w,h)<600: #Check if either dimension is smaller then 600 im=resizeAspect(im,(600,600)) #Re-size Image w,h = im.size #update image size center = [int(w/2.0),int(h/2.0)] #Calculate Center box = (center[0]-300, center[1]-300, center[0]+300, center[1]+300) #Defines a box where you want it to be cropped croppedIm = im.crop(box) #Crop the image #croppedIm.show() #Show the cropped image fileName, fileExtension=os.path.splitext(img) croppedIm.save(fileName+'_crop.png', "PNG") #Save the cropped image ``` When you start working on the programmatic level, then the sky is the limit! It is even possible to detect faces and crop around the face, allowing you to intelligently crop thousands of photos... [updated 09/12/2012]
Look for Phatch (Linux, Mac, Windows), it's exactly what you are looking for : <http://photobatch.stani.be/download/index.html>
810,586
Let $c\in\mathbb{R}\setminus\{ 1\}$, $c>0$. Let $U\_i = \left\lbrace U\_{i, 0}, U\_{i, 1}, \dots \right\rbrace$, $U\_i\in\mathbb{R}^\mathbb{N}$. We know that $U\_{n+1,k}=\frac{c^{n+1}}{c^{n+1}-1}U\_{n,k+1}-\frac{1}{c^{n+1}-1}U\_{n,k}$. (As @TedShifrin pointed out, it can also be written $U\_{n+1,k}=U\_{n,k+1}+\frac{1}{c^{n+1}-1}\left(U\_{n,k+1}-U\_{n,k}\right)$) (obviously it implies that if $\lvert U\_k \rvert=n$ then $\lvert U\_{k+1}\rvert=n-1$ etc) Here is what I conjectured: $$\forall h\in\mathbb{N}, U\_{h,0}=\sum\limits\_{p=0}^h\frac{c^{\frac{p^2+p}{2}}}{\left(\prod\limits\_{i=1}^p\left(c^i-1\right)\right)\prod\limits\_{i=1}^{h-p}\left(1-c^i\right)}U\_{0,p}$$ I tested it for some values ($0,1,3,4$) and it seemed to work. Mathematica also verified it up to at least 10. What do you think? If it IS true, how can I prove it? --- Example with $c=4$, $h=2$ : $U\_{1,0}=\frac{4}{3}U\_{0,1}-\frac{1}{3}U\_{0,0}$, $U\_{1,1}=\frac{4}{3}U\_{0,2}-\frac{1}{3}U\_{0,1}$ $U\_{2,0}=\frac{16}{15}U\_{1,1}-\frac{1}{15}U\_{1,0}$ Therefore $U\_{2,0}=\frac{16}{15}\left(\frac{4}{3}U\_{0,2}-\frac{1}{3}U\_{0,1}\right)-\frac{1}{15}\left(\frac{4}{3}U\_{0,1}-\frac{1}{3}U\_{0,0}\right)$ $U\_{2,0}=U\_{0,0}\left(\frac{1}{15\times 3}\right)-U\_{0,1}\left(\frac{16}{15\times 3}+\frac{4}{15\times 3}\right)+U\_{0,2}\left(\frac{16\times 4}{15\times 3}\right)$ $U\_{2,0}=U\_{0,0}\left(\frac{1}{45}\right)-U\_{0,1}\left(\frac{4}{9}\right)+U\_{0,2}\left(\frac{64}{45}\right)$ The formula gives us : $U\_{2,0}=U\_{0,0}\left(\frac{4^0}{(1-4)(1-16)}\right)+U\_{0,1}\left(\frac{4^1}{(4-1)(1-4)}\right)+U\_{0,2}\left(\frac{4^3}{(16-1)(4-1)}\right)$ $U\_{2,0}=U\_{0,0}\left(\frac{1}{45}\right)+U\_{0,1}\left(\frac{-4}{9}\right)+U\_{0,2}\left(\frac{64}{45}\right)$
2014/05/26
[ "https://math.stackexchange.com/questions/810586", "https://math.stackexchange.com", "https://math.stackexchange.com/users/150347/" ]
Let $S$ be the shift operator on sequences. That is, for any sequence, $a$, $$ (Sa)\_i=a\_{i+1}\tag{1} $$ Then, the recursion becomes $$ U\_n=\frac{c^nS-I}{c^n-1}U\_{n-1}\tag{2} $$ Consider the polynomial $$ \prod\_{k=1}^n\left(c^kx-1\right)=\sum\_{p=0}^na\_{n,p}x^p\tag{3} $$ We have that $a\_{n,0}=(-1)^n$ and since each $x=c^{-k}$, for $1\le k\le n$, is a root of $(3)$, we have $$ \begin{align} 0 &=\begin{bmatrix} 1&c^{-1}&c^{-2}&\cdots&c^{-n}\\ 1&c^{-2}&c^{-4}&\cdots&c^{-2n}\\ 1&c^{-3}&c^{-6}&\cdots&c^{-3n}\\ \vdots&\vdots&\vdots&\ddots&\vdots\\ 1&c^{-n}&c^{-2n}&\cdots&c^{-n^2} \end{bmatrix} \begin{bmatrix} a\_{n,0}\\ a\_{n,1}\\ a\_{n,2}\\ \vdots\\ a\_{n,n} \end{bmatrix}\\ &=\begin{bmatrix} 1&1&1&\cdots&1\\ 1&c^{-1}&c^{-2}&\cdots&c^{-n}\\ 1&c^{-2}&c^{-4}&\cdots&c^{-2n}\\ \vdots&\vdots&\vdots&\ddots&\vdots\\ 1&c^{1-n}&c^{2-2n}&\cdots&c^{n-n^2} \end{bmatrix} \begin{bmatrix} c^{-0}a\_{n,0}\\ c^{-1}a\_{n,1}\\ c^{-2}a\_{n,2}\\ \vdots\\ c^{-n}a\_{n,n} \end{bmatrix}\tag{4} \end{align} $$ That is, $c^{-p}a\_{n,p}$ is proportional to $(-1)^p$ times the determinant of the submatrix gotten by removing column $p$ from the matrix in $(4)$. Each of those submatrices is a [Vandermonde matrix](http://en.wikipedia.org/wiki/Vandermonde_matrix). Thus, we can compute $$ \begin{align} c^{-p}a\_{n,p} &=\frac{\displaystyle(-1)^p\prod\_{k=1}^n(1-c^{-k})}{\displaystyle\prod\_{k=0}^{p-1}(c^{-p}-c^{-k})\prod\_{k=p+1}^n(c^{-k}-c^{-p})}\\ &=\frac{\displaystyle c^{p(p-1)/2}\prod\_{k=1}^n(c^k-1)}{\displaystyle\prod\_{k=1}^p(c^k-1)\prod\_{k=1}^{n-p}(1-c^k)}\tag{5} \end{align} $$ Thus, using $(3)$ and $(5)$, we get $$ \prod\_{k=1}^n\frac{c^kx-1}{c^k-1}=\sum\_{p=0}^n\frac{\displaystyle c^{p(p+1)/2}}{\displaystyle\prod\_{k=1}^p(c^k-1)\prod\_{k=1}^{n-p}(1-c^k)}x^p\tag{6} $$ Combining $(2)$ (repeatedly) and $(6)$ yields $$ \begin{align} U\_n &=\left[\prod\_{k=1}^n\frac{c^kS-I}{c^k-1}\right]U\_0\\[6pt] &=\sum\_{p=0}^n\frac{\displaystyle c^{p(p+1)/2}}{\displaystyle\prod\_{k=1}^p(c^k-1)\prod\_{k=1}^{n-p}(1-c^k)}S^pU\_0\tag{7} \end{align} $$ Element $0$ of $(7)$ is the equation desired. --- **Finding A Perpendicular Vector** Suppose we have $n$ linearly independent vectors, $\{v\_k\}$, in $\mathbb{R}^{n+1}$ and we want to find a vector perpendicular to all of them. Arrange the $n$ vectors as the bottom rows of an $n{+}1\times n{+}1$ matrix, with an unknown vector, $u$, as the top row: $$ M=\begin{bmatrix} u\_0&u\_1&u\_2&\dots&u\_n\\ v\_{1,0}&v\_{1,1}&v\_{1,2}&\dots&v\_{1,n}\\ v\_{2,0}&v\_{2,1}&v\_{2,2}&\dots&v\_{2,n}\\ \vdots&\vdots&\vdots&\ddots&\vdots\\ v\_{n,0}&v\_{n,1}&v\_{n,2}&\dots&v\_{n,n}\\ \end{bmatrix}\tag{8} $$ Using [Laplace's formula](http://en.wikipedia.org/wiki/Determinant#Laplace.27s_formula_and_the_adjugate_matrix) for the determinant, we get $$ \det(M)=u\_0\det(M\_0)-u\_1\det(M\_1)+u\_2\det(M\_2)-u\_3\det(M\_3)+\dots\tag{9} $$ where $M\_k$ is the $n\times n$ matrix formed by removing the top row and column $k$ from $M$. If we replace $u$ by any of the $v\_k$, $\det(M)=0$. That is, the vector $$ \begin{bmatrix}\det(M\_0),-\det(M\_1),\det(M\_2),\dots,(-1)^n\det(M\_n))\end{bmatrix}\tag{10} $$ is perpendicular to each of the $v\_k$. --- **A Shortcut With Particular Vandermonde Determinants** Suppose we have the $n\times n{+}1$ Vandermonde matrix $$ X=\begin{bmatrix} x\_0^0&x\_1^0&x\_2^0&\dots&x\_n^0\\ x\_0^1&x\_1^1&x\_2^1&\dots&x\_n^1\\ x\_0^2&x\_1^2&x\_2^2&\dots&x\_n^2\\ \vdots&\vdots&\vdots&\ddots&\vdots\\ x\_0^{n-1}&x\_1^{n-1}&x\_2^{n-1}&\dots&x\_n^{n-1}\\ \end{bmatrix}\tag{11} $$ Let $X\_p$ be the submatrix of $X$ with column $p$ removed. Then, using the formula for the determinant of a Vandermonde matrix, we have $$ \det(X\_p)=\frac{\displaystyle\prod\_{0\le j\lt k\le n}(x\_k-x\_j)}{\displaystyle\prod\_{i=0}^{p-1}(x\_p-x\_i)\prod\_{i=p+1}^n(x\_i-x\_p)}\tag{12} $$ that is, the products in the denominator remove the terms in the numerator that contain $x\_p$. Since the numerator in $(12)$ does not depend on $p$, we can factor out the numerator, for example, when computing a vector parallel to $$ \begin{bmatrix} \det(X\_0),-\det(X\_1),\det(X\_2),\dots,(-1)^n\det(X\_n) \end{bmatrix}\tag{13} $$ as is done in $(5)$.
Here’s what I hope is a good start. I’m stuck at the very end, but maybe you can finish it up. (It is homework, after all.) The special functions experts might have a quicker way to answer this, I imagine. For $h=0$, the desired result is exactly what “we know.” Use induction, and assume the result for $h<M$. $$ \begin{align} U\_{M,0}&=\frac{c^M}{c^M-1}(U\_{M-1,1})-\frac{1}{c^M-1}(U\_{M-1,0})\\ &=\frac{c^M}{c^M-1}(U\_{M-1,1})- \frac{1}{c^M-1}\sum\limits\_{p=0}^{M-1}\frac{c^{\frac{p^2+p}{2}}}{\left(\prod\limits\_{i=1}^p\left(c^i-1\right)\right)\prod\limits\_{i=1}^{{M-1}-p}\left(1-c^i\right)}U\_{0,p}\\ &=\frac{c^M}{c^M-1}(U\_{M-1,1})+\frac{1}{1-c^M}\sum\limits\_{p=0}^{M-1}\frac{c^{\frac{p^2+p}{2}}}{\left(\prod\limits\_{i=1}^p\left(c^i-1\right)\right)\dfrac{\prod\limits\_{i=1}^{{M}-p}\left(1-c^i\right)}{1-c^{M{\color{red}{-p}}}}}U\_{0,p} \\ &\mbox{\*\*\* Earlier answer omitted the part in red \*\*\*}\\ &=\frac{c^M}{c^M-1}(U\_{M-1,1})+\frac{1}{1-c^M}\sum\limits\_{p=0}^{M-1}\frac{c^{\frac{p^2+p}{2}}}{\left(\prod\limits\_{i=1}^p\left(c^i-1\right)\right)\dfrac{\prod\limits\_{i=1}^{{M}-p}\left(1-c^i\right)}{1-c^{M{-p}}}}U\_{0,p} \\ &=\frac{c^M}{c^M-1}(U\_{M-1,1})+\frac{1}{\prod\limits\_{i=1}^M (1-c^i)}+\frac{1}{1-c^M}\sum\limits\_{p=1}^{M-1}\frac{c^{\frac{p^2+p}{2}}}{\prod\limits\_{i=1}^p\left(c^i-1\right)\prod\limits\_{i=1}^{{M}-1-p}\left(1-c^i\right)}U\_{0,p}. \end{align}$$ The proof will be complete if you can show that this equals $$\sum\limits\_{p=0}^M\frac{c^{\frac{p^2+p}{2}}}{\left(\prod\limits\_{i=1}^p\left(c^i-1\right)\right)\prod\limits\_{i=1}^{{M}-p}\left(1-c^i\right)}U\_{0,p},$$ which after correcting my earlier error, I have no idea how to do. Another approach seems needed.
74,217
I have already gone through [this question](https://travel.stackexchange.com/questions/4868/empty-suitcase-on-flight) about empty suitcases. However, it does not address protecting the suitcases from possible damage. My friend (who is a foreign student studying in Germany) would like to take 2 empty large suitcases to India so that he can bring them back filled up when he returns. However, he feels the suitcases might get damaged when he checks them in empty while travelling from Germany. I know airlines usually have no problem taking empty suitcases, but I would like to know methods for protecting the suitcases when they are empty. The suitcases cannot be placed one inside the other. Is it a good idea to wrap them at the airport or something along those lines? **How can I protect empty (close to empty) suitcases from damage?**
2016/07/24
[ "https://travel.stackexchange.com/questions/74217", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/46639/" ]
I had to do something slightly similar once with some half-empty suitcases that would have large heavy things piled on top of them while moving house. What worked quite well for me was to take large, sturdy, readily available bag-like things such as: * Heavy duty bin bags * Duvet covers, large pillow cases * Sleeping bag liners ...open them out to get a lot of air into them, then firmly tie them shut, trapping air making them act like flexible-shaped cushions. Because these bags aren't completely full, they can be manoeuvred to fill whatever shaped space is needed quite well, and there's less risk of popping than, say, balloons (the "bang" of popping balloons coming from inside a bag when a heavy bag is put on top of yours might concern a baggage handler...). Things like bin bags are also very useful for compartmentalising your packing on the way back, so they're not being wasted.
I thought there might be some dedicated packing material for doing this and there is [this](http://rads.stackoverflow.com/amzn/click/B0141MR8YI) on Amazon as an example, but it doesn't look very practical. However, there are some super cheap [airbeds](http://www.walmart.com/ip/Intex-Twin-Classic-Downy-Airbed-Mattress/20449351) around which your friend might be able to find from somewhere like Aldi. Just partially inflate enough to fill the suitcase. The added bonus is he could use it at the seaside in India... There's always bubble wrap from a self-storage company, or waste cardboard boxes, or just buying a load of balloons and blowing them up. Perhaps some cheap plastic footballs that he could perhaps give away on arrival.
30,461,969
I try to make a local HTTPS connection to a XMLRPC api. Since I upgrade to python 2.7.9 that [enable by default certificates verification](https://www.python.org/dev/peps/pep-0476/), I got a CERTIFICATE\_VERIFY\_FAILED error when I use my API ``` >>> test=xmlrpclib.ServerProxy('https://admin:bz15h9v9n@localhost:9999/API',verbose=False, use_datetime=True) >>> test.list_satellites() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/xmlrpclib.py", line 1233, in __call__ return self.__send(self.__name, args) File "/usr/local/lib/python2.7/xmlrpclib.py", line 1591, in __request verbose=self.__verbose File "/usr/local/lib/python2.7/xmlrpclib.py", line 1273, in request return self.single_request(host, handler, request_body, verbose) File "/usr/local/lib/python2.7/xmlrpclib.py", line 1301, in single_request self.send_content(h, request_body) File "/usr/local/lib/python2.7/xmlrpclib.py", line 1448, in send_content connection.endheaders(request_body) File "/usr/local/lib/python2.7/httplib.py", line 997, in endheaders self._send_output(message_body) File "/usr/local/lib/python2.7/httplib.py", line 850, in _send_output self.send(msg) File "/usr/local/lib/python2.7/httplib.py", line 812, in send self.connect() File "/usr/local/lib/python2.7/httplib.py", line 1212, in connect server_hostname=server_hostname) File "/usr/local/lib/python2.7/ssl.py", line 350, in wrap_socket _context=self) File "/usr/local/lib/python2.7/ssl.py", line 566, in __init__ self.do_handshake() File "/usr/local/lib/python2.7/ssl.py", line 788, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581) >>> import ssl >>> ssl._create_default_https_context = ssl._create_unverified_context >>> test.list_satellites() [{'paired': True, 'serial': '...', 'enabled': True, 'id': 1, 'date_paired': datetime.datetime(2015, 5, 26, 16, 17, 6)}] ``` Does exists a pythonic way to disable default certificate verification in python 2.7.9 ? I don't realy know if it's good to change "private" global SSL attribute (`ssl._create_default_https_context = ssl._create_unverified_context`)
2015/05/26
[ "https://Stackoverflow.com/questions/30461969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866886/" ]
I think another way to disable certificate verification could be: ``` import xmlrpclib import ssl s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE test=xmlrpclib.Server('https://admin:bz15h9v9n@localhost:9999/API',verbose=0,context=s) ```
With Python 2.6.6 for example: ``` s = xmlrpclib.ServerProxy('https://admin:bz15h9v9n@localhost:9999/API', transport=None, encoding=None, verbose=0,allow_none=0, use_datetime=0) ``` It works for me...
41,153,221
I'm looking to change the background color of all pages with /cutticket in the URL using jquery. Right now I have the following but I am not seeing any visible change. No console errors at the moment. ``` if (window.location.href.indexOf("/cutticket") > -1) { document.body.style.backgroundColor = "red"; } ```
2016/12/14
[ "https://Stackoverflow.com/questions/41153221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2948393/" ]
Your code works. Simply include: ``` <script> if (window.location.href.indexOf("/cutticket") > -1) { document.body.style.backgroundColor = "red"; } </script> ``` just before: ``` </body> </html> ``` **Reason:** The script makes a reference to `<body>` - so for the script to work properly, the browser must have parsed `<body>` in the markup before it starts parsing the script.
I had done it something like this: ``` <script> var base = "http://0.0.0.0:8881" var url = document.URL; if (!(url == base + "/asda")) { document.body.style.backgroundColor = "red"; } </script> ```
31,928,868
When it comes to the M Developer Preview runtime permissions, according to [Google](https://plus.google.com/+AndroidDevelopers/posts/8aaudh5n1zM?linkId=16190516): 1. If you have never asked for a certain permission before, just ask for it 2. If you asked before, and the user said "no", and the user then tries doing something that needs the rejected permission, you should prompt the user to explain why you need the permission, before you go on to request the permission again 3. If you asked a couple of times before, and the user has said "no, and stop asking" (via the checkbox on the runtime permission dialog), you should just stop bothering (e.g., disable the UI that requires the permission) However, we only have one method, `shouldShowRequestPermissionRationale()`, returning a `boolean`, and we have three states. We need a way to distinguish the never-asked state from the stop-asking state, as we get `false` from `shouldShowRequestPermissionRationale()` for both. For permissions being requested on first run of the app, this is not a big problem. There are plenty of recipes for determining that this is probably the first run of your app (e.g., `boolean` value in `SharedPreferences`), and so you assume that if it's the first run of your app, you're in the never-asked state. However, part of the vision of runtime permissions is that you might not ask for all of them up front. Permissions tied to fringe features you might only ask for later on, when the user taps on something that requires that permission. Here, the app may have been run many times, for months, before we all of a sudden need to request another permission. In those cases, are we supposed to track whether or not we asked for the permission ourselves? Or is there something in the Android M API that I am missing that tells us whether we asked before or not?
2015/08/10
[ "https://Stackoverflow.com/questions/31928868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115145/" ]
I know I am posting very late, but detailed example may be helpful for someone. **What I have noticed is, if we check the shouldShowRequestPermissionRationale() flag in to onRequestPermissionsResult() callback method, it shows only two states.** State 1:-Return true:-- Any time user clicks Deny permissions (including the very first time. State 2:-Returns false :- if user select s “never asks again. Here is an example with multiple permission request:- The app needs 2 permissions at startup . SEND\_SMS and ACCESS\_FINE\_LOCATION (both are mentioned in manifest.xml). As soon as the app starts up, it asks for multiple permissions together. If both permissions are granted the normal flow goes. [![enter image description here](https://i.stack.imgur.com/TmOCS.png)](https://i.stack.imgur.com/TmOCS.png) ``` public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(checkAndRequestPermissions()) { // carry on the normal flow, as the case of permissions granted. } } private boolean checkAndRequestPermissions() { int permissionSendMessage = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS); int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); List<String> listPermissionsNeeded = new ArrayList<>(); if (locationPermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.SEND_SMS); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS); return false; } return true; } ``` In case one or more permissions are not granted, activityCompat.requestPermissions() will request permissions and the control goes to onRequestPermissionsResult() callback method. **You should check the value of shouldShowRequestPermissionRationale() flag in onRequestPermissionsResult() callback method.** There are only two cases:-- **Case 1:**-Any time user clicks Deny permissions (including the very first time), it will return true. So when the user denies, we can show more explanation and keep asking again. **Case 2:**-Only if user select “never asks again” it will return false. In this case, we can continue with limited functionality and guide user to activate the permissions from settings for more functionalities, or we can finish the setup, if the permissions are trivial for the app. **CASE- 1** [![Case - 1 ](https://i.stack.imgur.com/nbTo6.png)](https://i.stack.imgur.com/nbTo6.png) **CASE- 2** [![Case - 2](https://i.stack.imgur.com/rQqYp.png)](https://i.stack.imgur.com/rQqYp.png) ``` @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { Log.d(TAG, "Permission callback called-------"); switch (requestCode) { case REQUEST_ID_MULTIPLE_PERMISSIONS: { Map<String, Integer> perms = new HashMap<>(); // Initialize the map with both permissions perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED); perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); // Fill with actual results from user if (grantResults.length > 0) { for (int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); // Check for both permissions if (perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "sms & location services permission granted"); // process the normal flow //else any one or both the permissions are not granted } else { Log.d(TAG, "Some permissions are not granted ask again "); //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission // // shouldShowRequestPermissionRationale will return true //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup. if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { showDialogOK("SMS and Location Services Permission required for this app", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: checkAndRequestPermissions(); break; case DialogInterface.BUTTON_NEGATIVE: // proceed with logic by disabling the related features or quit the app. break; } } }); } //permission is denied (and never ask again is checked) //shouldShowRequestPermissionRationale will return false else { Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG) .show(); // //proceed with logic by disabling the related features or quit the app. } } } } } } private void showDialogOK(String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", okListener) .create() .show(); } ```
Regarding MLProgrammer-CiM's answer, I have an idea of how to solve the scenario in which the user revokes the permission after the boolean stored in SharedPrefrences is already true, simply create another constant boolean, if the first one called for example: `Constant.FIRST_TIME_REQUEST` (which its default state will be true) the second one will be called `Constant.PERMISSION_ALREADY_GRANTED` (which will be false on default) On `onRequestPermissionsResult` if permission was granted you change its value to true, of course. Now, in the part where you want to ask permission with pre-explanation, write something like that: ``` if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { SharedPreferences sp = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE); boolean isPermissionGranted = sp.getBoolean(Constant.PERMISSION_ALREADY_GRANTED, false); if (isPermissionGranted) { sp.putBoolean(Constant.PERMISSION_ALREADY_GRANTED, false); sp.putBoolean(Constant.FIRST_TIME_REQUEST, true); } if (ActivityCompat.shouldShowRequestPermissionRationale(activity, androidPermissionName) || sp.getBoolean(Constant.FIRST_TIME_REQUEST, true) ) { showDialogExplanation(); } } ``` that way even if the user will remove the permission, the boolean will be set to false again. good luck, I hope it'll help. Shlo
16,490,323
Say my data looks like this: ``` Item 1 Item 2 Item 3 SubKey1:SubValue1 SubKey2:SubValue2 Item 4 SubKey1:SubValue1 Item 5 SubKey1:SubValue1 SubKey2:SubValue2 SubKey3:SubValue3 ``` Is there a data structure that supports this or would I need to create a new type?
2013/05/10
[ "https://Stackoverflow.com/questions/16490323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1406734/" ]
If everything that you want is a string, you could use this: ``` Dictionary<string, Dictionary<string, string>> ``` You would use it like this: ``` var myItems = new Dictionary<string, Dictionary<string, string>>(); myItems.Add("Item 1", null); myItems.Add("Item 2", null); var subDictionary1 = new Dictionary<string, string>(); subDictionary1.Add("subKey1", "subValue1"); subDictionary1.Add("subKey2", "subValue2"); myItems.Add("Item 3", subDictionary1); var subDictionary2 = new Dictionary<string, string>(); subDictionary2.Add("subKey1", "subValue1"); myItems.Add("Item 4", subDictionary2); var subDictionary3 = new Dictionary<string, string>(); subDictionary3.Add("subKey1", "subValue1"); subDictionary3.Add("subKey2", "subValue2"); subDictionary3.Add("subKey3", "subValue3"); myItems.Add("Item 5", subDictionary3); ```
From what I see you could use a `List<Dictionary<string, string>>` In the first two items you could just have an empty dictionary (or a null). But it depends a bit on what you want to do with it.
42,531,286
Have a XML string like below: ``` <stages> <params/> <test description=""/> </stages> ``` I want to add the following XML string after `<test desc.../>` tag OR before the end of stages i.e. `</stages>` ``` <stage id="myId" level="1"> ``` and all subsequent stages. Post-addition it should like ``` <stages> <params/> <test description=""/> <stage id="myId" level="1"/> <stage id=.../> ... </stages> ``` I am trying to do something like this: ``` var stageNode = document.createTextNode( "<stage id=\"myId\" level=\"1\">") ); var root = document.getElementsByTagName("test").parentNode; console.log(document.getElementsByTagName("test")); //<-- giving [] in console log and root is undefined; though the element is there var stages = root.getElementsByTagName("stage"); root.insertBefore(stageNode,stages.nextSibling); ``` How can I do this in JavaScript or JQuery? Using DocumentBuilder or DocumentBuilderFactory is giving me "Unexpected identifier" error. Is there an easier way to do the above using document builder in Javascript (as in Java)?
2017/03/01
[ "https://Stackoverflow.com/questions/42531286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/786676/" ]
You are including a folder within the search pattern which isn't expected. According to the [docs](https://msdn.microsoft.com/en-us/library/wz42302f(v=vs.110).aspx): > > searchPattern Type: System.String The search string to match against > the names of files in path. This parameter can contain a combination > of valid literal path and wildcard (\* and ?) characters (see Remarks), > but doesn't support regular expressions. > > > With this in mind, try something like this: ``` String[] files = Directory.GetFiles(@"C:\Users\user", "test*.doc", SearchOption.AllDirectories) .Where(file => file.Contains("\\Debug\\")) .ToArray(); ``` This will get ALL the files in your specified directory and return the ones with `Debug` in the path. With this in mind, try and keep the search directory narrowed down as much as possible. Note: My original answer included [EnumerateFiles](https://msdn.microsoft.com/en-us/library/dd413233(v=vs.110).aspx) which would work like this (making sure to pass the [search option](https://msdn.microsoft.com/en-us/library/dd383571(v=vs.110).aspx) (thanks @CodeCaster)): ``` String[] files = Directory.EnumerateFiles(@"C:\Users\user", "test*.doc", SearchOption.AllDirectories) .Where(file => file.Contains("\\Debug\\")) .ToArray(); ``` I've just run a test and the second seems to be slower however it might be quicker on a larger folder. Worth keeping in mind. Edit: Note from `@pinkfloydx33` > > I've actually had that practically take down a system that I had > inherited. It was taking so much time trying to return the array and > killing the memory footprint as well. Problem was diverted converting > over to the enumerable counterparts > > > So using the second option would be safer for larger directories.
The second parameter, the search pattern, works only for filenames. So you'll need to iterate the directories you want to search, then call `Directory.GetFiles(directory, "test*.doc")` on each directory. How to write that code depends on how robust you want it to be and what assumptions you want to make (e.g. *"all Debug directories are always two levels into the user's directory"* versus *"the Debug directory can be at any level into the user's directory"*). See [How to recursively list all the files in a directory in C#?](https://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c). Alternatively, if you want to search *all* subdirectories and then discard files that don't match your preferences, see [Searching for file in directories recursively](https://stackoverflow.com/questions/9830069/searching-for-file-in-directories-recursively): ``` var files = Directory.GetFiles(@"C:\Users\user", "test*.doc", SearchOption.AllDirectories) .Where(f => f.IndexOf(@"\debug", StringComparison.OrdinalIgnoreCase) >= 0); ``` But note that this may be bad for performance, as it'll scan irrelevant directories.
67,851,335
I have two lists of data frames. In each list a data frame has a column with the same name and values. As an example: ``` x <- list(data.frame(i=as.character(1:5),x=rnorm(5),z=rnorm(5)), data.frame(i=as.character(1:5),x=rnorm(5),z=rnorm(5))) y <- list(data.frame(i=as.character(5:1),x1=rnorm(5),z1=rnorm(5)), data.frame(i=as.character(5:1),x1=rnorm(5),z1=rnorm(5))) ``` I would like to combine the two lists into one so that each element of the new list is a data frame with the following columns: `i, x, z, x1, z1`). That is I would like a list of two data frames each with five rows and the five columns I mentioned. I could not find a solution to this (for example, found how to concatenate dfs in a list in one df). I thought to use `lapply` and pass the function merge(`x,y, by= i)`, but I do not know what the first argument (I.e. data used) should be. Please note that the values in the common column are not in the same order (in the example they are reversed but in my data they are mixed). So let me know if your solution would require ordering the column first. Thanks.
2021/06/05
[ "https://Stackoverflow.com/questions/67851335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4801942/" ]
It looks like this is what you want: ``` map2(x, y, ~ inner_join(.x, .y)) ``` ``` [[1]] i x z x1 z1 1 1 0.7715183 -0.6933826 -0.3335239 0.5957587 2 2 -0.3824746 -0.7248827 -1.6736241 -1.2248904 3 3 0.3412777 -0.3711940 0.9334678 0.4043867 4 4 -0.4225862 -1.6653314 1.0369985 1.1808140 5 5 0.7468157 0.1704126 -0.1470796 -1.6237296 [[2]] i x z x1 z1 1 1 0.69264103 -0.6640663 -0.2253319 0.26323254 2 2 -0.07861775 0.7914119 0.3725911 0.02854667 3 3 -0.86588724 -0.5519633 -1.5114177 -0.14283509 4 4 1.16069947 1.1299540 -0.4207173 -1.15829758 5 5 2.13867104 -0.9668079 0.1082068 -2.74714297 ```
Using `data.table` ``` library(data.table) Map(function(u, v) setDT(u)[v, on = .(i)], x, y) ```
25,624,213
Whenever I use `$model->attributes=$_POST['Users']` ,it saves Data from User form. When I use `$model->setAttributes($_POST['Users'])`,it also saves Data from User form. So please can anyone clarify the difference between the two codes ?
2014/09/02
[ "https://Stackoverflow.com/questions/25624213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2240375/" ]
There is absolutely no difference. When you try to assign a property that is not defined as a PHP class property (such as `attributes` here) on a [component](http://www.yiiframework.com/doc/guide/1.1/en/basics.component), Yii by convention calls the similarly-named setter method `setAttributes` instead. If no such method exists an exception is thrown. Since a Yii model is a component and models do not have an `attributes` property, the setter method is called even when you use the first form. All of this is also [explained in detail](http://www.yiiframework.com/doc/guide/1.1/en/basics.component#defining-and-using-a-component-property) in the manual.
There is no difference. array\_merge used to merge attributes, if set later
37,392
When reading fantasy novels, I have as a rule been left with the impression that exact timekeeping is either avoided as a topic, or referred to only vaguely and obliquely. In many cases, the author would freely use "hours" as a metonymy for a part of the day spent doing something, however never actually imply that these hours can be counted and consist of minutes and seconds, or let his elven queen invite the orc delegates to convene in her throne room at precisely 10.30 in the morning for trade negotiations. It is true that for most intents and purposes in a medieval fantasy world, the protagonists can safely and realistically use dawn, morning, noon, etc. when referring to the time of day, just as our ancestors in the real world didn’t need to worry that they will oversleep for the autumn harvest or be late for an evening round of beers at the local inn. Still, I believe that a developed fantasy society does need to keep track of time and that there are situations when coordination of efforts between numerous persons is essential and can only be achieved if people have a way of keeping exact time. In my opinion, simply transferring our timekeeping system into a fantasy world seems lazy and, most of all, robs this world of its rugged romanticism and faux historic flair. Yet in order to be believable and feel natural when referred to in prose, this system needs to convey the sense that it has developed organically in the course of the world’s history. Therefore I ask you: ***What is a realistic way of creating a unique timekeeping system for a fantasy society that is mainly high to late medieval in its phase of development?*** *(The planet of this world is identical to Earth from an astronomical perspective, so there’s no need to account for anything strange and exotic in the day/night cycle. There is also no magic whatsoever.)* Thank you in advance for your thoughts.
2016/03/04
[ "https://worldbuilding.stackexchange.com/questions/37392", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/18451/" ]
Clocks are not the only way to keep track of time. I think we all agree that the purpose of clocks is to synchronize the activity of multiple people over an area. We like to say things like "At 12:30 I will go to the store." However, is is also possible to synchronize actions based on events. "I will go to the store after the Blacksmith I am apprenticing finishes eating his lunch." One can synchronize that way. Consider the courts in fantasy capitols. Time can be managed by the flurry of movement of paiges letting people know how the audience with the queen is going. In fact, in many cases, this is a more effective approach to timekeeping. How many times have you had a 30 minute meeting that becomes a 4 hour discussion? It happens often enough that flexibility in time is useful. This works well until you need people who aren't interacting to all convene at the same time. Then you need something more synchronous. Often the town bells may be used to provide such a synchronous moment for all people. In Islamic countries, they could syncrhonize to the Muezzin calls, 5 times a day. In the end, clocks are needed when you must synchronize many arbitrary events at many times of day, over long distances. That calls for an absolute sense of time, and if you need that, you need a clock. However, if your fantasy culture doesn't need quite that much synchronicity, time may be defined by particularly important events to the people of the area. Many school children learn to tell time of day by how many recess bells they hear, long before they learn to read a clock. Such a culturally specific form of synchronization could fit the bill. In the other extreme, farm life is not all that dependent on exact timing. You may find that sunrise and sunset are sufficient to synchronize farmer life. It all just depends on the individual culture.
Even in industrial age, like the town I grew up in, in the past the only way to tell time was by the factory siren, telling people the shift was over - like a medieval belltower ringing vespers etc. Sundials are not too useful since you need sun, so that they do not work in cloudy weather, and of course only in daytime; without some sort of outside announcement most people would have little idea (clocks used to be really expensive even when they existed) what time it is, other than morning, mid-morning, about noonish, time to eat, etc. So unless your world has invented some sort of common clock, telling time accurately would not work, or your world maybe has a similar system as a belltower telling time to people. For inspiration, the Canonical Hours are: matins, morning prayer - the first canonical hour; at daybreak prime - the second canonical hour; about 6 a.m. terce, tierce - the third canonical hour; about 9 a.m. sext - the fourth of the seven canonical hours; about noon nones - the fifth of the seven canonical hours; about 3 p.m. evensong, vespers - the sixth of the seven canonical hours of the divine office; complin, compline - last of the seven canonical hours just before retiring. Or, you could follow the five times Muslims pray per day.
6,496,628
Good afternoon, We are currently using STL multimap and STL set to cache memory mapped file regions. We would like our cache to have only unique entries. We wondering if there is a way for STL set and STL map to be faster than STL multiset and STL multimap for preventing duplicate entries. We are using the following code excerpt to prevent STL multimap and STL set duplicate entries. Is it possible to make this faster? Thank you. ``` int distance(char* x, char* y,int error){ if (x >= y && (x - y) <= error){ return 0; } return (x - y); }; class MinDist { public: MinDist(){} MinDist(char* & p, const int & error){} bool operator() (char * p1, char * p2 ) { return distance( p1, myPoint, myError) < distance( p2, myPoint, myError); } public: static char* myPoint; static int myError; }; std::multiset<Range> ranges_type; std::multimap<char *,Range, MinDist> mmultimap; MinDist::myPoint = TmpPrevMapPtr; MinDist::myError = MEM_BLOCK_SIZE; std::pair<I,I> b = mmultimap.equal_range(TmpPrevMapPtr); for (I i=b.first; i != b.second; ++i){ ranges_type.erase(i->second); numerased++; } typedef std::multimap<char*,Range,MinDist>::iterator J; std::pair<J,J> pr = mmultimap.equal_range(TmpPrevMapPtr); erasecount = 0; J iter = pr.first; J enditer = pr.second; for( ; iter != enditer ; ){ if ((*iter).first == TmpPrevMapPtr){ mmultimap.erase(iter++); erasecount++; } else{ ++iter; } } MinDist::myPoint = 0; ranges_type.insert(RangeMultiSet::value_type(n, n + mappedlength, &adjustedptr[n],MapPtr,mappedlength)); mmultimap.insert(RangeMultiMap::value_type(MapPtr, Range(n,n + mappedlength, &adjustedptr[n], MapPtr,mappedlength))); ```
2011/06/27
[ "https://Stackoverflow.com/questions/6496628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/557534/" ]
There's a lot of stuff to read here, and optimization of the complex container types is a tricky problem. I've spent a fair bit of time working on similar problems, so I'll try to point out some things that have helped me. Firstly, the usual way to make your code faster is *don't use binary trees when vectors will do*. The Microsoft STL implementation is going to spend about 14 bytes (3 pointers + short int for red/black flag last I checked) of overhead for each node in your map/set, plus malloc overhead of at least 4 more bytes before it gets around to storing your node data. While I don't know the specifics of your domain too well, memory mapped I/O strikes me as an area where there likely exists a complex but faster vector-based solution. It would require that the number of blocks you map simultaneously is small--if your lookup-table is up to or less than 6,000 bytes, a sorted-array implementation with memmove for insert/erase, and binary\_search for lookup will likely be faster in Release mode (and in Debug mode, it'll be faster up to several megabytes, sadly). If the elements are 4-byte pointers, then 6,000 bytes allows for up to 1,500 mapped blocks. There are times that you simply need to use trees, however. One case is complex nodes (so that construction/destruction is essential) or fairly high element count (so that the O(N) array insertion becomes slower than the malloc cost of O(log n) tree insertion). What can you do here? Note that map/multimap and set/multiset or pretty nearly the same speed; the multi\* versions do tend to be a little slower, but only because the code to handle them is a few lines longer. Anyway, one thing that can help a lot is figuring out how to cut the malloc cost, since every node is going to call malloc/free at some point. Cutting that is *difficult*--the Release mode allocator is roughly the equivalent of about 50-200 arithmetic operations, so while it's beatable, it takes some effort. You do have some hope, though -- map/set allocations are all identically sized, so a memory pool can work very well. [Google](http://www.google.com/search?q=custom%20stl%20allocator) is probably a good way to get started; there are many good articles on this topic. Finally, there's an open source sampling profiler that I have found very helpful -- it's called [Very Sleepy](http://www.codersnotes.com/sleepy), and usually Just Works on Visual Studio projects. If you want to definitely answer whether map/multimap or set/multiset is quicker in your case, that's the main thing I'd point you to. Good luck!
Here is a generic situation: ``` #include <cstddef> // for size_t #include <set> // for std::set #include <algorithm> // for std::swap #include <ostream> // for std::ostream struct Range { int start, end; // interpret as [start, end), so Range(n,n) is empty! Range(int s, int e) : start(s), end(e) { if (start > end) std::swap(start, end); } inline bool operator<(const Range & r) const { return (start < r.start) || (!(r.start > start) && end < r.end); } inline size_t size() const { return end - start; } }; std::ostream & operator<<(std::ostream & o, const Range & r) { return o << "[" << r.start << ", " << r.end << ")"; } typedef std::set<Range> cache_t; cache_t::const_iterator findRange(int pos, const cache_t & cache) { cache_t::const_iterator it = cache.lower_bound(Range(pos, pos)), end = cache.end(); for ( ; it != end && it->start <= pos ; ++it) // 1 { if (it->end > pos) return it; } return end; } inline bool inRange(int pos, const cache_t & cache) { return findRange(pos, cache) != cache.end(); } ``` Now you can use `findRange(pos, cache)` to discover whether a given position is already covered by a range in the cache. Note that the loop at `// 1` is rather efficient as it only starts at the first element where `pos` could possibly be and stops once `pos` can no longer be in range. For non-overlapping ranges this will cover at most one range!
1,047,053
I have tried solving this problem but my answer is not correct **Problem** In a cinema festival , 30 movies are scheduled every night in the following categories: * 10 in horror movies (H), * 15 in comedy movies (C), * 5 in documentaries (D) A guest is allowed to watch 1 movie each night during the 5 night that he will be spending, he wish to watch a different movie every night, also he wish to watch a movie from each category during his stay in the festival. In how many different way can he schedule his program. **My Answer** First we make sure that he watch a movie in every category then we select 2 movies from the remaining 27 movies (all categories together) and since he can see those movies in different order during the 5 days we multiply everything by 5! for ex: ({H1} , {C4}, {D3} , {H4,C13}) then we can permute this (5!) to get all arrangement possible I would write that like this for all existing possibilities: $$\binom{10}{1} \binom{15}{1}\binom{5}{1}\binom{27}{2} \cdot 5!$$ but my result is incorrect. Can you please help, many thanks.
2014/12/01
[ "https://math.stackexchange.com/questions/1047053", "https://math.stackexchange.com", "https://math.stackexchange.com/users/196814/" ]
Your result would be correct if, in addition to selecting which movies to watch, your guest were also identifying a *favorite* movie from each genre -- i.e., he would first pick a favorite from each of the three categories, and then pick two more movies from what's left over. But since the problem doesn't ask for him to identify favorites, counting things this way leads to double (and even triple) counting. I think you have to break things down into a bunch of cases: The guest either picks three horror movies and one of each of the others, or three comedies and one of each of the others, or three documentaries and one of each of the others, or one horror movie and two of each of the others, or one comedy and ... I hope the rest is clear. Can you take it from here? (The $5$-factorial part of your solution was indeed correct, so don't forget to multiply by it at the end.)
Your method, of selecting one from each category then selecting any two others and permutating, will suffer from over counting.   Since it counts both all the ways to select, say "The Ring" as one of the ones, and all the ways to select it as one of the other two. --- There are $5!$ ways to watch five different movies over the stay.   Now to choose *which* five, you must select at least one from each category.   That's either three from one and one from each other, or two from two and one from the other.   Sum all the ways to do this: $$\newcommand{\Ch}[2]{{^{#1}\mathsf C\_{#2}}} 5!\Biggl(\Ch{10}{3}\Ch{15}{1}\Ch{5}{1}+\Ch{10}{1}\Ch{15}{3}\Ch{5}{1}+\ldots\text{et cetera} \Biggr) $$
25,223,768
I want to create a user menu, that looks like this: ![enter image description here](https://i.stack.imgur.com/YuZZ5.png) When I create such a menu with bootstrap, its full width and not aligned under the button. So it looks like this: ![enter image description here](https://i.stack.imgur.com/Xjtpv.png) So how could I create such a menu with bootstrap?
2014/08/09
[ "https://Stackoverflow.com/questions/25223768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2977288/" ]
If you stepped through your program with a debugger you'd find out that the following is your problem: ``` strcpy(array[k],array[k+1]); ``` When `k == 3` you're attempting to access an element outside the bounds of `array` for the second argument of `strcpy`: ``` array[k+1] ```
Your approach is not good. When you find a matched string you copy all tail of the array in the new position. Here is a more simple and clear approach ``` #include <stdio.h> #include <string.h> #define N 4 int main(void) { char s[N][N] = { "cat", "mat", "sat", "mat" }; int i, j; j = 0; /* current osition where a unique string will be placed */ for ( i = 0; i < N; i++ ) { int k = 0; while ( k < j && strcmp( s[k], s[i] ) != 0 ) k++; if ( k == j ) { if ( j != i ) strcpy( s[j], s[i] ); j++; } } for ( i = 0; i < j; i++ ) printf( "%s ", s[i] ); puts( "" ); return 0; } ``` The output is ``` cat mat sat ``` Simply copy paste and investigate.:)
19,421,238
I want to check programatically if my device is locked by a third party Lockscreen...With the normal Lockscreen by android you can do that by ``` KeyguardManager kgMgr = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); boolean locked = kgMgr.inKeyguardRestrictedInputMode(); ``` But what if a third party Lockscreen is installed?! Is there any way to check if the device is locked?
2013/10/17
[ "https://Stackoverflow.com/questions/19421238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1370245/" ]
Since candidates is an array, `$#candidates` is the largest index (number of elements - 1) For example: ``` my @x = (4,5,6); print $#x; ``` will print `2` since that is the largest index. Note that if the array is empty, `$#candidates` will be -1 EDIT: from `perldoc perlvar`: ```none $# is also used as sigil, which, when prepended on the name of an array, gives the index of the last element in that array. my @array = ("a", "b", "c"); my $last_index = $#array; # $last_index is 2 for my $i (0 .. $#array) { print "The value of index $i is $array[$i]\n"; } ```
It is a value of last index on array (in your case it is last index on candidates).
3,318,427
I recently posted a article in my blog site which uses Wordpress for CMS and after posting the article i noticed a set of dots appearing after the post . I'm not able to remove it .. Can anyone help me ? and explain me what's wrong with it ?!
2010/07/23
[ "https://Stackoverflow.com/questions/3318427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391186/" ]
It tells the compiler the boundary to align objects in a structure to. For example, if I have something like: ``` struct foo { char a; int b; }; ``` With a typical 32-bit machine, you'd normally "want" to have 3 bytes of padding between `a` and `b` so that `b` will land at a 4-byte boundary to maximize its access speed (and that's what will typically happen by default). If, however, you have to match an externally defined structure you want to ensure the compiler lays out your structure exactly according to that external definition. In this case, you can give the compiler a `#pragma pack(1)` to tell it *not* to insert any padding between members -- if the definition of the structure includes padding between members, you insert it explicitly (e.g., typically with members named `unusedN` or `ignoreN`, or something on that order).
I have seen people use it to make sure that a structure takes a whole cache line to prevent false sharing in a multithreaded context. If you are going to have a large number of objects that are going to be loosely packed by default it could save memory and improve cache performance to pack them tighter, though unaligned memory access will usually slow things down so there might be a downside.
34,444
> > **Possible Duplicate:** > > [How does the automatic subjective filter work?](https://meta.stackexchange.com/questions/4371/how-does-the-automatic-subjective-filter-work) > > > How does SOFU determine that "The question you're asking appears subjective and is likely to be closed."?
2010/01/04
[ "https://meta.stackexchange.com/questions/34444", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/5849/" ]
I'm of the understanding that it looks for a few specific keywords (like "best") in the title. Try writing a nonsense title with "best" in it and hit Tab, then go back and change "best" to "biggest". **Update**: Here's the definitive answer, from Jeff: [How does the automatic subjective filter work?](https://meta.stackexchange.com/questions/4371/how-does-the-automatic-subjective-filter-work)
Not just that. It also looks for keywords like "you" For example, ``` How would you do something in somelanguage in the best possible manner ``` returns the alert ``` How would you do something in somelanguage ``` returns the alert; while ``` How to do something in somelanguage ``` does not return the alert
88,266
I saw the following in a journal homepage at <http://www.pphmj.com/journals/jpanta_author_information.htm> > > **Print Charges:** > To defray the publication cost, authors are requested to arrange print charges of their accepted papers at the rate of US$ 40 per page from their institutions/research grants, if any. > > > I don't understand the meaning of **if any** in the above sentences. I have a paper with no grant. Should I pay any thing?
2017/04/19
[ "https://academia.stackexchange.com/questions/88266", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72391/" ]
**If** you are at **any** institution or **if** you have **any** grants, these should be used to pay the print charges. If you don't have these, it implies you pay the charges out of your own pocket-- if you want a printed version of your paper, that is.
Actually there is another interpretation that sometimes applies, though I can't say that it does here. For some journals, in some situations, if you don't have institutional or grant funds to pay page charges they are just forgiven and won't accrue to the author(s). I can't say how prevalent this is, but it has occurred (one of my mathematics papers, in fact). But you should ask the editor what happens if you have no source of funding other than yourself.
36,621
I'm taking the leap: my PHP scripts will ALL fail gracefully! At least, that's what I'm hoping for...` I don't want to wrap (practically) every single line in `try...catch` statements, so I think my best bet is to make a custom error handler for the beginning of my files. I'm testing it out on a practice page: ``` function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die(); } set_error_handler("customError"); echo($imAFakeVariable); ``` This works fine, returning: > > Sorry, an error has occurred on line 17. The function that caused the > error says Undefined variable: imAFakeVariable. > > > However, this setup doesn't work for undefined functions. ``` function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die(); } set_error_handler("customError"); imAFakeFunction(); ``` This returns: > > Fatal error: Call to undefined function: imafakefunction() in > /Library/WebServer/Documents/experimental/errorhandle.php on line 17 > > > Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause?
2008/08/31
[ "https://Stackoverflow.com/questions/36621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
`set_error_handler` is designed to handle errors with codes of: `E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE`. This is because `set_error_handler` is meant to be a method of reporting errors thrown by the *user* error function `trigger_error`. However, I did find this comment in the manual that may help you: > > "The following error types cannot be handled with a user defined function: `E_ERROR`, `E_PARSE`, `E_CORE_ERROR`, `E_CORE_WARNING`, `E_COMPILE_ERROR`, `E_COMPILE_WARNING`, and most of `E_STRICT` raised in the file where `set_error_handler()` is called." > > > This is not exactly true. `set_error_handler()` can't handle them, but `ob_start()` can handle at least `E_ERROR`. > > > > ``` > <?php > > function error_handler($output) > { > $error = error_get_last(); > $output = ""; > foreach ($error as $info => $string) > $output .= "{$info}: {$string}\n"; > return $output; > } > > ob_start('error_handler'); > > will_this_undefined_function_raise_an_error(); > > ?> > > ``` > > Really though these errors should be silently reported in a file, for example. Hopefully you won't have many `E_PARSE` errors in your project! :-) As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong.
I've been playing around with error handling for some time and it seems like it works for the most part. ``` function fatalHandler() { global $fatalHandlerError, $fatalHandlerTitle; $fatalHandlerError = error_get_last(); if( $fatalHandlerError !== null ) { print($fatalHandlerTitle="{$fatalHandlerTitle} | ".join(" | ", $fatalHandlerError). (preg_match("/memory/i", $fatalHandlerError["message"]) ? " | Mem: limit ".ini_get('memory_limit')." / peak ".round(memory_get_peak_usage(true)/(1024*1024))."M" : "")."\n". "GET: ".var_export($_GET,1)."\n". "POST: ".var_export($_POST,1)."\n". "SESSION: ".var_export($_SESSION,1)."\n". "HEADERS: ".var_export(getallheaders(),1)); } return $fatalHandlerTitle; } function fatalHandlerInit($title="phpError") { global $fatalHandlerError, $fatalHandlerTitle; $fatalHandlerTitle = $title; $fatalHandlerError = error_get_last(); set_error_handler( "fatalHandler" ); } ``` Now I have an issue where if the memory is exhausted, it doesn't report it every time. It seems like it depends on how much memory is being used. I did a script to load a large file (takes ~6.6M of memory) in an infinite loop. Setup1: ``` ini_set('memory_limit', '296M'); fatalHandlerInit("testing"); $file[] = file("large file"); // copy paste a bunch of times ``` In this case I get the error to be reports and it dies on 45 file load. Setup2 - same but change: ini\_set('memory\_limit', '299M'); This time I don't get an error and it doesn't even call my custom error function. The script dies on the same line. Does anyone have a clue why and how to go around that?
30,048,722
I have tried to hide toolbar from the text change listener ``` public void onTextChanged(CharSequence s, int start, int before, int count) { toolbar.animate() .translationY(-toolbar.getBottom()) .setInterpolator(new AccelerateInterpolator()) .start(); } ``` this solution works perfectly on higher level api(successfully work on kitkat).But I got following error on running device with api level 10. > > java.lang.NoSuchMethodError: android.support.v7.widget.Toolbar.animate > > > the layout xml portion is ``` <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:background="#ff6d7fe2" app:contentInsetEnd="0dp"> </android.support.v7.widget.Toolbar> ``` I have not set the toolbar as support action bar.why I got this error even if using android.support.v7.widget.Toolbar?
2015/05/05
[ "https://Stackoverflow.com/questions/30048722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944894/" ]
All what Julian said, but presumably the real question is about the difference between plain iCalendar-over-HTTP (commonly called webcal, 'iCalendar subscription' or 'subscribed calendar') and CalDAV. Or in other words: what does CalDAV add. Simply put: in iCoHTTP you usually store a whole calendar under one URL, like '<http://yahoo.com/sports/nba/schedule-2015.ics>' (or webcal:). This URL represents a full calendar and is almost always readonly (you can't do a PUT to this URL). Why is that? Because to add/change/delete a single event in such a calendar, you would need to re-transfer the full calendar. In CalDAV a calendar is a WebDAV collection, there is one URL which represents the calendar, e.g.: '<http://icloud.com/calendars/joe/home/>' and then you have one child URL for each event. Like '<http://icloud.com/calendars/joe/home/buy-beer.ics>', '<http://icloud.com/calendars/joe/home/family-meeting.ics>' and so on. You can then just DELETE, PUT etc individual items of such a collection. In summary: If you simply want to publish a calendar which rarely changes and is managed by other means (like a CMS), you can use iCal-over-HTTP. If you want to provide a calendar which the user (or maybe a group of people) can change from within their calendar client, you want to use CalDAV. CalDAV also has a set of extensions, e.g. many CalDAV server can automatically perform scheduling operations for you (setting up meetings and such). There is an extension to share calendars with other people, and so on. P.S.: This is a bit confusing, but yes, Apple also has a way of using WebDAV to manage iCalendar subscriptions. But this is yet another thing which works alongside CalDAV.
CalDAV is a protocol, extending WebDAV, thus HTTP. Webcal is a URI scheme that AFAIK was invented by Apple and has exactly the same semantics as "http", except that Safari (and maybe some other browsers) know that the URI refers to a calendar, and thus invoke the "right" application without having to fetch the resource. (Of course the right thing would have been just to inspect the media type (content-type header field) and then to invoke the matching application. So this is an anti-pattern (done again by Apple with "itms" URIs).
35,489,409
I try to extract from "EditText" in "string" in the same activity but fail. cod: ``` String mStreamUrl = ((EditText) findViewById(R.id.bTorrentUrl)).getText().toString(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_t); String action = getIntent().getAction(); Uri data = getIntent().getData(); if (action != null && action.equals(Intent.ACTION_VIEW) && data != null) { try { mStreamUrl = URLDecoder.decode(data.toString(), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } ``` log: ``` hutting down VM 02-18 18:55:49.326 5809-5809/ro.vrt.videoplayerstreaming E/AndroidRuntime: FATAL EXCEPTION: main Process: ro.vrt.videoplayerstreaming, PID: 5809 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ro.vrt.videoplayerstreaming/ro.vrt.videoplayerstreaming.TorrentPlayer}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at android.app.Activity.findViewById(Activity.java:2096) at ro.vrt.videoplayerstreaming.TorrentPlayer.<init>(TorrentPlayer.java:34) at java.lang.Class.newInstance(Native Method) at android.app.Instrumentation.newActivity(Instrumentation.java:1067) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  02-18 18:55:53.763 5809-5809/ro.vrt.videoplayerstreaming I/Process: Sending signal. PID: 5809 SIG: 9 ``` If you deleteString > > mStreamUrl = ((EditText)findViewById(R.id.bTorrentUrl)).getText().toString(); > > > and put > > private String mStreamUrl = "xxxx"; > > > everything work fine. **Thank you**
2016/02/18
[ "https://Stackoverflow.com/questions/35489409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4718734/" ]
Change this: > > > ``` > String mStreamUrl = ((EditText) findViewById(R.id.bTorrentUrl)).getText().toString(); > > ``` > > to this: ``` String mStreamUrl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_t); mStreamUrl = ((EditText) findViewById(R.id.bTorrentUrl)).getText().toString(); // ... } ``` You can't find the view before the layout is inflated. Even then, however, the string will be whatever value you defined in the layout. You probably want to wait until the user clicks a button before you get the text from the widget.
When you use findViewById you always risk a NullPointerException because of the way Android loads it's views. What I would suggest if to see if your view is non-null then cast it to a string (getText().toString()) in a separate statement. **Update : remember to call this after setContentView()** Also remember that findViewById will only return widgets contained by the view you set on setContentView. If the button is placed on other view, your code will never work.
36,103
I know that *apparently* there is no information about this in the Dragon Ball Super series. But since new information is constantly popping up in manga, magazines, etc. Before the series sometimes, that's why I'm asking. More data on this, according to [Dragon Ball Wikia on Super Saiyan Rosé](http://dragonball.wikia.com/wiki/Super_Saiyan_Ros%C3%A9) > > This form is a counterpart to Super Saiyan Blue, and possesses a > different hair color due to the user already possessing the status as > a god prior to surpassing Super Saiyan God > > > So if Goku would turn a god of destruction as when he was offered once (or Vegeta) or Trunks would become a Kaioshin as when he was a Kaioshin apprentice, wouldnt they turn into Super Saiyan Rosé when trying to transform into super saiyan god super saiyan?
2016/08/29
[ "https://anime.stackexchange.com/questions/36103", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/3028/" ]
I dont think they would be able to achieve it because I think it is partly linked to him being the same kind of race as Gowasu (as in mind)
Don't listen to anyone else except Zamasu it has to do with the fact that Super Saiyan Rose is Goku Black's version of the regular Super Saiyan that surpassed the power of Super Saiyan God and evolved naturally into SSGSS/A differently colored Super Saiyan Blue due to his status as an actual god with natural god ki. SSGSS is blue for Goku and Vegeta because they aren't actual gods just mortals with godly ki.
63,417,385
I am trying to make an if/elseif statement work in php and everything seems to work just fine, besides if the "locid" is empty, or not present, i want to display a different query. Could someone help me figure out whats wrong with the code? Basically, the if(empty($locid)) statement does not work. The page appears as blank. This is the code: ``` if (isset($_GET['locid'])) { $locid = $_GET['locid']; if (empty($locid)) { $selectloc = "SELECT * FROM locations;"; } elseif ($locid == 'all') { $selectloc = "SELECT * FROM locations;"; } elseif ($locid == 'veterinary') { $selectloc = "SELECT * FROM locations WHERE location_cate='Veterinary';"; } elseif ($locid == 'store') { $selectloc = "SELECT * FROM locations WHERE location_cate='Store';"; } elseif ($locid == 'shelter') { $selectloc = "SELECT * FROM locations WHERE location_cate='Shelter';"; } elseif ($locid == 'other') { $selectloc = "SELECT * FROM locations WHERE location_cate='Other';"; } else { $selectloc = "SELECT * FROM locations;"; } } ```
2020/08/14
[ "https://Stackoverflow.com/questions/63417385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13806446/" ]
You have a logical flaw in your *if* *else* construction. First you check if the `GET` variabe is set and enter an *if* statement if that's the case. However, checking for an empty variable inside that makes no sense as you know when you have entered the statement, the variable won't be empty. Therefore, you should move your empty logic into an else statement supplementing your *isset()* as the logic would be that either the variable is set, or it is not (i.e. empty). ``` <?php if (isset($_GET['locid'])) { $locid = $_GET['locid']; if ($locid == 'all') { $selectloc = "SELECT * FROM locations;"; } elseif ($locid == 'veterinary') { $selectloc = "SELECT * FROM locations WHERE location_cate='Veterinary';"; } elseif ($locid == 'store') { $selectloc = "SELECT * FROM locations WHERE location_cate='Store';"; } elseif ($locid == 'shelter') { $selectloc = "SELECT * FROM locations WHERE location_cate='Shelter';"; } elseif ($locid == 'other') { $selectloc = "SELECT * FROM locations WHERE location_cate='Other';"; } else { $selectloc = "SELECT * FROM locations;"; } } else { $selectloc = "SELECT * FROM locations;"; } ?> ```
If the ids differ only by the case, you can greatly simplify the code: ``` $locids = [ 'veterinary', 'store', 'shelter', 'other' ]; $whereClause = ''; $locid = $_GET['locid'] ?? null; if (in_array($locid, $locids)) { $locationCate = ucfirst($locid); $whereClause = "WHERE location_cate='$locationCate'"; } $selectloc = "SELECT * FROM locations $whereClause;"; ```
25,941,744
Given the following classes: ``` public abstract class Super { protected static Object staticVar; protected static void staticMethod() { System.out.println( staticVar ); } } public class Sub extends Super { static { staticVar = new Object(); } // Declaring a method with the same signature here, // thus hiding Super.staticMethod(), avoids staticVar being null /* public static void staticMethod() { Super.staticMethod(); } */ } public class UserClass { public static void main( String[] args ) { new UserClass().method(); } void method() { Sub.staticMethod(); // prints "null" } } ``` I'm not targeting at answers like "Because it's specified like this in the JLS.". I know it is, since [JLS, 12.4.1 When Initialization Occurs](http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1) reads just: > > *A class or interface type T will be initialized immediately before the first occurrence of any one of the following:* > > > * *...* > * *T is a class and a static method declared by T is invoked.* > * *...* > > > I'm interested in whether there is a good reason why there is not a sentence like: > > * T is a subclass of S and a static method declared by S is invoked on T. > > >
2014/09/19
[ "https://Stackoverflow.com/questions/25941744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1744774/" ]
The reason is quite simple: for JVM not to do extra work prematurely (Java is lazy in its nature). Whether you write `Super.staticMethod()` or `Sub.staticMethod()`, the same implementation is called. And this parent's implementation typically does not depend on subclasses. Static methods of `Super` are not supposed to access members of `Sub`, so what's the point in initializing `Sub` then? Your example seems to be artificial and not well-designed. Making subclass rewrite static fields of superclass does not sound like a good idea. In this case an outcome of Super's methods will depend on which class is touched first. This also makes hard to have multiple children of Super with their own behavior. To cut it short, static members are not for polymorphism - that's what OOP principles say.
When static block is executed [Static Initializers](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.7) > > A static initializer declared in a class is executed when the class is initialized > > > when you call `Sub.staticMethod();` that means class in not initialized.Your are just refernce When a class is initialized > > When a Class is initialized in Java After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when : > > > 1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java. > > > 2) an static method of Class is invoked. > > > 3) an static field of Class is assigned. > > > 4) an static field of class is used which is not a constant variable. > > > 5) if Class is a top level class and an assert statement lexically nested within class is executed. > > > [When a class is loaded and initialized in JVM - Java](http://javarevisited.blogspot.in/2012/07/when-class-loading-initialization-java-example.html) that's why your getting null(default value of instance variable). ``` public class Sub extends Super { static { staticVar = new Object(); } public static void staticMethod() { Super.staticMethod(); } } ``` in this case class is initialize and you get hashcode of `new object()`.If you do not override `staticMethod()` means your referring super class method and `Sub` class is not initialized.
20,556,102
So I am trying to get angular working on IE8. I have followed all the steps on <http://docs.angularjs.org/guide/ie> and it seems to be working -- I see the content of `ng-view` rendered on IE8 when I switch between views. The problem is that I don't actually see any content in the inspector: ![enter image description here](https://i.stack.imgur.com/zA99Z.png) .. it's just an empty ng-view tag. I *can* see all of the content on the page, but no styling is applied to anything inside `ng-view`. I am not sure whether this is an angular or HTML5 issue. I have added the [html5shiv](https://code.google.com/p/html5shiv/) and HTML5 elements outside of `ng-view` are styled nicely. **EDIT** I have determined that the problem is HTML5 elements. `<section>` and `<article>` are not styled inside `ng-view`, while simple divs receive all the specified styling. Outside of `ng-view`, `<nav>` and `<header>` are styled just fine.
2013/12/12
[ "https://Stackoverflow.com/questions/20556102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2026098/" ]
Let's take a tour of [String#repalceAll(String regex, String replacement)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29) You will see that: > > An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression > > > `Pattern.compile(regex).matcher(str).replaceAll(repl)` > > > So lets take a look at [Matcher.html#replaceAll(java.lang.String)](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#replaceAll%28java.lang.String%29) documentation > > Note that backslashes (`\`) and dollar signs (`$`) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. **Dollar signs may be treated as references to captured subsequences** as described above, and **backslashes are used to escape literal characters in the replacement string**. > > > You can see that in `replacement` we have special character `$` which can be used as reference to captured group like ``` System.out.println("aHellob,aWorldb".replaceAll("a(\\w+?)b", "$1")); // result Hello,World ``` But sometimes we don't want `$` to be such special because we want to use it as simple dollar character, so we need a way to escape it. And here comes `\`, because since it is used to escape metacharacters in regex, Strings and probably in other places it is good convention to use it here to escape `$`. So now `\` is also metacharacter in replacing part, so if you want to make it simple `\` literal in replacement you need to escape it somehow. And guess what? You escape it the same way as you escape it in regex or String. You just need to place another `\` before one you escaping. So if you want to create `\` in replacement part you need to add another `\` before it. But remember that to write `\` literal in String you need to write it as `"\\"` so to create two `\\` in replacement you need to write it as `"\\\\"`. --- So try ``` s = s.replaceAll("'", "\\\\'"); ``` Or even better ============== to reduce explicit escaping in replacement part (and also in regex part - forgot to mentioned that earlier) just use `replace` instead `replaceAll` which adds regex escaping for us ``` s = s.replace("'", "\\'"); ```
This doesn't say how to "fix" the problem - that's already been done in other answers; it exists to draw out the details and applicable documentation references. --- When using [`String.replaceAll`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29) or any of the applicable Matcher replacers, pay attention to the replacement string and how it is handled: > > Note that *backslashes (`\`) and dollar signs (`$`) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string.* Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string. > > > As pointed out by isnot2bad in a comment, [`Matcher.quoteReplacement`](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#quoteReplacement%28java.lang.String%29) may be useful here: > > Returns a literal replacement String for the specified String. .. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes (`\`) and dollar signs (`$`) will be given no special meaning. > > >
11,279,835
I have a ``` < div id="thisdiv" class="class1 class2 class3 class4 class5"> text < /div> ``` I need to be able to delete all classes after class3 with jQuery. something like ``` $('#thisdiv').removeClass(all after class3); ``` OR ``` $('#thisdiv').attr('class', all from class1 to class3); ``` Please how can I do that?
2012/07/01
[ "https://Stackoverflow.com/questions/11279835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803358/" ]
``` function removeAllClass(selector, after, before) { $(selector).attr('class', function(i, oldClass) { var arr = oldClass.split(' '); if (!before) { arr.splice(arr.indexOf(after)+1).join(' '); return arr.join(' '); } else { return arr.slice(arr.indexOf(after), arr.indexOf(before) + 1).join(' '); } }); } ``` **Use:** * all after `class3` `removeAllClass('#thisdiv', 'class3');` **[DEMO](http://jsfiddle.net/FNUK2/6/)** * from `class1` to `class3` `removeAllClass('#thisdiv', 'class1', 'class3');` **[DEMO](http://jsfiddle.net/FNUK2/5/)** ### According to comment > > UPDATE: I wonder if I can make it work with > **$('#thisdiv').removeAllClass('class3');** > > > ``` $.fn.removeAllClass = function(after, before) { $(this).attr('class', function(i, oldClass) { var arr = oldClass.split(' '); if (!before) { arr.splice(arr.indexOf(after) + 1).join(' '); return arr.join(' '); } else { return arr.slice(arr.indexOf(after), arr.indexOf(before) + 1).join(' '); } }); } ``` **Use:** * all after `class3` `$('#thisdiv').removeAllClass('class3');` **[DEMO](http://jsfiddle.net/FNUK2/7/)** * from `class1` to `class3` `$('#thisdiv').removeAllClass('class1', 'class3');` **[DEMO](http://jsfiddle.net/FNUK2/9/)**
To do something like this correctly might be a little bit expensive. You need to replace the `class` attr by iterating over existing classes and removing those that don't fit your criteria. The order of classes from the `class` attribute are not guaranteed to be in any order, in general: ``` function removeAbove(prefix, max) { var regex = new RegExp('^' + prefix + '(\\d+)$'); return function (v) { var match = regex.exec(v); if (!match || parseInt(match[1], 10) <= max) { return v; } } } function processClasses(keys, fn) { var i = keys.length, result = [], temp; while (i--) { temp = fn(keys[i]); if (temp) { result.push(temp); } } return result.join(' '); } $('#thisdiv').attr('class', function (idx, cls) { return processClasses(cls.split(' '), removeAbove('class', 3)); }); ```
4,971,981
I have a subview that acts as a container view in a table header. In that, I have a UIButton. The button is not receiving any touch events. (Yes everything is wired up properly in IB...) So my question is, is it a common problem to have buttons not receiving any events in the header? Do I need to forward any events? I can't really post any code, since it would appear to be more of an IB problem. Anyone experience this before? --- UPDATE: If I put the button in the footer, with no container view, it will work. So perhaps it's because it is in a view inside the header??
2011/02/11
[ "https://Stackoverflow.com/questions/4971981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410856/" ]
Wow, I feel like a moron. I didn't have user interaction enabled. Sorry for wasting all your time guys...
I've included UIButtons and even UITableViews in my table header before, so I don't think it should be an issue. Something is just not setup correctly. I didn't have to do anything special to get touch events to fire.
4,253,328
I've found the `R.string` pretty awesome for keeping hardcoded strings out of my code, and I'd like to keep using it in a utility class that works with models in my application to generate output. For instance, in this case I am generating an email from a model outside of the activity. **Is it possible to use `getString` outside a `Context` or `Activity`**? I suppose I could pass in the current activity, but it seems unnecessary. Please correct me if I'm wrong! Edit: Can we access the resources *without* using `Context`?
2010/11/23
[ "https://Stackoverflow.com/questions/4253328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/210920/" ]
In `MyApplication`, which extends `Application`: ``` public static Resources resources; ``` In `MyApplication`'s `onCreate`: ``` resources = getResources(); ``` Now you can use this field from anywhere in your application.
If you want to use getString Outside of a Context or Activity you should have context in constructor or method parameter so that you can access getstring() method. Specially in Fragment You shoud ensure that getActivity() or getContext() are not providing null value. To avoid null from getActivity() or getContext() in a Fragment try this : Declare a variable : ``` Context mContext; ``` now override onAttach and onDetach method of Fragment : ``` @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Override public void onDetach() { super.onDetach(); mContext = null; } ``` Now Use **mContext** whereever you are using getString() method. ex: ``` Toast.makeText(mContext, mContext.getString(R.string.sample_toast_from_string_file), Toast.LENGTH_SHORT).show(); ```
67,170,310
I'm running some code using Junit4 and an external jar of JunitParams. As far as I could tell, my code was all set right, and imports are all correct...but my method under test keeps throwing runtime exceptions since it seems to ignore the @Parameters annotation hanging out in it. When it reaches my method under test, it keeps saying "java.lang.Exception: Method ----- should have no parameters" I'm not sure what the issue is, even though other people have run into issues with mix/matched import statements, etc. I checked mine and that doesn't seem like the case here. Test Runner class: ```java package Chapter8.Wrappers.Tests; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args){ Result result = JUnitCore.runClasses(StringProcessorTest.class); for(Failure failures: result.getFailures()) { System.out.println(failures.toString()); } System.out.println(result.wasSuccessful()); } } ``` and my test class, StringProcessorTest : ```java package Chapter8.Wrappers.Tests; import Chapter8.Wrappers.Challenges.BackwardsString.StringProcessor; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import java.util.Collection; @RunWith(JUnitParamsRunner.class) public class StringProcessorTest { private StringProcessor processor; private final String expectedResult; private final String inputString; public StringProcessorTest(String inputString, String expectedResult){ super(); this.inputString = inputString; this.expectedResult = expectedResult; } @Before public void initialize(){ processor = new StringProcessor(); } @Parameters public static Collection stringValues(){ return Arrays.asList(new Object[][] { {"HELLO","OLLEH"}, {"TESTING", "GNITSET"} }); } @Test public void objectConstructor_InitializeStringBuilderInside_EqualsPassedString(String inputString, String expectedResult){ Object input; input = inputString; processor = new StringProcessor(input); Assert.assertEquals(expectedResult, processor.printReverseString()); } } ``` Console output: ``` Chapter8.Wrappers.Tests.StringProcessorTest: java.lang.Exception: Method objectConstructor_InitializeStringBuilderInside_EqualsPassedString should have no parameters false Process finished with exit code 0 ```
2021/04/19
[ "https://Stackoverflow.com/questions/67170310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15081463/" ]
I found something that ended up working out- I changed the inside of the @RunWith annotation to ``` Parameterized.class ``` It turned out I was trying to pass parameters into the method under the @Test annotation, and not just the constructor of my StringProcessorTest class; I removed them from the method under test. It was already warning me about that but I didn't understand why earlier. When I re-ran it, it completed without issues and ran both times.
I think you have two choices to resolve your issue: 1. Remove the `@Parameters` annotation from `stringValues()` method and add it to your test method like this: ```java private List stringValues(){ return Arrays.asList(new Object[][] { {"HELLO","OLLEH"}, {"TESTING", "GNITSET"} }); } @Test @Parameters(method = "stringValues") public void objectConstructor_InitializeStringBuilderInside_EqualsPassedString(String inputString, String expectedResult) { processor = new StringProcessor(inputString); Assert.assertEquals(expectedResult, processor.printReverseString()); } ``` OR 2. Remove `stringValues()` method and put the `@Parameters` annotation directly on your test method: ```java @Test @Parameters({ "HELLO, OLLEH", "TESTING, GNITSET" }) public void objectConstructor_InitializeStringBuilderInside_EqualsPassedString(String inputString, String expectedResult) { processor = new StringProcessor(inputString); Assert.assertEquals(expectedResult, processor.printReverseString()); } ```
16,293
How can we maintain Selenium scripts when the application changes? Specifically, how do we define and manage automation to keep it up to date with changes in the application being tested?
2015/12/29
[ "https://sqa.stackexchange.com/questions/16293", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/15824/" ]
Do you mean something like version control? Your developers use probably SVN or GIT, so all your tests should be stored there as well. This way you can checkout any old version of the code and the right tests for it will be checked out too.
The same question has been asked multiple times : [Building "slow to break" regression tests](https://sqa.stackexchange.com/questions/4/building-slow-to-break-regression-tests) [How can I structure Selenium tests in a way that minimizes the maintenance work?](https://sqa.stackexchange.com/questions/8470/how-can-i-structure-selenium-tests-in-a-way-that-minimises-the-maintenance-work?rq=1) I would suggest you to go through both these links because it has loads of ideas and suggestions people have mentioned as to how you can build a properly maintainable test framework. Also I could think of this particular [link](https://sqa.stackexchange.com/questions/3933/how-do-i-keep-selenium-test-cases-dry?rq=1) , which talks about the principle of **DRY (Don't Repeat Yourself)** to be particularly apt for your scenario. Please go through it as well.
39,073,346
I have 2 tables: **checkinout** ``` Userid | Checktime | Checktype | VERIFYCODE | SENSORID | Memoinfo | WorkCode | sn | ``` **userinfo** ``` Userid | Name | Gender ``` I want to get the column Name only from userinfo table and insert it to checkinout table corresponds to their Userid, `checkinout.userid=userinfo.userid` Below is my query but I'm getting syntax error around userinfo, can you tell what I'm missing? > > Syntax Error: unexpected 'userinfo' (identifier) > > > ``` SELECT checkinout.USERID, checkinout.CHECKTIME, checkinout.CHECKTYPE,checkinout.VERIFYCODE, checkinout.SENSORID, checkinout.Memoinfo, checkinout.WorkCode, checkinout.sn, userinfo.name from bio_raw.checkinout, bio_raw.userinfo join bio_raw.userinfo on checkinout.userid = userinfo.userid ```
2016/08/22
[ "https://Stackoverflow.com/questions/39073346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6329280/" ]
You can not mix explizit and implizit join: ``` SELECT checkinout.USERID, checkinout.CHECKTIME, checkinout.CHECKTYPE,checkinout.VERIFYCODE, checkinout.SENSORID, checkinout.Memoinfo, checkinout.WorkCode, checkinout.sn, userinfo.name from bio_raw.checkinout join bio_raw.userinfo on checkinout.userid = userinfo.userid ```
When you want to join 2 tables there is no need to put all of them in `FROM` param. ``` SELECT checkinout.USERID, checkinout.CHECKTIME, checkinout.CHECKTYPE,checkinout.VERIFYCODE, checkinout.SENSORID, checkinout.Memoinfo, checkinout.WorkCode, checkinout.sn, userinfo.name from bio_raw.checkinout join bio_raw.userinfo on checkinout.userid = userinfo.userid ```
13,351,314
So I'm a pretty spoiled rubyist and basically never have to install anything using sudo anymore. I've installed node.js and npm (granted, using the Mac 64-bit .pkg, which could have done gosh knows what on my system) and they work fine. Now, executing the following: `npm install jasmine-node -g` Doesn't work and says, "Please try running this command again as root/Administrator." which I take to mean `sudo npm install jasmine-node -g` Doing: `npm install jasmine-node` (*not* globally) works fine, but doesn't setup my path correctly, doesn't run from the command line, etc. **How *should* I install jasmine-node?** `cd` to `/usr/local/bin` and install it (without the '-g' option) there? Use homebrew? Or use the `sudo ...` command I listed above? Thanks. /UPDATE: As mentioned above, I installed node.js & npm on my Lion OS X Mac (64-bit) using the universal installer and here are my node/npm listings in /usr/local/bin, in case they're of help: ``` -rwxr-xr-x 1 24561 wheel 355 Apr 11 2012 /usr/local/bin/node-waf -rwxr-xr-x 1 24561 wheel 18930304 Oct 25 14:07 /usr/local/bin/node lrwxr-xr-x 1 root admin 38 Nov 12 10:00 /usr/local/bin/npm -> ../lib/node_modules/npm/bin/npm-cli.js ``` Also, I found [this answer](https://stackoverflow.com/a/13219572/492404), which is one other option (in addition to the three I presented above). Please let me know which method is recommended (again, ideally without using 'sudo' is my preference). /END UPDATE Here is what doing it with `-g` (globally) returns (not using `sudo`): ``` npm http GET https://registry.npmjs.org/jasmine-node npm http 200 https://registry.npmjs.org/jasmine-node npm http GET https://registry.npmjs.org/jasmine-node/-/jasmine-node-1.0.26.tgz npm http 200 https://registry.npmjs.org/jasmine-node/-/jasmine-node-1.0.26.tgz npm ERR! Error: EACCES, mkdir '/usr/local/lib/node_modules/jasmine-node' npm ERR! { [Error: EACCES, mkdir '/usr/local/lib/node_modules/jasmine-node'] npm ERR! errno: 3, npm ERR! code: 'EACCES', npm ERR! path: '/usr/local/lib/node_modules/jasmine-node', npm ERR! fstream_type: 'Directory', npm ERR! fstream_path: '/usr/local/lib/node_modules/jasmine-node', npm ERR! fstream_class: 'DirWriter', npm ERR! fstream_stack: npm ERR! [ 'DirWriter._create (/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23)', npm ERR! '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:37:53', npm ERR! 'Object.oncomplete (fs.js:297:15)' ] } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! System Darwin 11.4.2 npm ERR! command "node" "/usr/local/bin/npm" "install" "jasmine-node" "-g" npm ERR! cwd /Users/brad/play/troles npm ERR! node -v v0.8.14 npm ERR! npm -v 1.1.65 npm ERR! path /usr/local/lib/node_modules/jasmine-node npm ERR! fstream_path /usr/local/lib/node_modules/jasmine-node npm ERR! fstream_type Directory npm ERR! fstream_class DirWriter npm ERR! code EACCES npm ERR! errno 3 npm ERR! stack Error: EACCES, mkdir '/usr/local/lib/node_modules/jasmine-node' npm ERR! fstream_stack DirWriter._create (/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23) npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:37:53 npm ERR! fstream_stack Object.oncomplete (fs.js:297:15) npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /Users/brad/play/troles/npm-debug.log npm ERR! not ok code 0 ```
2012/11/12
[ "https://Stackoverflow.com/questions/13351314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492404/" ]
I just changed the ownership of all the folders node was concerned with. ``` sudo chown -R my_account_name /usr/local/lib/node_modules/ sudo chown -R my_account_name /usr/local/lib/node/ sudo chown -R my_account_name /usr/local/include/node/ ``` I don't really know if that's bad practice, but I don't really give a damn.
When you run npm install -g somepackage, you may get an EACCES error asking you to run the command again as root/Administrator. It's a permissions issue. It's **easy to fix**, open your terminal (Applications > Utilities > Terminal) ``` sudo chown -R $USER /usr/local ``` \*\* I strongly recommend you to not use the package management with sudo (sudo npm -g install something), because you can get some issues later \*\* Reference: <http://foohack.com/2010/08/intro-to-npm/> **\*\* Recommended way \*\*** The reason is because this can cause permissions problems with lots of other apps, so I'd suggest not doing this. **A better solution when you are installing in global:** > > sudo chown -R `whoami` ~/.npm > > >
16,975,601
My html/css code interferes with my **HTML/CSS** drop down menu I have one textbox positioned above my navigation bar but the css code inter fears with my css dropdown. **[JSFIDDLE](http://jsfiddle.net/K6fey/1/)** **HTML** ``` <title>Mingamez.com</title> <link rel="shortcut icon" href="images/favicon.png"> <link rel="stylesheet" type="text/css" href="css/main.css"/> </head> <div id='cssmenu'> <ul> <li class='active'><a href='index.html'><span><img style="height: 35px;width:75;" src="images/logo_image.png" alt="website logo"/></span></a></li> <li class='has-sub'><a href='#'><span><img src="images/menu_image.png" alt="Menu"/> </span></a> <ul> <li class='has-sub'><a href='#'><span>Product 1</span></a> <ul> <li><a href='#'><span>Sub Item</span></a></li> <li class='last'><a href='#'><span>Sub Item</span></a></li> </ul> </li> <li class='has-sub'><a href='#'><span>Product 2</span></a> <ul> <li><a href='#'><span>Sub Item</span></a></li> <li class='last'><a href='#'><span>Sub Item</span></a></li> </ul> </li> </ul> </div> <form method="get" action="search" id="advsearch"> <input name="q" type="text" size="40" placeholder="Search..." /> </form> </html> ``` **CSS** ``` /** Body */ body{ background-color:#9FBAC4; } /** Advanced css menu */ #cssmenu ul { margin: 0; padding: 0; z-index:-1;} #cssmenu li { margin: 0; padding: 0; z-index:-1;} #cssmenu a { margin: 0; padding: 0; z-index:-1;} #cssmenu ul {list-style: none; z-index:-1;} #cssmenu a {text-decoration: none; z-index:-1;} #cssmenu { height: 62px; background-color: rgb(35,35,35); box-shadow: 0px 2px 3px rgba(0,0,0,.4);} #cssmenu { position: fixed; left: 0; top: 0; width: 100%; z-index:-1;} #cssmenu > ul > li { float: left; margin-right: 35px; margin-left: 35px; position: relative; } #cssmenu > ul > li > a { color: rgb(160,160,160); font-family: Verdana, 'Lucida Grande'; font-size: 15px; line-height: 70px; padding: 15px 20px; -webkit-transition: color .15s; -moz-transition: color .15s; -o-transition: color .15s; transition: color .15s; } #cssmenu > ul > li > a:hover {color: rgb(250,250,250); } #cssmenu > ul > li > ul { opacity: 0; visibility: hidden; padding: 16px 0 20px 0; background-color: rgb(250,250,250); text-align: left; position: absolute; top: 55px; left: 50%; margin-left: -90px; width: 180px; -webkit-transition: all .3s .1s; -moz-transition: all .3s .1s; -o-transition: all .3s .1s; transition: all .3s .1s; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0px 1px 3px rgba(0,0,0,.4); -moz-box-shadow: 0px 1px 3px rgba(0,0,0,.4); box-shadow: 0px 1px 3px rgba(0,0,0,.4); } #cssmenu > ul > li:hover > ul { opacity: 1; top: 68px; visibility: visible; } #cssmenu > ul > li > ul:before{ content: ''; display: block; border-color: transparent transparent rgb(250,250,250) transparent; border-style: solid; border-width: 10px; position: absolute; top: -20px; left: 50%; margin-left: -10px; } #cssmenu > ul ul > li { position: relative;} #cssmenu ul ul a{ color: rgb(50,50,50); font-family: Verdana, 'Lucida Grande'; font-size: 13px; background-color: rgb(250,250,250); padding: 5px 8px 7px 16px; display: block; -webkit-transition: background-color .1s; -moz-transition: background-color .1s; -o-transition: background-color .1s; transition: background-color .1s; } #cssmenu ul ul a:hover {background-color: rgb(240,240,240);} #cssmenu ul ul ul { visibility: hidden; opacity: 0; position: absolute; top: -14px; right: 206px; padding: 16px 0 20px 0; background-color: rgb(250,250,250); text-align: left; width: 160px; -webkit-transition: all .83s; -moz-transition: all .83s; -o-transition: all .83s; transition: all .83s; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0px 1px 3px rgba(0,0,0,.4); -moz-box-shadow: 0px 1px 3px rgba(0,0,0,.4); box-shadow: 0px 1px 3px rgba(0,0,0,.4); } #cssmenu ul ul > li:hover > ul { opacity: 1; left: -170px; visibility: visible;} #cssmenu ul ul a:hover{ background-color: rgb(0,133,143); color: rgb(240,240,240); } /** Advanced Css Search Box */ #advsearch { text-align: center; margin-top: 0px; } #advsearch input[type="text"] { background: url(images/search-dark.png) no-repeat 10px 6px #fcfcfc; border: 1px solid #d1d1d1; font: bold 12px Arial,Helvetica,Sans-serif; color: #bebebe; width: 150px; padding: 6px 15px 6px 35px; -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; text-shadow: 0 2px 3px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15) inset; -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15) inset; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15) inset; -webkit-transition: all 0.7s ease 0s; -moz-transition: all 0.7s ease 0s; -o-transition: all 0.7s ease 0s; transition: all 0.7s ease 0s; } #advsearch input[type="text"]:focus { width: 200px; } ```
2013/06/07
[ "https://Stackoverflow.com/questions/16975601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1978141/" ]
It looks like you're having a layering issue - the box around the input field actually extends the whole screen width and is in front of the menu so you can't "get to" the menu. Easy fix, just set a width on `#advsearch` and give it a higher `z-index`. Like this: ``` #advsearch { text-align: center; margin: 20px auto 0px; width:250px; position:relative; z-index:100; } ``` I also added a z-index higher than -1 to `#cssmenu` (I used `z-index:50;`) because -1 makes the menu unusable on most browsers. Working example: <http://jsfiddle.net/daCrosby/K6fey/3/>
first of all close your html tags properly. you have missed the li and ul closing tags. ``` </li> </ul> ``` close this before tags change the below css: (add padding-top:20px; ) ``` #cssmenu { position:fixed; left: 0; padding-top:25px; top: 0; width: 100%; z-index:-1; } ```
14,403
I'll give you an example of a divine person: God the Father. I'll give you an example of a human person: the apostle Paul. **According to Roman Catholic orthodoxy** (note: cite it), is Jesus Christ a human person, a divine person, both, or none?
2013/02/22
[ "https://christianity.stackexchange.com/questions/14403", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/-1/" ]
There are two issues here, which can unfortunately interact in a confusing way. Part 1: Christ is one Person. He is fully human. He is also fully divine. That's what it means to have those two natures. So both "divine" and "human" can be correctly used as predicate adjectives describing Christ. Part 2: Theologians have decided to use only the greater of the two natures, namely the divine, as an attributive adjective for Him. So they call Him a divine person, and they do not call him a human person. This decision leads to the linguistically strange situation that theologians say that Christ is a person, that Christ is human, but not that Christ is a human person.
Jesus Christ is one Person, a divine Person, with two natures, His divine nature, and His human nature. He cannot be, and is not, two persons. He is already the second Divine Person of the Most Holy Trinity, so He cannot logically be also a human person.
72,689,384
I'm trying to create a C program that creates a txt file with random integers, and then `mmap` the said file and `qsort` it. Creating the txt and mapping goes smoothly, but I can't figure out why `qsort` just destroys it. My guess, it's something to do with data types, but even after playing around with them, I get more or less the same result. compar: ``` int cmp(const void *p1, const void *p2) { return (*(const int *)p1 - *(const int *)p2); } ``` mmap and qsort: ``` char *addr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, myFile, 0); for (int i = 0; i < size; i++) printf("%c", addr[i]); qsort(addr, 20, sizeof(char), cmp); printf("\n-------------\n"); for (int i = 0; i < size; i++) printf("%c", addr[i]); ``` output example: ``` 10 19 9 8 18 2 9 6 3 7 15 12 12 14 6 2 4 3 15 13 ------------- 296 1 9 93818 1 0 7 15 12 12 14 6 2 4 3 15 13 ``` So 20 random integers are created in txt and mapped with no problems. But I guess `qsort` doesn't like what's given to it. I tried having `mmap` as `int`, but that created other problems like incorrect numbers in the array and incorrect amount of numbers and some 0s (perhaps I handled the output incorrectly). I'm not exactly sure what I'm doing wrong. here is the full code in case if it's needed: ``` #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <time.h> #include <stdlib.h> int cmp(const void *p1, const void *p2); void rand_txt(int size); int main() { rand_txt(20); int myFile = open("rand.txt", O_RDWR); struct stat myStat = {}; fstat(myFile, &myStat); off_t size = myStat.st_size; char *addr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, myFile, 0); for (int i = 0; i < size; i++) printf("%c", addr[i]); qsort(addr, 20, sizeof(char), cmp); printf("\n-------------\n"); for (int i = 0; i < size; i++) printf("%c", addr[i]); return 0; } int cmp(const void *p1, const void *p2) { return (*(const int*)p1 - *(const int*)p2); } //Function to create a txt with random integers in given size void rand_txt(int size) { FILE *fp = fopen("rand.txt", "w"); srand(time(0)); for (int i = 0; i < size; i++) fprintf(fp, "%d\n", (rand() % size) + 1); fclose(fp); } ``` Also a quickie: Do the arrays and pointers behave in the same way in practice(like strings)? say we declare: `int *x = { 10, 20, 30, 40 };` can we just `fprint("%d\t", x[i]);` or such type of arrays must be declared as `int[] = { 10, 20... };` and not with pointers? (I can and will test it myself and edit the "quickie" out if there is no answer until after I am able to test and study it)
2022/06/20
[ "https://Stackoverflow.com/questions/72689384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19200014/" ]
Here is the solution I might think is the right one ``` class CarRecord(models.Model): date_created = models.DateTimeField(auto_now_add=True) type = models.CharField(max_length=50) license = models.CharField(max_length=50) owners = models.ManyToManyField(User, related_name='car_owners') creator = models.ForeignKey(User,on_delete=models.DO_NOTHING) class CarRecordSerializer(serializers.ModelSerializer): creator = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=False) owners_details = UserSerializer(source='owners', many=True, read_only=True) class Meta: model = CarRecord fields = '__all__' def create(self, validated_data): try: new_owners = validated_data.pop('owners') except: new_owners = None car_record = super().create(validated_data) if new_owners: for new_owner in new_owners: car_record.owners.add(new_owner) return car_record ``` In views.py ``` from rest_frameword import generics from rest_framework import permissions class CustomCarRecordPermissions(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method == 'GET': return True elif request.method == 'PUT' or request.method == 'PATCH': return request.user == obj.creator or request.user in obj.owners.all() elif request.method == 'DELETE': return request.user == obj.creator return False class CarRecordListCreate(generics.ListCreateAPIView): permission_classes = (IsAuthenticated, ) serializer_class = CarRecordSerializer queryset = CarRecord.objects.all() def post(self, request, *args, **kwargs): request.data['creator'] = request.user.id return super().create(request, *args, **kwargs) class CarRecordDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = (CustomCarRecordPermissions, ) serializer_class = CarRecordSerializer lookup_field = 'pk' queryset = CarRecord.objects.all() ``` models is self explanatory; In CarRecord serializers we set creator as required False and primary key related field so that we can supply request user id before create as shown in views.py post method. In Detail view we set our custom permission; If the request is GET we allow permissions. But if the request is PUT or PATCH the owners and the creator are allowed. But if it is a delete request only creator is allowed.
You can write permission class car owner user. Your model. ``` class CarRecord(models.Model): date_created = models.DateTimeField() type = models.CharField(max_length=50) license = models.CharField(max_length=50) owners = models.ManyToManyField(User, related_name='car_owners', verbose_name=('owners'), default=[])) creator = models.ForeignKey(User,on_delete=models.DO_NOTHING) ``` Permission class **permission.py** ``` from rest_framework.permissions import BasePermission, from cars.models import CarRecord class isCarAccess(BaseCommand): def has_permission(self, request, view): if request.method == 'OPTIONS': return True check_user = CarRecord.objects.filter(owners__in=[request.user]) return request.user is not None and request.user.is_authenticated and check_user ``` this permission class will check that does user exists, user is authenticated and as well the user belongs to the card record or not. And you can pass this permission in your view. ``` from .permission import isCarAccess from .models import CarRecord class CarRecordViews(APIView): permission_classes = [isCarAccess] def get(self, request): car_record = CarRecord.objects.filter(owners__in=[request.user]) # return all records of cars that user some type of permission for ``` and your **settings.py** ``` REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ), } ```
14,439,993
I would like to use push notification message without badge, message or sound, only with application related JSON in order to update app's content in realtime. These notifications useless when app is not running so I won't send them when app enters background or user idle (sending unsubsrcibe to my server ) and subscribe again when app enters foreground or user activity. Does Apple permit this usage of push notification? I wouldn't like to use polling or custom socket based solution.
2013/01/21
[ "https://Stackoverflow.com/questions/14439993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413505/" ]
Im sure there are more reasons to not use APNS for realtime communication with your server, but here are two 'blocker' 1. you will not be able to unsubscribe from your server if the user lost connection. 2. push notifications are not reliable in terms of delivery time. You will only get notice by the push-server that your apn is queued, not that it is actualy delivered.
Apple specifically instructs against using it to send data. Only to notify that new data is available. And notifications are explicitly not real time.
29,944,647
This question has been asked before but not solved. I'm using jquery Tabs and Accordion, both on the same page and they simple won't work together. They work seperate on individual pages, but as soon as theyre on the same page the tabs won't work. In fact, it flips randomly between which one works and which one doesnt when I reload the page. I'm hoping to nest accordions within tabs using jquery. Reordering the js loading order doesnt appear to help as some people have had luck doing, though my instinct is its a loading order issue. Here is the html: ``` <div id="styleguide-tabs-demo-regular"> <ul> <li><a href="#tabs-1">Tab One</a></li> <li><a href="#tabs-2">Tab Two</a></li> <li><a href="#tabs-3">Tab Three</a></li> </ul> <div id="tabs-1">Tab 1 content</div> <div id="tabs-2">Tab 2 content</div> <div id="tabs-3">Tab 3 content</div> </div> <p><br /><br /><br /><br /></p> <div class="styleguide_demo_accordion1"> <h3><a href="#">Section 1</a></h3> <div> <div class="styleguide-section__accordion-demo-element">Content for Section 1</div> </div> <h3><a href="#">Section 2</a></h3> <div> <div class="styleguide-section__accordion-demo-element">Content for Section 2</div> </div> <h3><a href="#">Section 3</a></h3> <div> <div class="styleguide-section__accordion-demo-element">Content for Section 3</div> </div> </div> <p>&nbsp;</p> ``` jquery: ``` $("div.styleguide_demo_accordion1").accordion({header: "h2", collapsible: true, heightStyle: "content", active: false}) $("div#customaccordion").accordion({header: "h2", collapsible: true, heightStyle: "content", active: false}) $(function() { $( "#tabs" ).tabs(); }); $("div#styleguide-tabs-demo-regular").tabs(); ``` Any help would be amazing!
2015/04/29
[ "https://Stackoverflow.com/questions/29944647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403887/" ]
I tried your code, created a [JSFiddle](http://jsfiddle.net/Lg30296h/) and all I had to change was this line: ``` $("div.styleguide_demo_accordion1").accordion({header: "h2", collapsible: true, heightStyle: "content", active: false}) ``` to ``` $("div.styleguide_demo_accordion1").accordion({header: "h3", collapsible: true, heightStyle: "content", active: false}) ``` So basically, after changing the `header` option from `h2` to `h3`, it appears to work as intended. Is it possible that you just made a typing error?
Nothing strange. There are `<h3>` in HTML while `header: "h2"` in JS Change all `<h3>` to `<h2>` or `header: "h2"` to `header: "h3"` and it will be OK
38,185,206
I have a date in String format, in the following manner "2016-07-08" (8th July 2016). I need to check if this is a Friday, the reason is that the date will change and I will always need to check if the provided date is Friday. I am using the following code (assume startDate is a String which holds my date): ``` DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd"); java.util.Date date = formatter.parse(startDate); cal.setTime(date); if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY){ System.out.println("IT'S FRIDAY!!!!"); } ``` I tried outputting the value that is stored in cal, and it is returning Mon Jan 04 00:00:00 CET 2016.
2016/07/04
[ "https://Stackoverflow.com/questions/38185206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6547502/" ]
Capital `Y` is for week-year. You probably meant `yyyy-MM-dd` (with lower case `y` for the year). The [javadoc](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) lists all the valid patterns.
Your problem lies in pattern used for parsing years. Instead of creating SimpleDateFormat with `YYYY-MM-dd` please use this instead ``` new SimpleDateFormat("yyyy-MM-dd") ```
22,244,536
Clojure beginner here. Here's some code I'm trying to understand, from <http://iloveponies.github.io/120-hour-epic-sax-marathon/sudoku.html> (one page of a rather nice beginning Clojure course): --- ``` Subset sum is a classic problem. Here’s how it goes. You are given: a set of numbers, like #{1 2 10 5 7} and a number, say 23 and you want to know if there is some subset of the original set that sums up to the target. We’re going to solve this by brute force using a backtracking search. Here’s one way to implement it: (defn sum [a-seq] (reduce + a-seq)) (defn subset-sum-helper [a-set current-set target] (if (= (sum current-set) target) [current-set] (let [remaining (clojure.set/difference a-set current-set)] (for [elem remaining solution (subset-sum-helper a-set (conj current-set elem) target)] solution)))) (defn subset-sum [a-set target] (subset-sum-helper a-set #{} target)) So the main thing happens inside subset-sum-helper. First of all, always check if we have found a valid solution. Here it’s checked with (if (= (sum current-set) target) [current-set] If we have found a valid solution, return it in a vector (We’ll see soon why in a vector). Okay, so if we’re not done yet, what are our options? Well, we need to try adding some element of a-set into current-set and try again. What are the possible elements for this? They are those that are not yet in current-set. Those are bound to the name remaining here: (let [remaining (clojure.set/difference a-set current-set)] What’s left is to actually try calling subset-sum-helper with each new set obtainable in this way: (for [elem remaining solution (subset-sum-helper a-set (conj current-set elem) target)] solution)))) Here first elem gets bound to the elements of remaining one at a time. For each elem, solution gets bound to each element of the recursive call solution (subset-sum-helper a-set (conj current-set elem) target)] And this is the reason we returned a vector in the base case, so that we can use for in this way. ``` --- And sure enough, `(subset-sum #{1 2 3 4} 4)` returns `(#{1 3} #{1 3} #{4})`. But why must line 3 of `subset-sum-helper` return `[current-set]`? Wouldn't that return a final answer of `([#{1 3}] [#{1 3}] [#{4}])`? I try removing the enclosing brackets in line 3, making the function begin like this: ``` (defn subset-sum-helper [a-set current-set target] (if (= (sum current-set) target) current-set (let ... ``` Now `(subset-sum #{1 2 3 4} 4)` returns `(1 3 1 3 4)`, which makes it look like `let` accumulates not the three sets #{1 3}, #{1 3}, and #{4}, but rather just the "bare" numbers, giving `(1 3 1 3 4)`. So `subset-sum-helper` is using the list comprehension `for` within a recursive calculation, and I don't understand what's happening. When I try visualizing this recursive calculation, I found myself asking, "So what happens when ``` (subset-sum-helper a-set (conj current-set elem) target) ``` doesn't return an answer because no answer is possible given its starting point?" (My best guess is that it returns `[]` or something similar.) I don't understand what the tutorial writer meant when he wrote, "And this is the reason we returned a vector in the base case, so that we can use `for` in this way." I would greatly appreciate any help you could give me. Thanks!
2014/03/07
[ "https://Stackoverflow.com/questions/22244536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/627723/" ]
The `subset-sum-helper` function always returns a *sequence* of solutions. When the `target` is not met, the `solution` body at the end of the `for` expression enumerates such a sequence. When `target` is met, there is only one solution to return: the `current-set` argument. It must be returned as a sequence of one element. There are many ways to do this: ``` [current-set] ; as given - simplest (list current-set) (cons current-set ()) (conj () current-set) ... ``` If you cause an immediate return from `subset-sum-helper` (no recursion), you'll see the *vector*: ``` => (subset-sum #{} 0) [#{}] ``` Otherwise you'll see a *sequence* generated by `for`, which prints like a list: ``` => (subset-sum (set (range 1 10)) 7) (#{1 2 4} #{1 2 4} #{1 6} #{1 2 4} #{1 2 4} #{2 5} #{3 4} #{1 2 4} #{1 2 4} #{3 4} #{2 5} #{1 6} #{7}) ``` When no answer is possible, `subset-sum-helper` returns an empty sequence: ``` => (subset-sum-helper #{2 4 6} #{} 19) () ``` Once again, this is printed as though it were a list. The algorithm has problems: * It finds each solution many times - factorial of `(count s)` times for a solution `s`. * If an adopted element `elem` overshoots the target, it uselessly tries adding every permutation of the `remaining` set. --- The code is easier to understand if we recast it somewhat. The recursive call of `subset-sum-helper` passes the first and third arguments intact. If we use `letfn` to make this function local to `subset-sum`, we can do without these arguments: they are picked up from the context. It now looks like this: ``` (defn subset-sum [a-set target] (letfn [(subset-sum-helper [current-set] (if (= (reduce + current-set) target) [current-set] (let [remaining (clojure.set/difference a-set current-set)] (for [elem remaining solution (subset-sum-helper (conj current-set elem))] solution))))] (subset-sum-helper #{}))) ``` ... where the single call to the `sum` function has been expanded inline. It is now fairly clear that `subset-sum-helper` is returning the solutions that include its single `current-set` argument. The `for` expression is enumerating, for each element `elem` of `a-set` *not* in the `current-set`, the solutions containing the current set and the element. And it is doing this in succession for all such elements. So, starting with the empty set, which all solutions contain, it generates all of them.
Maybe this explanation helps you: Firstly we can experiment in a minimal code the expected behaviour (with and without brackets) of the [for](http://clojuredocs.org/clojure_core/clojure.core/for) function but removing the recursion related code **With brackets:** ``` (for [x #{1 2 3} y [#{x}]] y) => (#{1} #{2} #{3}) ``` **Without brackets:** ``` (for [x #{1 2 3} y #{x}] y) => (1 2 3) ``` **With brackets and more elements into the brackets\***:\*\* ``` (for [x #{1 2 3} y [#{x} :a :b :c]] y) => (#{1} :a :b :c #{2} :a :b :c #{3} :a :b :c) ``` So you need (on this case) the brackets to avoid iterating over the set. If we dont use the brackets we'll have "x" as binding value for y, and if we use the brackets we'll have #{x} as binding value for y. In other words the code author needs a set and not iterating over a set as a binding value inside its for. So she put a set into a sequence "[#{x}]" **And summarising** "for" function takes a vector of one or more binding-form/**collection-expr** pairs So if your "collection-expre" is #{:a} the iteration result will be (:a) but if your "collection-expre" is [#{:a}] the iteration result will be (#{:a}) Sorry for the redundance on my explanations but it's difficult to be clear with these nuances
8,989,302
``` import java.util.*; public class Test { public static void main(String[] args) { List db = new ArrayList(); ShopDatabase sb = new ShopDatabase(db); sb.addEntry(new ProductEntry("film", 30, 400)); sb.addEntry(new CashierEntry("Kate", "Smith", 23, 600)); sb.addEntry(new ManagerEntry("Jack", "Simpson", 1, 700)); sb.addEntry(new ProductEntry("soap", 18, 3)); sb.addEntry(new ManagerEntry("Helen", "Jones", 60, 650)); sb.addEntry(new CashierEntry("Jane", "Tomson", 15, 900)); sb.addEntry(new ProductEntry("shampoo", 25, 5)); sb.addEntry(new CashierEntry("Bill", "Black", 59, 300)); Collections.sort(db); Iterator itr = db.iterator(); while (itr.hasNext()) { Entry element = (Entry) itr.next(); System.out.println(element + "\n"); } } } public abstract class Entry implements Comparable { public String name; public int id; public Entry(String name, int id) { this.name = name; this.id = id; } public String getName() { return this.name; } public int getId() { return this.id; } public int compareTo(Object entry) { Entry temp = (Entry) entry; int difference = this.id - temp.id; return difference; } public String toString() { return this.id + " " + this.name; } } public class People extends Entry { private String name; private String familyName; private int id; private int salary; public People(String name, String familyName, int id, int salary) { super(name, id); this.familyName = familyName; this.salary = salary; } /* * public String toString() { return this.id + " " + this.name + " " + * this.familyName + " " + this.salary; } /*public int compareTo(Object * entry) { Entry temp = (Entry) entry; int difference = this.id - temp.id; * return difference; * * } */ } public class ProductEntry extends Entry { public String name; public int id; public int stock; public ProductEntry(String name, int id, int stock) { super(name, id); this.stock = stock; } /* * public String toString() { return this.id + " " + this.name + " " + * this.stock; } /*public int compareTo(Object entry) { Entry temp = (Entry) * entry; int difference = this.id - temp.id; return difference; * * } */ } public class ManagerEntry extends People { public String name; public String familyName; public int id; public int salary; public ManagerEntry(String name, String familyName, int id, int salary) { super(name, familyName, id, salary); } } public class CashierEntry extends People { public String name; public String familyName; public int id; public int salary; public CashierEntry(String name, String familyName, int id, int salary) { super(name, familyName, id, salary); } /* * public String toString() { return this.id + " " + this.name + " " + * this.familyName + " " + this.salary; } */ } ``` Can anyone please help when I have code like this the output is ``` 1 Jack 15 Jane 18 soap 23 Kate 25 shampoo 30 film 59 Bill 60 Helen ``` but if I uncommenting toString in People and ProductEntry the output is ``` 0 null Simpson 700 0 null Tomson 900 0 null 3 0 null Smith 600 0 null 5 0 null 400 0 null Black 300 0 null Jones 650 ``` why name and id is becomming null ???? Thank you in advance
2012/01/24
[ "https://Stackoverflow.com/questions/8989302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1110626/" ]
The problem is that you have multiple fields called `name`. The one in `People` **shadows** the one in `Entry`, and so on. What happens is that the constructor sets the base class's `name`, and `toString()` prints out the derived class's `name` (which has never been initialized and is therefore `null`). Same for `id`. Simply remove `name` and `id` from `People` and `ProductEntry`, and it'll behave as you expect.
You're shadowing the variables `name` and `id` with other fields named `name`, and `id`, and so the compiler is getting confused as to what to refer to (the superclass versions, or the versions from `Person`, which are never defined). Follow @aix's and @Dave Newton's advice and you'll be good to go.
1,031,403
I am having a bizare problem where I have a script that works elsewhere on the site but refuses to work for me now. The problem is exclusive to IE, it works fine in Mozilla. Below is the form: ``` <form class="element_form" action="general_image.php" method="post"> <?php generate_input('hidden', '', 'id', $id);?> <input type="image" src="../images/delete.gif" name="action" value="delete" class="button" /> <input type="image" src="../images/tick.gif" name="action" value="active_switch" class="button" /> </form> ``` Here is the code that is supposed to work: ``` <?php include('header.php'); $db->connect(); $table = 'general_image'; $page = 'general'; $region = $_SESSION['region']; $action = $secure->secure_string($_REQUEST['action']); $id = $secure->secure_string($_POST['id']); $max_active = 1; if($action == 'active_switch' || $action == 'delete'){ $response = array(); $response['action'] = $action; $response['id'] = $id; if($action == 'active_switch'){ $query = 'SELECT * FROM general WHERE region = "' . $region . '"'; $result = mysql_query($query); if(!$result) { $utility->fail($action, 'query error: ' . $query); }else{ $row = mysql_fetch_assoc($result); $already_active = false; $active = ''; if($id == $row['fifi']){ $already_active = true; } $active .= $row['fifi']; $response['results'] = $active; if(!$already_active){ $update = ''; $active = ''; $update .= 'fifi="' . $id . '"'; $active .= $id; $query = 'UPDATE general SET ' . $update . ' WHERE region = "' . $region . '"'; $response['results'] = $active; }else{ $utility->redirect($page . '.php'); } } }elseif($action == 'delete') { $query = "DELETE FROM $table WHERE id=" . $id; } echo $query . "hello"; if(!mysql_query($query)) { $utility->fail($action, 'query error: ' . $query); } ``` If someone could tell me what I'm doing wrong that would be great. Thanks EDIT ``` $action = $secure->secure_string does the following: function secure_string($string) { return (strip_tags(addslashes(mysql_real_escape_string(stripslashes($string))))); } ```
2009/06/23
[ "https://Stackoverflow.com/questions/1031403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31677/" ]
i have found that sometimes it is better to have a hidden field for action then a submit button or image. if someone press RETURN or ENTER to submit the form which action will be returned ?
Are you remembering to `session_start();` ?
12,926,900
Let see code first ``` var name = "The Window"; var object = { name : "My Object", getNameFunc : function(){ return function(){ return this.name; }; } }; alert(object.getNameFunc()()); ``` the result is `"The Window"`; I want to know what happend in every step. I think `this` is point to the object which call this function; right? But why in this case `this` is `window`
2012/10/17
[ "https://Stackoverflow.com/questions/12926900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1041001/" ]
I tried other solutions and the exception didn't go away. So I decompiled the entire `jose4j 0.6.5 jar` with a Java Decomplier and look at its pom.xml. I realised it has a specific dependency on **slf4j-api, version 1.7.21**: [![enter image description here](https://i.stack.imgur.com/73LS8.png)](https://i.stack.imgur.com/73LS8.png) So in my project's pom.xml, I added the exact same dependency, updated my Maven project so that it downloads this jar into my repository and the exception was gone. However it may bring up another error caused by slf4j itself: ``` SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. ``` To overcome this issue, I added the following into my project's pom.xml. So altogether you need to add the following to your pom.xml and my `jose4j` ran without anymore issues: ``` <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.6.4</version> </dependency> ``` Remember to update your Maven project after amending your `pom.xml`. (Right-click Project folder in Eclipse `->` Maven `->` Update Project..)
Add the following jars to the class path or lib folder 1. [slf4j-api-1.7.2.jar](https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.7.2) 2. [slf4j-jdk14-1.7.2.jar](https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14/1.7.2)
24,278,731
Landscape mode handle when auto screen orientation is ON and easily turn to portrait. But Auto Screen Orientation is Off then forcefully change supported orientation which effect on if Auto Screen Orientation is ON. Pls tell me these things in WP How check auto screen orientation of setting ON or Off? Another way to change orientation of screen contents?
2014/06/18
[ "https://Stackoverflow.com/questions/24278731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3244180/" ]
One place that I have seen a `while(1);` is in embedded programming. The architecture used a main thread to monitor events and worker threads to handle them. There was a hardware watchdog timer (explanation [here](http://en.wikipedia.org/wiki/Watchdog_timer)) that would perform a soft reset of the module after a period of time. Within the main thread polling loop, it would reset this timer. If the main thread detected an unrecoverable error, a `while(1);` would be used to tie up the main thread, thus triggering the watchdog reset. I believe that assert failure was implemented with a `while(1);` as well.
``` while(1); ``` is actually very useful. Especially when it's a program that has some sort of passcode or so and you want to disable the use of the program for the user because, for an example, he entered the wrong passcode for 3 times. Using a `while(1);` would stop the program's progress and nothing would happen until the program is rebooted, mostly for security reasons.
46,437,808
I'm developing an android app, it has a Splash Screen that runs for 2500ms. I want to add the functionality for a User touch screen and skip this Activity. I could made it with a button, but for pretty objective I just want to add a screen touch listener (Don't know how.) My SplashScreen: ``` public class Splash extends Activity { // Splash screen timer private static int SPLASH_TIME_OUT = 2500; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splashactivity); /* * Showing splash screen with a timer. This will be useful when you * want to show case your app logo / company */ new Handler().postDelayed(new Runnable() { @Override public void run() { startActivity(new Intent(Splash.this, MainActivity.class)); finish(); } }, SPLASH_TIME_OUT); //Skip this intro RelativeLayout root_layout = (RelativeLayout) findViewById(R.id.root_splash); root_layout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { startActivity(new Intent(Splash.this, MainActivity.class)); finish(); return true; } }); } } ``` My splashactivity layout: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root_splash" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/splash_screen"> </RelativeLayout> ```
2017/09/27
[ "https://Stackoverflow.com/questions/46437808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4681874/" ]
**Try this it will resolve your problem** ``` <div *ngFor="let letter of letters" (click)="myMethod(letter)">{{letter}} </div> myMethod(selectedLetter){ let postLen = 3; // configurable let i=0, len =str1.length; let foundFlag = false; let arr1 = [], arr2 = [], arr3 = []; for(;i<len;i++){ if(str1[i] == selectedLetter){ for(k=0;k<postLen && (i+k)< len ; k++){ arr1.push(str1[i+k]); i++; } foundFlag = true; }else if(!foundFlag){ arr2.push(str1[i]); }else{ arr3.push(str1[i]); } } this.letters = arr3.concat(arr2); this.letters = this.letters.concat(arr1); } ```
Just use two lists with `ngIf`: the first list renders the letters before `currentLetter` or `currentLetter` itself, while the second list renders the letters after `currentLetter`. ``` <ng-container *ngFor="let letter of letters; index as i"> <button *ngIf="i>=letters.indexOf(currentLetter)" (click)="currentLetter = letter">{{letter}}</button> </ng-container> <ng-container *ngFor="let letter of letters; index as i"> <button *ngIf="i<letters.indexOf(currentLetter)" (click)="currentLetter = letter">{{letter}}</button> </ng-container> ``` [![result1](https://i.stack.imgur.com/oRN8f.png)](https://i.stack.imgur.com/oRN8f.png) [![result2](https://i.stack.imgur.com/JxUXq.png)](https://i.stack.imgur.com/JxUXq.png)
57,695,362
Maven dependencies are downloaded every time my build workflow is triggered. Travis CI provides a way to cache maven repository. Does Github actions provider similar functionality that allows to cache maven repository?
2019/08/28
[ "https://Stackoverflow.com/questions/57695362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1101512/" ]
For completeness, this is an example of how to cache the local Maven repository on subsequent builds: ``` steps: # Typical Java workflow steps - uses: actions/checkout@v1 - name: Set up JDK 11 uses: actions/setup-java@v1 with: java-version: 11 # Step that does that actual cache save and restore - uses: actions/cache@v1 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- # Step that runs the tests - name: Run tests run: mvn test ``` See [this page](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/caching-dependencies-to-speed-up-workflows) for more details.
As of 2021, the most up to date official answer would be ```yaml - name: Cache local Maven repository uses: actions/cache@v2 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- ``` taken from an official github example at <https://github.com/actions/cache/blob/master/examples.md#java---maven>
3,687,904
What's the least (negative) integer value that can be exactly represented by Double type in all major x86 systems? Especially in (simultaneously) JVM, MySQL, MS SQL Server, .Net, PHP, Python and JavaScript (whatever corresponding type it uses). The reason why I ask about this is because I'd like to choose a value to use to represent an error (to return from a function in case it couldn't be calculated successfully) - that's why I need an exact value to be 100% predictable for exact equality checks. Exceptions (try-catch) seem to work much slower - that's why I need such a thing.
2010/09/10
[ "https://Stackoverflow.com/questions/3687904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/274627/" ]
The answer: 1. Get a gun. 2. Track down those responsible and ... 3. Just kidding. But *someone* needs to stand up and take responsibility for their garbage, don't you think? We wouldn't really shoot them, but don't we wish sometimes that we could get face-to-face with the person or team and demand they answer why they did such a bad job?!?! I agree there is some real junk in the latest Microsoft products. In SSRS when you click into a text box in the middle of existing text and hit paste, after the paste operation the cursor is at the end of all the text instead of at the end of the pasted text (in the middle). SSRS and SSIS are just rife with all sorts of nonsense like this.
I had several such issues. That wizard is absolutely not reliable. If this is a one time task, I would export into csv, and then import from csv. If you need to run it regularly, write your own code.[We recently had a similar discussion: Should programmers use SSIS, and if so, why?](https://stackoverflow.com/questions/3558185/should-programmers-use-ssis-and-if-so-why/3558562#3558562)
46,394,306
Let's assume that I have 5 tables ``` CREATE TABLE Student ( id int not null primary key auto_increment, firtsname varchar(30) ); CREATE TABLE Lecture ( id int not null primary_key auto_increment, lecturename varchar(30) ); CREATE TABLE Teacher ( id int not null primary key auto_increment, name varchar(30) ); CREATE TABLE StudentLecture ( StudentID int, LectureID int, foreign key(StudentID) references Student(id), foreign key(LectureID) references Lecture(id) ); CREATE TABLE TeacherLecture ( TeacherID int, LectureID int, foreign key(TeacherID) references Teacher(id), foreign key(LectureID) references Lecture(id) ); ``` Let's assume that I put some data into every table. My question is is there a simple way to get in one query a result which contains Students Teachers and Lectures which are connected? My mean is i want to get something like: Student 'x' is assigned to 'lectureY' leading by 'teacherZ'. Or maybe this small database is poorly designed, i am newbie, still reading and trying. And second question is, how to make in this database properly to put the grades. A grades should be putting by the teachers, and every student should have a list of grades for each lecture. Thanks for helping.
2017/09/24
[ "https://Stackoverflow.com/questions/46394306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7945407/" ]
``` import re def askName(): name = input("Please enter your name: ") if re.match("[A-z]",name): with open("filename", "w") as f: f.write(name) else: askName() askName() ```
My solution upon many others: ``` while True: name=(input("Please enter your name: ")) if name and name.isalpha(): filename = ("name.txt") with open (filename, "a") as f: f.write (name + "\n") break else: print ("Invalid name. Try again") continue ```