id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
51,489,049
Flutter project exceeds .dex Method Reference Count limit
<p>Why does a Flutter project <strong><em>exceed 64K</strong> method reference in its <code>.dex</code> file</em>? </p> <p>I am wondering what the cause of this could be:<br> In a <em>rather small</em> Flutter project I use 13 <em>plugins</em>. Without <a href="https://developer.android.com/studio/build/multidex" rel="noreferrer">Multidex</a>, the Android build fails because it vastly exceeds the method reference limit.</p> <p>Is there any trick (e.g. Gradle related) that would allow to shrink the method reference count because I think that such a project should not exceed the limit?<br> (<em>if you want further information on why I think that this is odd, please take a look at older revisions of this question</em>)</p>
51,911,530
8
0
null
2018-07-24 00:59:50.827 UTC
1
2022-02-02 05:11:00.103 UTC
2018-08-18 17:15:19.403 UTC
null
6,509,751
null
6,509,751
null
1
30
android|flutter
9,539
<p><a href="https://developer.android.com/studio/build/shrink-code" rel="nofollow noreferrer">Use ProGuard</a> to eliminate unused classes at compile time. This will reduce your method count by a considerable amount.</p> <p>You will need to adjust the ProGuard rules to work with Flutter like the <a href="https://flutter.io/android-release/#step-1---configure-proguard" rel="nofollow noreferrer">Flutter documentation explains here</a>.</p>
51,828,448
Angular 2+: Get child element of @ViewChild()
<p>How can I access the child elements (here: <code>&lt;img&gt;</code>) of <code>@ViewChild()</code> in Angular 2+ without explicit declaration?</p> <p><strong>In template.html</strong></p> <pre><code>&lt;div #parent&gt; &lt;!-- There can be anything than &lt;img&gt; --&gt; &lt;img src="http://localhost/123.jpg" alt=""&gt; &lt;/div&gt; </code></pre> <p><strong>In component.ts</strong></p> <pre><code>@ViewChild('parent') parent; public getFirstChild() { this.firstChild = this.parent.? // } </code></pre> <p>The aim is, to be able to create a universal component that uses:</p> <pre><code>&lt;div #parent&gt; &lt;ng-content&gt;&lt;/ng-content&gt; &lt;/div&gt; </code></pre> <p>So the child elements of <code>#parent</code> need to be accessible without explicit declaration.</p>
51,828,743
4
0
null
2018-08-13 18:25:15.92 UTC
1
2022-01-18 16:09:12.647 UTC
2022-01-18 16:09:12.647 UTC
null
542,251
null
4,986,557
null
1
20
angular|typescript|angular-components|viewchild
48,506
<p>You can use the <code>nativeElement</code> property of the <code>ElementRef</code> given by <code>ViewChild</code> to get the corresponding HTML element. From there, standard DOM methods and properties give access to its children:</p> <ul> <li>element.children</li> <li>element.querySelector</li> <li>element.querySelectorAll</li> <li>etc.</li> </ul> <p>For example:</p> <pre><code>@ViewChild("parent") private parentRef: ElementRef&lt;HTMLElement&gt;; public getChildren() { const parentElement = this.parentRef.nativeElement; const firstChild = parentElement.children[0]; const firstImage = parentElement.querySelector("img"); ... } </code></pre> <p>See <a href="https://stackblitz.com/edit/angular-kgw8lx" rel="noreferrer"><strong>this stackblitz</strong></a> for a demo.</p>
37,372,357
Laravel - How to get current user in AppServiceProvider
<p>So I am usually getting the current user using <code>Auth::user()</code> and when I am determining if a user is actually logged in <code>Auth::check</code>. However this doesn't seem to work in my <code>AppServiceProvider</code>. I am using it to share data across all views. I <code>var_dump</code> both <code>Auth::user()</code> and <code>Auth::check()</code> while logged in and I get <code>NULL</code> and <code>false</code>. </p> <p>How can I get the current user inside my <code>AppServiceProvider</code> ? If that isn't possible, what is the way to get data that is unique for each user (data that is different according to the <code>user_id</code>) across all views. Here is my code for clarification.</p> <pre><code>if (Auth::check()) { $cart = Cart::where('user_id', Auth::user()-&gt;id); if ($cart) { view()-&gt;share('cart', $cart); } } else { view()-&gt;share('cartItems', Session::get('items')); } </code></pre>
37,373,424
3
1
null
2016-05-22 08:56:20.133 UTC
11
2022-02-14 08:27:35.983 UTC
2016-05-23 08:49:37.53 UTC
null
3,739,901
null
4,804,019
null
1
30
php|laravel|authentication|laravel-5|service-provider
28,942
<p>Laravel session is initialized in a middleware so you can't access the session from a Service Provider, because they execute <strong>before</strong> the middleware in the request lifecycle</p> <p>You should use a middleware to share your varibles from the session</p> <p>However, If for some other reason you want to do it in a service provider, you can do it using a <a href="https://laravel.com/docs/5.4/views#view-composers" rel="nofollow noreferrer">view composer</a> with a callback, like this:</p> <pre><code>public function boot() { //compose all the views.... view()-&gt;composer('*', function ($view) { $cart = Cart::where('user_id', Auth::user()-&gt;id); //...with this variable $view-&gt;with('cart', $cart ); }); } </code></pre> <p>The callback will be executed only when the view is actually being composed, so middlewares will be already executed and session will be available</p>
1,085,816
Right Align DataGridView Column Header in Winforms
<p>I have a column Name "Quote Price" in a DataGridView winforms control. I can right align a column with no spaces such as "Unit" howerver I can't right align the column header with column Name called "Quote Price". I have attempted to use the TopRight, MiddleRight and bottomRight with no success.</p> <pre><code>SelectedAdditionalCost.Columns["Quote Price"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight; // Doesn't want to right align SelectedAdditionalCost.Columns["Quote Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; // column contents No worries, right aligns. </code></pre> <p>I am sure I am doing something really silly, however, I can't get this working.</p>
1,085,870
2
0
null
2009-07-06 07:30:53.59 UTC
2
2017-09-05 05:27:33.057 UTC
2010-02-01 00:46:09.79 UTC
null
2,660
null
108,608
null
1
16
winforms|datagridview
45,765
<p>As I was writing up the below I realised something that may be the problem - the name of a <code>DataGridView</code> column cannot contain a space - you are referencing the columns collection by the header text, not the column name. Although, when I try and run code like you have in your example I hit a runtime error (null reference exception).</p> <p>Anyway, that aside:</p> <p>The code you have works perfectly for me, I implemented the following in one of my datagridview test projects (in the constructor) and the header text right aligns:</p> <pre><code>dataGridView.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight; dataGridView.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight; </code></pre> <p>Because you mentioned the space on the header text, column 2 included a space in its text.</p> <p>One thing I've seen mentioned is that the header text can appear to not right align when the sort glyph is stopping it from aligning fully to the cell margin.</p> <p>See if this makes any difference:</p> <pre><code>dataGridView.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable; </code></pre>
784,734
Using WPF Imaging classes - Getting image dimensions without reading the entire file
<p>Link <a href="https://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file">this</a> post I want to be able to read an image files height and width without reading in the whole file into memory.</p> <p>In the post Frank Krueger mentions there is a way of doing this with some WPF Imaging classes. Any idea on how to do this??</p>
785,383
2
0
null
2009-04-24 06:23:35.507 UTC
12
2014-08-05 23:55:27.597 UTC
2017-05-23 11:53:51.473 UTC
null
-1
null
90,922
null
1
20
wpf|image|image-processing|file-io|metadata
9,860
<p>This should do it:</p> <pre><code>var bitmapFrame = BitmapFrame.Create(new Uri(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg"), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); var width = bitmapFrame.PixelWidth; var height = bitmapFrame.PixelHeight; </code></pre>
871,549
How do I read/write App.config settings with PowerShell?
<p>I'd like to use PowerShell as part of our automated build process to update an App.config file while deploying into our test environment. How can I do this?</p>
871,576
2
0
null
2009-05-16 02:42:24.233 UTC
12
2009-05-16 17:02:41.233 UTC
2009-05-16 03:23:35.93 UTC
null
108,040
null
108,040
null
1
29
powershell|app-config
29,793
<p>Given this sample App.config: C:\Sample\App.config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;connectionStrings&gt; &lt;add name="dbConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/&gt; &lt;/connectionStrings&gt; &lt;/configuration&gt; </code></pre> <p>The following script, C:\Sample\Script.ps1, will read and write a setting:</p> <pre><code># get the directory of this script file $currentDirectory = [IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path) # get the full path and file name of the App.config file in the same directory as this script $appConfigFile = [IO.Path]::Combine($currentDirectory, 'App.config') # initialize the xml object $appConfig = New-Object XML # load the config file as an xml object $appConfig.Load($appConfigFile) # iterate over the settings foreach($connectionString in $appConfig.configuration.connectionStrings.add) { # write the name to the console 'name: ' + $connectionString.name # write the connection string to the console 'connectionString: ' + $connectionString.connectionString # change the connection string $connectionString.connectionString = 'Data Source=(local);Initial Catalog=MyDB;Integrated Security=True' } # save the updated config file $appConfig.Save($appConfigFile) </code></pre> <p>Execute the script:</p> <pre><code>PS C:\Sample&gt; .\Script.ps1 </code></pre> <p>Output:</p> <pre><code>name: dbConnectionString connectionString: Data Source=(local);Initial Catalog=Northwind;Integrated Security=True </code></pre> <p>Updated C:\Sample\App.config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;connectionStrings&gt; &lt;add name="dbConnectionString" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" /&gt; &lt;/connectionStrings&gt; &lt;/configuration&gt; </code></pre>
1,136,770
How to get an output of an Exec'ed program in Inno Setup?
<p>Is it possible to get an output of an <code>Exec</code>'ed executable?</p> <p>I want to show the user an info query page, but show the default value of MAC address in the input box. Is there any other way to achieve this?</p>
1,136,960
2
0
null
2009-07-16 10:40:48.513 UTC
8
2017-04-05 07:19:55.397 UTC
2016-06-15 07:20:26.867 UTC
null
850,848
versioner
null
null
1
35
inno-setup
21,385
<p>Yes, use redirection of the standard output to a file:</p> <pre class="lang-pascal prettyprint-override"><code>[Code] function NextButtonClick(CurPage: Integer): Boolean; var TmpFileName, ExecStdout: string; ResultCode: integer; begin if CurPage = wpWelcome then begin TmpFileName := ExpandConstant('{tmp}') + '\ipconfig_results.txt'; Exec('cmd.exe', '/C ipconfig /ALL &gt; "' + TmpFileName + '"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); if LoadStringFromFile(TmpFileName, ExecStdout) then begin MsgBox(ExecStdout, mbInformation, MB_OK); { do something with contents of file... } end; DeleteFile(TmpFileName); end; Result := True; end; </code></pre> <p>Note that there may be more than one network adapter, and consequently several MAC addresses to choose from.</p>
1,089,406
Why are the properties of anonymous types in C# read-only?
<p>In C#, the properties of anonymous types are read-only:</p> <pre><code>var person = new { Surname = "Smith", OtherNames = "John" }; person.Surname = "Johnson"; // ERROR: .Surname is read-only </code></pre> <p>Of course I can declare a real class if I want writable fields or properties, but regardless, what is the reasoning behind this design decision to make the properties read-only?</p>
1,089,429
2
3
null
2009-07-06 22:01:51.693 UTC
6
2022-05-05 00:23:27.667 UTC
null
null
null
null
33,080
null
1
54
c#|c#-3.0
11,621
<p>Interesting article on that <a href="http://blogs.msdn.com/sreekarc/archive/2007/04/03/immutable-the-new-anonymous-type.aspx" rel="noreferrer">here</a>. From there ...</p> <blockquote> <p>... [B]y ensuring that the members do not change, we ensure that the hash is constant for the lifetime of the object.This allows anonymous types to be used with collections like hashtables, without actually losing them when the members are modified. There are a lot of benefits of immutabilty in that, it drastically simplifies the code that uses the object since they can only be assigned values when created and then just used (think threading)</p> </blockquote>
2,597,166
Make dictionary from list with python
<p>I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value.</p> <p><code>x = (1,'a',2,'b',3,'c')</code> -> <code>{1: 'a', 2: 'b', 3: 'c'}</code></p> <pre><code>def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 key = val else: i = 0 self.dict[key] = val </code></pre> <p>A better way to get the same results?</p> <h2>ADDED</h2> <pre><code>i = iter(k) print dict(zip(i,i)) </code></pre> <p>seems to be working</p>
2,597,178
5
1
null
2010-04-08 02:20:43.187 UTC
7
2018-09-04 13:01:34.587 UTC
2018-09-04 13:01:34.587 UTC
null
1,222,951
null
260,127
null
1
28
python|list|dictionary
84,321
<pre><code>dict(x[i:i+2] for i in range(0, len(x), 2)) </code></pre>
2,760,931
Initial capacity of collection types, e.g. Dictionary, List
<p>Certain collection types in .Net have an optional "Initial Capacity" constructor parameter. For example:</p> <pre><code>Dictionary&lt;string, string&gt; something = new Dictionary&lt;string,string&gt;(20); List&lt;string&gt; anything = new List&lt;string&gt;(50); </code></pre> <p>I can't seem to find what the default initial capacity is for these objects on MSDN.</p> <p>If I know I will only be storing 12 or so items in a dictionary, doesn't it make sense to set the initial capacity to something like 20?</p> <p>My reasoning is, assuming that the capacity grows like it does for a StringBuilder, which doubles each time the capacity is hit, and each reallocation is costly, why not pre-set the size to something you know will hold your data, with some extra room just in case? If the initial capacity is 100, and I know I will only need a dozen or so, it seems as though the rest of that memory is allocated for nothing.</p>
2,760,961
5
0
null
2010-05-03 20:18:31.123 UTC
9
2022-06-07 01:16:21.523 UTC
2014-11-26 16:58:27.22 UTC
null
55,164
null
55,164
null
1
53
c#|.net|memory-management|collections|object-initializers
34,610
<p>If the default values are not documented, the reason is likely that the optimal initial capacity is an <strong>implementation detail</strong> and subject to change between framework versions. That is, you shouldn't write code that assumes a certain default value.</p> <p>The constructor <strong>overloads with a capacity are for cases in which you know better</strong> than the class what number of items are to be expected. For example, if you create a collection of 50 values and know that this number will never increase, you can initialize the collection with a capacity of 50, so it won't have to resize if the default capacity is lower.</p> <p>That said, you can determine the default values using Reflector. For example, in .NET 4.0 (and probably previous versions as well),</p> <ul> <li><p>a List&lt;T&gt; is initialized with a capacity of 0. When the first item is added, it is reinitialized to a capacity of 4. Subsequently, whenever the capacity is reached, the capacity is doubled.</p></li> <li><p>a Dictionary&lt;T&gt; is intialized with a capacity of 0 as well. But it uses a completely different algorithm to increase the capacity: it increases the capacity always to prime numbers.</p></li> </ul>
2,752,192
Array of function pointers in Java
<p>I have read <a href="https://stackoverflow.com/questions/122407/whats-the-nearest-substitute-for-a-function-pointer-in-java">this question</a> and I'm still not sure whether it is possible to keep pointers to methods in an array in Java. If anyone knows if this is possible (or not), it would be a real help. I'm trying to find an elegant solution of keeping a list of <code>String</code>s and associated functions without writing a mess of hundreds of <code>if</code> statements.</p> <p>Cheers</p>
2,752,205
6
0
null
2010-05-02 01:48:34.343 UTC
10
2021-02-26 16:02:39.667 UTC
2021-02-26 16:02:39.667 UTC
null
2,164,365
null
328,085
null
1
17
java|arrays|pointers|function
29,154
<p>Java doesn't have a function pointer per se (or "delegate" in C# parlance). This sort of thing tends to be done with anonymous subclasses.</p> <pre><code>public interface Worker { void work(); } class A { void foo() { System.out.println("A"); } } class B { void bar() { System.out.println("B"); } } A a = new A(); B b = new B(); Worker[] workers = new Worker[] { new Worker() { public void work() { a.foo(); } }, new Worker() { public void work() { b.bar(); } } }; for (Worker worker : workers) { worker.work(); } </code></pre>
2,575,044
BNF vs EBNF vs ABNF: which to choose?
<p>I want to come up with a language syntax. I have read a bit about these three, and can't really see anything that one can do that another can't. Is there any reason to use one over another? Or is it just a matter of preference?</p>
2,575,110
6
0
null
2010-04-04 16:19:59.003 UTC
8
2021-05-28 21:03:56.957 UTC
null
null
null
null
2,147
null
1
39
syntax|grammar|bnf|ebnf
10,118
<p>You have to think about <strong>EBNF</strong> and <strong>ABNF</strong> as extensions that help you just to be more concise and expressive while developing your grammars.</p> <p>For example think about an optional non-terminal symbol, in a <strong>BNF</strong> grammar you would define it by using intermediate symbols like:</p> <pre><code>A ::= OPTIONAL OTHER OPTIONAL ::= opt_part | epsilon </code></pre> <p>while with <strong>EBNF</strong> you can do it directly using optional syntax:</p> <pre><code>A ::= [opt_part] OTHER </code></pre> <p>Then since there's no way to express precedence in a <strong>BNF</strong> you have to use always intermediate symbols also for nested choices:</p> <pre><code>BNF A ::= B C B ::= a | b | c EBNF A ::= (a | b | c) C </code></pre> <p>This is true for many syntax issues that are allowed in an <strong>EBNF</strong> or <strong>ABNF</strong> grammar, thanks to syntactic sugar but not with a normal <strong>BNF</strong>. <strong>ABNF</strong> extends <strong>EBNF</strong>, allowing you to do more complicated things, like specifying how many occurrence of a symbol can be found together (i.e. <code>4*DIGIT</code>)</p> <p>So choosing an <strong>ABNF</strong> or an <strong>EBNF</strong> as language of choice for your grammar will make your work easier, since you will be more expressive without filling you grammar with useless symbols that will be generated anyway by your parser generator, but you won't care about them!</p>
3,152,439
What is a good mapping of .NET decimal to SQL Server decimal?
<p>I am having to interface some C# code with SQL Server and I want to have exactly as much precision when storing a value in the database as I do with my C# code. I use one of .NET's <code>decimal</code> type for a value. What datatype/precision would I use for this value in SQL Server? </p> <p>I am aware that the SQL Server <code>decimal</code> type is the type that most likely fits my needs for this. My question though is what scale and precision do I use so that it matches .NET's <code>decimal</code> type?</p>
3,152,535
6
1
null
2010-06-30 18:57:17.497 UTC
2
2018-02-14 18:26:03.033 UTC
2010-06-30 19:18:46.96 UTC
null
69,742
null
69,742
null
1
41
.net|sql-server|decimal
20,672
<p>You can use the SQL Server <code>decimal</code> type (<a href="http://msdn.microsoft.com/en-us/library/aa258832(SQL.80).aspx" rel="noreferrer">documentation here</a>). That allows you to specify a precision and scale for the numbers in the database, which you can set to be the same as in your C# code.</p> <p>Your question, however, seems to be about mapping the .NET decimal type to the SQL Server decimal type. And unfortunately, that's not straightforward. The SQL Server decimal, at maximum precision, covers the range from -10<sup>38</sup>+1 to 10<sup>38</sup>-1. In .NET, however, it can cover anywhere from ±10<sup>−28</sup> to ±7.9×10<sup>28</sup>, depending on the number.</p> <p>The reason is that, internally, .NET treats decimals very similar to floats—it stores it as a pair of numbers, a mantissa and an exponent. If you have an especially large mantissa, you're going to lose some of the precision. Essentially, .NET allows you to mix numbers which have both a high and a low scale; SQL Server requires you to choose it for a given column ahead of time.</p> <p><strong>In short</strong>, you're going to need to decide what the valid range of decimal values are, for your purposes, and ensure both your program and the database can handle it. You need to do that anyway for your program (if you're mixing values like 10<sup>−28</sup> with 7.9×10<sup>28</sup>, you can't rely on the decimal type anyway).</p>
2,679,193
How to name variables on the fly?
<p>Is it possible to create new variable names on the fly?</p> <p>I'd like to read data frames from a list into new variables with numbers at the end. Something like orca1, orca2, orca3...</p> <p>If I try something like</p> <pre><code>paste("orca",i,sep="")=list_name[[i]] </code></pre> <p>I get this error</p> <pre><code>target of assignment expands to non-language object </code></pre> <p>Is there another way around this?</p>
2,679,289
6
1
null
2010-04-20 22:38:26.43 UTC
61
2018-07-05 16:17:58.163 UTC
2016-10-27 19:47:38.063 UTC
null
4,099,593
null
313,163
null
1
105
r|assign|r-faq
112,668
<p>Use <code>assign</code>:</p> <pre><code>assign(paste("orca", i, sep = ""), list_name[[i]]) </code></pre>
2,568,234
How to plot data grouped by a factor, but not as a boxplot
<p>In R, given a vector</p> <pre><code>casp6 &lt;- c(0.9478638, 0.7477657, 0.9742675, 0.9008372, 0.4873001, 0.5097587, 0.6476510, 0.4552577, 0.5578296, 0.5728478, 0.1927945, 0.2624068, 0.2732615) </code></pre> <p>and a factor:</p> <pre><code>trans.factor &lt;- factor (rep (c("t0", "t12", "t24", "t72"), c(4,3,3,3))) </code></pre> <p>I want to create a plot where the data points are grouped as defined by the factor. So the categories should be on the x-axis, values in the same category should have the same x coordinate.</p> <p>Simply doing <code>plot(trans.factor, casp6)</code> does almost what I want, it produces a boxplot, but I want to see the individual data points.</p>
2,568,363
7
4
null
2010-04-02 17:50:19.023 UTC
8
2021-02-18 16:40:37.723 UTC
2014-01-01 18:03:29.323 UTC
null
1,315,767
null
3,306
null
1
12
r|plot
69,678
<pre><code>require(ggplot2) qplot(trans.factor, casp6) </code></pre>
3,154,582
Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails
<p>I get the following error when using a primitive attribute in my grails domain object:</p> <pre><code>Null value was assigned to a property of primitive type setter of MyDomain.myAttribute org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of MyDomain.myAttribute at grails.orm.HibernateCriteriaBuilder.invokeMethod(HibernateCriteriaBuilder.java:1077) </code></pre>
3,154,585
12
1
null
2010-07-01 01:33:11.543 UTC
19
2020-04-09 21:18:58.457 UTC
null
null
null
null
6,094
null
1
117
grails|grails-orm
167,646
<p>According to this <a href="https://stackoverflow.com/a/423718/42769">SO thread</a>, the solution is to use the non-primitive wrapper types; e.g., <code>Integer</code> instead of <code>int</code>.</p>
2,444,959
Would you use Code Bubbles?
<p>I've read <a href="https://stackoverflow.com/questions/2444719/how-to-implement-code-bubble-like-user-interface">this question</a> mentioning <a href="http://www.cs.brown.edu/people/acb/codebubbles_site.htm" rel="nofollow noreferrer">Code Bubbles</a> and I've watched their video presentation.</p> <p>The video is impressive, and does seem a little bit futuristic, but apparently it's somewhat real.</p> <p>But that kept me thinking... Would a developer really use such tool?</p> <p>We, as developers, are used to deal with code files, organizing them in directories, in one way or another, some common IDE (for those language that has them).</p> <p>It would be a great leap to use something like Code Bubbles, as they propose.</p> <p>I, personally, am not sure if I could work in such environment... although I think I would just need some adjusting... but I really don't see my mind working out the kinks of it.</p> <p>What are your thoughts on this?</p>
2,444,992
16
3
2010-03-15 03:40:36.073 UTC
2010-03-15 03:40:36.073 UTC
14
2011-09-05 12:02:43.88 UTC
2017-05-23 12:25:02.757 UTC
null
-1
null
44,375
null
1
29
ide|developer-tools
7,014
<p>For languages like C# and Java where the actual organisation of code files and blocks (methods, etc) is fairly rigid (even more so in Java than C#) then something that provides a novel "view" of the code could probably work. You could allow the tool to organise your code with one class per file, methods sorted by visibility, or whatever coding standard you wanted, and the tool could handle it all in such a way that someone could still come along and look at the "raw" files and make sense of it all.</p> <p>It would be a problem for a language like C++ where you can basically do whatever you like...</p>
33,547,583
Safe way to extract property names
<p>I'm looking for a way to get an object property name with typechecking that allows to catch possible regressions after refactoring. </p> <p>Here's an example: the component where I have to pass the property names as strings and it will be broken if I'll try to change the property names in the model.</p> <pre><code>interface User { name: string; email: string; } class View extends React.Component&lt;any, User&gt; { constructor() { super(); this.state = { name: "name", email: "email" }; } private onChange = (e: React.FormEvent) =&gt; { let target = e.target as HTMLInputElement; this.state[target.id] = target.value; this.setState(this.state); } public render() { return ( &lt;form&gt; &lt;input id={"name"} value={this.state.name} onChange={this.onChange}/&gt; &lt;input id={"email"} value={this.state.email} onChange={this.onChange}/&gt; &lt;input type="submit" value="Send" /&gt; &lt;/form&gt; ); } } </code></pre> <p>I'd appreciate if there's any nice solution to solve this issue.</p>
42,516,869
4
2
null
2015-11-05 14:48:07.04 UTC
10
2022-09-22 04:37:06.933 UTC
2018-11-06 22:23:27.667 UTC
null
3,345,644
null
334,904
null
1
45
typescript|reflection|metaprogramming
57,468
<p>In <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html" rel="nofollow noreferrer">TS 2.1</a> the <code>keyof</code> keyword was introduced which made this possible:</p> <pre><code>function propertyOf&lt;TObj&gt;(name: keyof TObj) { return name; } </code></pre> <p>or</p> <pre><code>function propertiesOf&lt;TObj&gt;(_obj: (TObj | undefined) = undefined) { return function result&lt;T extends keyof TObj&gt;(name: T) { return name; } } </code></pre> <p>or using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" rel="nofollow noreferrer">Proxy</a></p> <pre><code>export function proxiedPropertiesOf&lt;TObj&gt;(obj?: TObj) { return new Proxy({}, { get: (_, prop) =&gt; prop, set: () =&gt; { throw Error('Set not supported'); }, }) as { [P in keyof TObj]?: P; }; } </code></pre> <p>These can then be used like this:</p> <pre><code>propertyOf&lt;MyInterface&gt;(&quot;myProperty&quot;); </code></pre> <p>or</p> <pre><code>const myInterfaceProperties = propertiesOf&lt;MyInterface&gt;(); myInterfaceProperties(&quot;myProperty&quot;); </code></pre> <p>or</p> <pre><code>const myInterfaceProperties = propertiesOf(myObj); myInterfaceProperties(&quot;myProperty&quot;); </code></pre> <p>or</p> <pre><code>const myInterfaceProperties = proxiedPropertiesOf&lt;MyInterface&gt;(); myInterfaceProperties.myProperty; </code></pre> <p>or</p> <pre><code>const myInterfaceProperties = proxiedPropertiesOf(myObj); myInterfaceProperties.myProperty; </code></pre>
45,396,280
Customizing Increment Arrows on Input of Type Number Using CSS
<p>I have an input of type number that is rendered using the following code:</p> <p><code>&lt;input class="quantity" id="id_form-0-quantity" min="0" name="form-0-quantity" value="1" type="number"&gt;</code></p> <p>It looks like this: </p> <p><a href="https://i.stack.imgur.com/v328B.png" rel="noreferrer"><img src="https://i.stack.imgur.com/v328B.png" alt="enter image description here"></a></p> <p>I would like to turn it into something like this:</p> <p><a href="https://i.stack.imgur.com/8xCBK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8xCBK.png" alt="enter image description here"></a></p> <p>The second view is emulated using two separate buttons.</p> <p>How could I style the arrows as described?</p>
45,396,364
6
0
null
2017-07-30 04:11:37.33 UTC
52
2021-09-15 15:54:06.667 UTC
2018-07-30 21:25:10.35 UTC
null
1,891,677
null
5,969,463
null
1
76
html|css|textfield
168,162
<p><strong>tl;dr:</strong></p> <p>Having been asked in private about the following setup quite a few times, I decided to add a demo for it (Bootstrap 4 + jQuery + Font Awesome input-group setup):</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.btn-plus, .btn-minus').on('click', function(e) { const isNegative = $(e.target).closest('.btn-minus').is('.btn-minus'); const input = $(e.target).closest('.input-group').find('input'); if (input.is('input')) { input[0][isNegative ? 'stepDown' : 'stepUp']() } })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.inline-group { max-width: 9rem; padding: .5rem; } .inline-group .form-control { text-align: right; } .form-control[type="number"]::-webkit-inner-spin-button, .form-control[type="number"]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /&gt; &lt;script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;div class="input-group inline-group"&gt; &lt;div class="input-group-prepend"&gt; &lt;button class="btn btn-outline-secondary btn-minus"&gt; &lt;i class="fa fa-minus"&gt;&lt;/i&gt; &lt;/button&gt; &lt;/div&gt; &lt;input class="form-control quantity" min="0" name="quantity" value="1" type="number"&gt; &lt;div class="input-group-append"&gt; &lt;button class="btn btn-outline-secondary btn-plus"&gt; &lt;i class="fa fa-plus"&gt;&lt;/i&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p><strong>long (initial) answer:</strong></p> <p>The native <code>input[type=number]</code> controls are not style-able cross-browser. The easiest and safest way to achieve what you want cross-browser/cross-device is to hide them using:</p> <pre><code>input[type="number"] { -webkit-appearance: textfield; -moz-appearance: textfield; appearance: textfield; } input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; } </code></pre> <p>...which allows you to use your custom buttons, which could be linked to execute the functions the spinners (arrows) would (<code>.stepUp()</code> and <code>.stepDown()</code>), provided you keep the input's <code>type="number"</code>.</p> <p>For example:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>input[type="number"] { -webkit-appearance: textfield; -moz-appearance: textfield; appearance: textfield; } input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; } .number-input { border: 2px solid #ddd; display: inline-flex; } .number-input, .number-input * { box-sizing: border-box; } .number-input button { outline:none; -webkit-appearance: none; background-color: transparent; border: none; align-items: center; justify-content: center; width: 3rem; height: 3rem; cursor: pointer; margin: 0; position: relative; } .number-input button:before, .number-input button:after { display: inline-block; position: absolute; content: ''; width: 1rem; height: 2px; background-color: #212121; transform: translate(-50%, -50%); } .number-input button.plus:after { transform: translate(-50%, -50%) rotate(90deg); } .number-input input[type=number] { font-family: sans-serif; max-width: 5rem; padding: .5rem; border: solid #ddd; border-width: 0 2px; font-size: 2rem; height: 3rem; font-weight: bold; text-align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="number-input"&gt; &lt;button onclick="this.parentNode.querySelector('input[type=number]').stepDown()" &gt;&lt;/button&gt; &lt;input class="quantity" min="0" name="quantity" value="1" type="number"&gt; &lt;button onclick="this.parentNode.querySelector('input[type=number]').stepUp()" class="plus"&gt;&lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p><strong>Note:</strong> In order to change the input's value, one needs to find it. To provide flexibility, in the example above I grouped buttons and the <code>&lt;input&gt;</code> under a common parent and used that parent to find the <code>&lt;input&gt;</code> (choosing not to rely on their proximity or particular order in DOM). The above method <strong><em>will change any</em> <code>input[type=number]</code> <em>sibling to the buttons</em></strong>. If that's not convenient, one could use any other methods to find the input from the buttons:</p> <ul> <li>by <strong><em>id</em></strong>: <code>.querySelector('#some-id')</code>:</li> </ul> <pre class="lang-html prettyprint-override"><code>&lt;button onclick="this.parentNode.querySelector('#some-id').stepUp()"&gt;&lt;/button&gt; </code></pre> <ul> <li>by <strong><em>className</em></strong>: <code>.querySelector('.some-class')</code>:</li> </ul> <pre class="lang-html prettyprint-override"><code>&lt;button onclick="this.parentNode.querySelector('.some-class').stepUp()"&gt;&lt;/button&gt; </code></pre> <p>Also note the above examples only search inside the <code>.parentNode</code>, not in the entire <code>document</code>, which is also possible:<br> i.e: <code>onclick="document.getElementById('#some-id').stepUp()"</code></p> <ul> <li>by <strong><em>proximity</em></strong> (<code>previousElementSibling</code> | <code>nextElementSibling</code>)</li> </ul> <pre class="lang-html prettyprint-override"><code>&lt;button onclick="this.previousElementSibling.stepUp()"&gt;&lt;/button&gt; </code></pre> <ul> <li>any other way to determine and find a particular input element in a DOM structure. For example, one could use third party libraries, such as jQuery:</li> </ul> <pre class="lang-html prettyprint-override"><code>&lt;button onclick="$(this).prev()[0].stepUp()"&gt;&lt;/button&gt; </code></pre> <p>An important note when using jQuery is that the <code>stepUp()</code> and <code>stepDown()</code> methods are placed on the DOM element, not on the jQuery wrapper. The DOM element is found inside the <code>0</code> property of the <code>jQuery</code> wrapper.</p> <hr> <p><strong>Note</strong> on <code>preventDefault()</code>. Clicking a <code>&lt;button&gt;</code> inside a <code>&lt;form&gt;</code> <em>will</em> trigger the form submission. Therefore, if used as above, inside forms, the <code>onclick</code> should also contain <code>preventDefault();</code>. Example:</p> <pre><code>&lt;button onclick="$(this).prev()[0].stepUp();preventDefault()"&gt;&lt;/button&gt; </code></pre> <p>However, if one would use <code>&lt;a&gt;</code> tags instead of <code>&lt;button&gt;</code>s, this is not necessary. Also, the prevention can be set globally for all form buttons with a small JavaScript snippet:</p> <pre class="lang-js prettyprint-override"><code>var buttons = document.querySelectorAll('form button:not([type="submit"])'); for (i = 0; i &lt; buttons.length; i++) { buttons[i].addEventListener('click', function(e) { e.preventDefault(); }); } </code></pre> <p>... or, using jQuery:</p> <pre class="lang-js prettyprint-override"><code>$('form').on('click', 'button:not([type="submit"])', function(e){ e.preventDefault(); }) </code></pre>
10,389,808
Using HTTPS and httpWebRequest
<p>I am sending httpwebrequests to the paypal api server and this uses https. I did the normal things that you normally do with http requests, and it worked. Do I need to do anything special to properly use https, or is specifying https in the request URL enaugh to make it work?</p> <p>Thanks!</p> <p>Btw my requests are being sent from my server, so it isn't as important to encrypt them as if they where being sent from the client computer, but still I want to do it right.</p>
10,389,856
3
0
null
2012-04-30 19:59:13.62 UTC
2
2017-07-13 11:07:51.833 UTC
null
null
null
null
918,348
null
1
15
c#|asp.net|ssl|https
41,355
<p>Simply swapping http with https is fine enough while using <code>HttpWebRequest</code>. It requires no special handling for https requests.</p>
10,501,042
Cannot open .rpt Crystal Reports file in Visual Studio 2010
<p>I have taken over an existing C# project and am using Visual Studio 2010 with .NET framework 4.0.</p> <p>The application uses Crystal Reports. It seems like the definitions of the reports lie in a separately located folder containing many .rpt files.</p> <p>When I run the application, some of these reports work and others don't. I now want to debug the reports that don't work and also want to add some new Crystal Reports.</p> <p>Problem is, whenever I try to open one of the .rpt files in Visual Studio I get gibberish - it looks like binary code.</p> <p>For information: I already know that Crystal Reports does not come standard with Visual Studio 2010. I have therefore already installed <em>SAP Crystal Reports, version for Visual Studio 2010 - Click Once (64 Bit)</em> from the location <a href="http://www.businessobjects.com/jump/xi/crvs2010/us2_default.asp" rel="nofollow noreferrer">http://www.businessobjects.com/jump/xi/crvs2010/us2_default.asp</a> as was suggested in <a href="https://stackoverflow.com/questions/3668626/creating-a-crystal-reports-rpt-file-using-visual-studio-2010">Creating a Crystal Reports rpt file using Visual Studio 2010</a> and <a href="http://social.msdn.microsoft.com/Forums/en-US/vscrystalreports/thread/fb6d3588-1481-46a2-8284-90dbb40c42f6" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vscrystalreports/thread/fb6d3588-1481-46a2-8284-90dbb40c42f6</a></p> <p>Did I install the wrong thing or am I missing a dependency? The .rpt files are not part of the Visual Studio project. They are separate files in a folder. How do I go about opening them so that I can perform edits in Visual Studio?</p>
10,510,066
5
0
null
2012-05-08 14:52:08.627 UTC
2
2016-09-28 17:38:08.86 UTC
2017-05-23 12:25:24.137 UTC
null
-1
null
1,210,718
null
1
23
visual-studio-2010|crystal-reports
81,664
<p>I suspect the file-type association for .RPT is broken. You may have tried opening the .RPT before you had Crystal Reports installed and accidentally selected something else to open it. Now it probably automatically opens them incorrectly.</p> <p>This article describes changes between Windows versions and how to edit them: <a href="http://www.technize.com/advanced-file-types-association-in-windows-7/" rel="noreferrer">http://www.technize.com/advanced-file-types-association-in-windows-7/</a></p> <p>That said, there is a quicker easier way to do a quick test to confirm if those .RPT files are valid.</p> <p>In Visual Studio, inside your C# project, do an 'Add New Item > Reporting > Crystal Reports' and it will start a wizard for adding reports to your project. When this happens, you'll be prompted to 'create a new report' or to 'open from existing file'. Choose open existing and browse to your .RPT file. This should force Crystal Reports to attempt to open this file in the Visual Studio based Crystal Report designer.</p> <p>Best of luck with it.</p>
7,872,504
Excel VBA - select, get and set data in Table
<p>I've got a worksheet with a lot of tables in them and I'm just starting to use tables because they seem pretty handy. But I've never manipulated content in an Excel table before. And these tables are basically lists of columns with Firstname and Lastname. Based on the values on these columns, I want to generate a username. But I'm trying to write a generic Sub that takes arguments, such as worksheet and name of the table. </p> <p>Previously I've done this when the data has not been in a table:</p> <pre><code>Cells(2, 2).Select Do strFirstName = ActiveCell.Value strLastName = ActiveCell.Offset(0, 2).Value strFirstName = Left(strFirstName, 1) strUserName = strFirstName &amp; strLastName strUserName = LCase(strUserName) ActiveCell.Offset(0, 5).Value = strUserName ActiveCell.Offset(1, 0).Select Loop Until IsEmpty(ActiveCell) </code></pre> <p>And now I'm trying to do the exact same thing, only with data from a Table. Any ideas? I've added a watch for "ActiveSheet" to see if I can find the tables, and they seem to be in <code>ActiveSheet.ListObjects</code>, but I couldn't see any <code>.Select</code> option there. Perhaps I don't need to select the Table in order to manipulate it's content?</p>
7,874,472
1
0
null
2011-10-24 07:36:07.613 UTC
4
2016-11-09 13:59:55.69 UTC
2016-11-09 13:59:55.69 UTC
null
4,370,109
null
73,715
null
1
2
vba|excel
52,827
<p>When looping over a range (whether in a table or in a range) it is usually faster to copy the data to a variant array, manipulate that array, and then copy the result back to the sheet.</p> <pre><code>Sub zz() Dim oUsers As ListObject Dim v As Variant Dim vUserName() As Variant Dim i As Long Dim colFirst As Long Dim colLast As Long Dim colUser As Long Set oUsers = ActiveSheet.ListObjects(1) colFirst = oUsers.ListColumns("FirstName").Index colLast = oUsers.ListColumns("LastName").Index colUser = oUsers.ListColumns("UserName").Index v = oUsers.DataBodyRange ReDim vUserName(1 To UBound(v, 1), 1 To 1) For i = 1 To UBound(v, 1) vUserName(i, 1) = LCase(Left(v(i, colFirst), 1) &amp; v(i, colLast)) Next oUsers.ListColumns("UserName").DataBodyRange = vUserName End Sub </code></pre> <p>If you really want to loop over the range itself:</p> <pre><code> For i = 1 To oUsers.ListRows.Count oUsers.ListColumns("UserName").DataBodyRange.Rows(i) = LCase(Left( _ oUsers.ListColumns("FirstName").DataBodyRange.Rows(i), 1) &amp; _ oUsers.ListColumns("LastName").DataBodyRange.Rows(i)) Next </code></pre> <p>For this situation you could also just use a formula in the <code>UserName</code> column itself, with no vba required</p> <pre><code>=LOWER(LEFT([@FirstName],1)&amp;[@LastName]) </code></pre> <p><strong>EDIT</strong></p> <p>Sorry, don't know of a Formula way to remove any of a list of characters from a string. You might have to revert to vba for this. Here's a user defined function to do it. Your formula will become</p> <pre><code>=DeleteChars([@UserName],{"$","#"}) </code></pre> <p>To <em>Delete</em> the characters replace <code>{"$","#"}</code> with a array list of characters you want to remove (you can make the list as long as you need)<br> To <em>replace</em> the characters use <code>{"$","#";"X","X"}</code> where the list up to the ; is the old characters, after the ; the new. Just make sure the listsa are the same length. </p> <p>UDF code:</p> <pre><code>Function DeleteChars(r1 As Range, ParamArray c() As Variant) As Variant Dim i As Long Dim s As String s = r1 If UBound(c(0), 1) = 1 Then For i = LBound(c(0), 2) To UBound(c(0), 2) s = Replace(s, c(0)(1, i), "") Next Else For i = LBound(c(0), 2) To UBound(c(0), 2) s = Replace(s, c(0)(1, i), c(0)(2, i)) Next End If DeleteChars = s End Function </code></pre>
30,969,688
Ordered map in Swift
<p>Is there any <em>built-in</em> way to create an ordered map in Swift 2? Arrays <code>[T]</code> are sorted by the order that objects are appended to it, but dictionaries <code>[K : V]</code> aren't ordered.</p> <p>For example</p> <pre><code>var myArray: [String] = [] myArray.append("val1") myArray.append("val2") myArray.append("val3") //will always print "val1, val2, val3" print(myArray) var myDictionary: [String : String] = [:] myDictionary["key1"] = "val1" myDictionary["key2"] = "val2" myDictionary["key3"] = "val3" //Will print "[key1: val1, key3: val3, key2: val2]" //instead of "[key1: val1, key2: val2, key3: val3]" print(myDictionary) </code></pre> <p>Are there any built-in ways to create an ordered <code>key : value</code> map that is ordered in the same way that an array is, or will I have to create my own class? </p> <p>I would like to avoid creating my own class if at all possible, because whatever is included by Swift would most likely be more efficient.</p>
30,970,228
13
0
null
2015-06-21 21:51:48.8 UTC
13
2021-06-11 11:06:41.37 UTC
2019-07-26 22:33:36.847 UTC
null
2,767,207
null
2,767,207
null
1
66
ios|swift|dictionary|swift2
49,068
<p>You can order them by having keys with type <code>Int</code>.</p> <pre><code>var myDictionary: [Int: [String: String]]? </code></pre> <p>or</p> <pre><code>var myDictionary: [Int: (String, String)]? </code></pre> <p>I recommend the first one since it is a more common format (JSON for example).</p>
23,003,252
window.performance.now() equivalent in nodejs?
<p>I think the question is straight forward.</p> <p>I'm looking for something that's similar to window.performance.now() in nodejs V8 engine.</p> <p>Right now I'm just using:-</p> <pre><code>var now = Date.now(); //do some processing.. console.log("time elapsed:", Date.now() - now); </code></pre> <p>But, I read that window.performance.now() is lot more accurate than using the date because of the what's defined <a href="http://www.html5rocks.com/en/tutorials/webperformance/basics/">here</a>.</p>
23,003,576
9
0
null
2014-04-11 04:03:05.447 UTC
11
2022-09-02 09:56:30.577 UTC
null
null
null
null
1,204,312
null
1
106
javascript|node.js|navigation-timing-api
56,711
<p>I would only mention that three of the reasons the author gives for the preference of the timing API in the browser wouldn't seem to apply directly to a node situation, and the fourth, the inaccuracy of Javscript time, cites an article from 2008, and I would strongly caution against relying on older material regarding Javascript performance specifics, particularly given the recent round of performance improvements all the engines have made to support "HTML5" apps.</p> <p>However, in answer to your question, you should look at <a href="https://nodejs.org/api/process.html#process_process_hrtime_time" rel="noreferrer"><code>process.hrtime()</code></a></p> <p>UPDATE: The <a href="https://github.com/dbkaplun/present" rel="noreferrer"><code>present</code></a> package (available via <code>npm install present</code>) provides some sugar around <code>hrtime</code> if you'd like it.</p> <p><strong><em>Note:</em></strong> Since the <strong>version 8.5.0 of Node</strong>, you can use <a href="https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_now" rel="noreferrer">performance.now()</a></p>
19,525,160
How to conditionally buffer RACSignal values?
<p>I'm working on some code that interacts with a remote API via websockets. My data layer is responsible for establishing and monitoring the websocket connection. It also contains methods that can be used by the application to enqueue websocket messages to be sent. The application code should not be responsible for inspecting the state of the websocket connection, aka fire-and-forget.</p> <p>Ideally, I'd like to data layer to function as follows:</p> <ul> <li>When the data layer does not have a connection to the websocket endpoint (<code>self.isConnected == NO</code>), messages are buffered internally.</li> <li>When a connection is becomes available (<code>self.isConnected == YES</code>), buffered messages are immediately sent, and any subsequent messages are sent immediately.</li> </ul> <p>Here's what I've been able to come up with:</p> <pre><code>#import "RACSignal+Buffering.h" @implementation RACSignal (Buffering) - (RACSignal*)bufferWithSignal:(RACSignal*)shouldBuffer { return [RACSignal createSignal:^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) { RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable]; NSMutableArray* bufferedValues = [[NSMutableArray alloc] init]; __block BOOL buffering = NO; void (^bufferHandler)() = ^{ if (!buffering) { for (id val in bufferedValues) { [subscriber sendNext:val]; } [bufferedValues removeAllObjects]; } }; RACDisposable* bufferDisposable = [shouldBuffer subscribeNext:^(NSNumber* shouldBuffer) { buffering = shouldBuffer.boolValue; bufferHandler(); }]; if (bufferDisposable) { [disposable addDisposable:bufferDisposable]; } RACDisposable* valueDisposable = [self subscribeNext:^(id x) { [bufferedValues addObject:x]; bufferHandler(); } error:^(NSError *error) { [subscriber sendError:error]; } completed:^{ [subscriber sendCompleted]; }]; if (valueDisposable) { [disposable addDisposable:valueDisposable]; } return disposable; }]; } @end </code></pre> <p>Lastly, this is pseudo-code for how it would be used:</p> <pre><code>@interface APIManager () @property (nonatomic) RACSubject* requests; @end @implementation WebsocketDataLayer - (id)init { self = [super init]; if (self) { RACSignal* connectedSignal = RACObserve(self, connected); self.requests = [[RACSubject alloc] init]; RACSignal* bufferedApiRequests = [self.requests bufferWithSignal:connectedSignal]; [self rac_liftSelector:@selector(sendRequest:) withSignalsFromArray:@[bufferedApiRequests]]; } return self; } - (void)enqueueRequest:(NSString*)request { [self.requests sendNext:request]; } - (void)sendRequest:(NSString*)request { DebugLog(@"Making websocket request: %@", request); } @end </code></pre> <p>My question is: Is this the right approach for buffering values? Is there a more idiomatic RAC way of handling this?</p>
19,552,152
2
0
null
2013-10-22 18:04:12.59 UTC
12
2013-10-23 21:06:16.47 UTC
2013-10-22 18:09:19.54 UTC
null
2,908,238
null
2,908,238
null
1
10
ios|objective-c|reactive-programming|reactive-cocoa
1,746
<p>Buffering can be thought of as something that applies to <em>individual</em> requests, which leads to a natural implementation using <code>-flattenMap:</code> and <code>RACObserve</code>:</p> <pre><code>@weakify(self); RACSignal *bufferedRequests = [self.requests flattenMap:^(NSString *request) { @strongify(self); // Waits for self.connected to be YES, or checks that it already is, // then forwards the request. return [[[[RACObserve(self, connected) ignore:@NO] take:1] // Replace the property value with our request. mapReplace:request]; }]; </code></pre> <p>If ordering is important, you can replace <code>-flattenMap:</code> with <code>-map:</code> plus <code>-concat</code>. These implementations avoid the need for any custom operators, and work without manual subscriptions (which are notoriously messy).</p>
1,588,581
Oracle - Number to varchar
<p>I have a table containing a column of type Number</p> <pre><code>create table tmp ( /*other fields*/ some_field Number ) </code></pre> <p>and in a PL SQL script, I want to convert that field to a varchar. However, i don't know its length, so I get an exception</p> <blockquote> <p>Exception message is ORA-06502: PL/SQL: numeric or value error: character string buffer too small</p> </blockquote> <pre><code>v_some_field varchar(21); /*...*/ v_some_field := TO_CHAR(some_field,'999999999999999999999'); </code></pre> <p>How should i declare the v_some_field buffer? Setting it to varchar(32767) seems quite brute, is there any alternative?</p>
1,588,629
2
0
null
2009-10-19 13:07:15.94 UTC
null
2009-10-20 10:19:52.08 UTC
null
null
null
null
63,309
null
1
2
oracle|plsql|to-char
68,241
<p>you're getting an error not because the number is too large but because the result of your <code>to_char</code> is 22 characters long (21x"9"+one character for the sign):</p> <pre><code>SQL&gt; DECLARE 2 some_field NUMBER := 123; 3 v_some_field VARCHAR(21); 4 BEGIN 5 v_some_field := TO_CHAR(some_field, '999999999999999999999'); 6 END; 7 / ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at line 6 SQL&gt; DECLARE 2 some_field NUMBER := 123; 3 v_some_field VARCHAR(22); 4 BEGIN 5 v_some_field := TO_CHAR(some_field, '999999999999999999999'); 6 END; 7 / PL/SQL procedure successfully completed </code></pre>
34,377,012
How to verify which resources each user can access with OAuth and OpenID Connect?
<p>Suppose we have some RESTful API whose resources we want to expose. End users will work with this API through client applications like mobile apps and Javascript based clients that run on web browsers. </p> <p>With OAuth 2.0 this RESTful API will lie on the Resource Server and we will have one Authorization Server on which the client applications are registered. The users will then be registered at the authorization server and will be able to grant permission to those applications access resources on their behalf or not.</p> <p>So when the user access one client application he will be redirected to the Authorization Server and be prompted to grant permissions to said client app. After that an access token is issued and the client is able to make requests to the Resource Server.</p> <p>All of this is quite clear to me. There's just one missing piece: the protection of each resource might be user-dependent. To be more precise it might be claims-dependent. What I mean by that is we can have the following situation:</p> <ul> <li><p>The resource <a href="http://resourceserver.com/api/first-resource" rel="noreferrer">http://resourceserver.com/api/first-resource</a> should only be accessible to users with claim "ExampleClaim" with value 123.</p></li> <li><p>The resource <a href="http://resourceserver.com/api/second-resource" rel="noreferrer">http://resourceserver.com/api/second-resource</a> should only be accessible to users with claim "AnotherClaim" with value 123.</p></li> <li><p>The resource <a href="http://resourceserver.com/api/third-resource" rel="noreferrer">http://resourceserver.com/api/third-resource</a> should be accessible to any users.</p></li> </ul> <p>When I first heard of OAuth was dealing with ASP.NET WebAPI and I dealt with that in the following way: when the request was sent with the <code>Authorization: Bearer [token]</code> header, on server side the thread principal was set and I thought that this meant the user was authenticated with the API. So I used <code>[Authorize]</code> attributes in order to verify if the user could access the resource.</p> <p>After studying OAuth more deeply I saw this was a terrible misuse of the protocol. As I've learned, OAuth authorizes applications and not users. When the request is made with the Authorization header, as I've learned, the access token shouldn't contain information about the user, just about the application being allowed to make the request.</p> <p>Considering that, sending the Authorization header with the request doesn't identify the user and does don't say if the user can or cannot access said resource.</p> <p>In that case, how does one perform this kind of authorization? I mean, not authorization of the client app performing the request, but the authorization of the user accessing the resource based on his claims? I believe this is where OpenID Connect and it's ID tokens come in, but I'm unsure. How does one manage this?</p>
34,378,565
2
0
null
2015-12-20 01:00:58.727 UTC
12
2021-10-12 16:28:33.627 UTC
2018-07-18 00:53:34.073 UTC
null
1,620,696
null
1,620,696
null
1
25
api|rest|asp.net-web-api|oauth|authorization
6,859
<p>An access token does not contain a user's claims, but it contains the <strong>subject</strong> of the user who has granted permissions to the client application. &quot;Subject&quot; is a technical term and it means a unique identifier. Simply saying, &quot;subject&quot; is a user ID in your database.</p> <p>At a protected resource endpoint, you will do:</p> <ol> <li>Extract an access token from the request. (<a href="https://www.rfc-editor.org/rfc/rfc6750" rel="nofollow noreferrer">RFC 6750</a>)</li> <li>Get detailed information about the access token from the authorization server. (<a href="https://www.rfc-editor.org/rfc/rfc7662" rel="nofollow noreferrer">RFC 7662</a>)</li> <li>Validate the access token. The validation includes (a) whether the access token has expired or not, and (b) whether the access token covers scopes (permissions) that are required by the protected resource endpoint.</li> </ol> <p>The steps above from 1 to 3 are an access control against <em>client applications</em>. OAuth 2.0 (<a href="https://www.rfc-editor.org/rfc/rfc6749" rel="nofollow noreferrer">RFC 6749</a>) is for this. See &quot;<a href="https://www.authlete.com/documents/definitive_guide/protected_resource" rel="nofollow noreferrer">Protected Resource</a>&quot; by <a href="https://www.authlete.com/" rel="nofollow noreferrer">Authlete</a> (by me) for details about these steps.</p> <p>After the steps above, then you will do:</p> <ol start="4"> <li>Extract the subject from the access token. Again, &quot;subject&quot; is a unique identifier of the user.</li> <li>Retrieve claims of the user from your database.</li> <li>Validate the claims as you like.</li> </ol> <p>The steps above from 4 to 6 are an access control against <em>users</em>. OAuth 2.0 is NOT for this.</p> <p>The primary purpose of <a href="http://openid.net/connect/" rel="nofollow noreferrer">OpenID Connect</a> is to get an <a href="http://openid.net/specs/openid-connect-core-1_0.html#IDToken" rel="nofollow noreferrer">ID token</a> in a verifiable manner. You can confirm that an ID token has been issued by the right party by verifying the signature attached to the ID token. See JSON Web Signature (JWS) (<a href="https://www.rfc-editor.org/rfc/rfc7515" rel="nofollow noreferrer">RFC 7515</a>) for details about signature.</p> <p>An ID token itself is not a technology to protect Web APIs. But you may be able to use it for that purpose if you use <code>at_hash</code> claim in an ID token properly (see &quot;<a href="http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken" rel="nofollow noreferrer">3.1.3.6. ID Token</a>&quot; in <a href="http://openid.net/specs/openid-connect-core-1_0.html" rel="nofollow noreferrer">OpenID Connect Core 1.0</a>). However, at a protected resource endpoint, it will be much easier to get claims directly from your database than to parse an ID token.</p> <hr/> <sup>**[ Additional answer #1 for the comment ]**</sup> <p>In your use case, you don't need ID tokens. It's because an access token already contains information about the subject of the user. In normal cases, the information is equivalent to the value of <code>sub</code> claim in an ID token.</p> <p><img src="https://i.stack.imgur.com/TlozG.png" alt="Flow diagram explaining access tokens vs ID tokens" /></p> <p>Therefore, you don't need an ID token to get the subject of the user. See the description of step 4, and you can find &quot;extract the subject from the <strong>access token</strong>.&quot;</p> <hr/> <sup>**[ Additional answer #2 for the comment ]**</sup> <blockquote> <p>So is there anything wrong in extracting the subject from the access token like that and verify the claims? Or this is the right way of doing things?</p> </blockquote> <p>There is nothing wrong. For example, suppose you define a Web API, <code>https://api.example.com/profile</code>, which returns the profile information of a user. In normal cases, such an API would accept an access token and then extract the subject from the access token to determine which user to refer to. On the other hand, if the API did not extract the subject from the access token, it would have to require &quot;subject&quot; as a request parameter to determine which user to refer to (or require an ID token that contains &quot;sub&quot; claim). Even in such a case, the API must check whether the subject specified by the request parameter and the subject associated with the access token are identical because otherwise, it would become a security issue.</p> <p>Checking claims after extracting the subject is also a normal step. For example, you may want to restrict the functionalities of your service based on the plan that the user has paid for (Free plan, Lite plan, Enterprise plan, or whatever). In this case, you would have to refer to <code>plan</code> claim. Of course, checking such a claim can be done only after extracting the subject from the access token.</p> <p>Therefore, (1) extracting the subject from an access token and then (2) verifying the claims of the user are normal and even typical steps in implementations of protected resource endpoints.</p>
17,806,977
Comparison between RabbitMQ and MSMQ
<p>Can I get the comparison between RabbitMQ and MSMQ. It will be helpful performance information on different factors are available.</p>
17,811,687
1
0
null
2013-07-23 09:57:58.923 UTC
13
2013-07-23 13:31:55.32 UTC
null
null
null
null
2,264,512
null
1
68
performance|rabbitmq|msmq|message-queue
49,562
<p>I wrote a blog post a while back comparing MSMQ and RabbitMQ (among others):</p> <p><a href="http://mikehadlow.blogspot.co.uk/2011/04/message-queue-shootout.html">http://mikehadlow.blogspot.co.uk/2011/04/message-queue-shootout.html</a></p> <p>RabbitMQ gave slightly better performance than MSMQ, but both were comprehensively out performed by ZeroMQ. If performance is your main criteria, you should definitely look at ZeroMQ.</p> <p>It's worth noting that RabbitMQ and MSMQ are very different beasts. MSMQ is a simple store-and-forward queue. It doesn't provide any messaging patterns, such as pub/sub, or routing. For anything beyond simple point-to-point messaging you'd probably want to use a service bus library such as NServiceBus or MassTransit on top of MSMQ.</p> <p>RabbitMQ is a sophisticated server product that provides complex messaging patterns, topics and routing out-of-the-box. You also get centralized management and DR, something you'd have to implement yourself if you chose MSMQ.</p>
35,376,387
Extract int from string in Pandas
<p>Lets say I have a dataframe <code>df</code> as </p> <pre><code>A B 1 V2 3 W42 1 S03 2 T02 3 U71 </code></pre> <p>I want to have a new column (either at it the end of <code>df</code> or replace column <code>B</code> with it, as it doesn't matter) that only extracts the int from the column <code>B</code>. That is I want column <code>C</code> to look like</p> <pre><code>C 2 42 3 2 71 </code></pre> <p>So if there is a 0 in front of the number, such as for 03, then I want to return 3 not 03</p> <p>How can I do this?</p>
35,376,466
8
0
null
2016-02-13 05:16:57.59 UTC
30
2022-06-02 22:33:11.553 UTC
2018-10-03 00:11:42.893 UTC
null
832,230
null
5,739,619
null
1
34
python|pandas|dataframe
68,351
<p>You can convert to string and extract the integer using regular expressions.</p> <pre><code>df['B'].str.extract('(\d+)').astype(int) </code></pre>
25,807,835
Old SQL History in Oracle SQL Developer
<p>In SQL Developer, i was finding some SQL commands of previous month but not able to find that as it is showing only the records of last 4-5 days.</p> <p>Is there any way to find the old SQL commands those are not displaying under SQL history tab.</p> <p>Thanks.</p>
25,810,019
5
0
null
2014-09-12 11:59:14.613 UTC
2
2020-02-05 11:48:35.757 UTC
null
null
null
null
3,035,077
null
1
21
oracle|oracle-sqldeveloper
89,565
<p>As Oracle has documented, there is a SQL history folder and it is larger (has more SQL queries that go back about a year) than the SQL History tool bar (a couple of months).</p> <p>Here is the content of my SQL History tool bar:</p> <p><img src="https://i.stack.imgur.com/KsIo2.jpg" alt="SQL History tool bar"></p> <p>With respect to the SQL history folder, release notes cite this location in Windows 7:</p> <p>C:\Users\your_user_name\AppData\Roaming\SQL Developer\SqlHistory</p> <p>While this folder contains SQL History, it also contains: User-defined reports and user-defined snippets files (e.g. see <a href="http://www.oracle.com/technetwork/developer-tools/sql-developer/sqldev31-ea-relnotes-487612.html" title="3.1 Release notes">3.1 Sql Developer release notes</a>) Here is my SQL History folder:</p> <p><img src="https://i.stack.imgur.com/Z8ZYT.jpg" alt="My SQL History folder"></p> <p>I do not see any documentation to adjust the size of either.</p>
8,385,317
Load a mathematica package from within a package
<p>I have more or less the following setting. In <code>~/path/to/my/packages</code> I have two packages <code>package1.m</code> and <code>package2.m</code>. Each package's outline is, for example, the following:</p> <pre><code>BeginPackage["package1`"] Unprotect@@Names["package1`*"]; ClearAll@@Names["package1`*"]; Begin["`Private`"] vecNorm[vec_?VectorQ]:=Module[{},Return[Sqrt[vec.vec]]]; End[] Protect@@Names["package1`*"]; EndPackage[] </code></pre> <p>Now, my problem is that I want to use <code>vecNorm</code> defined in <code>package1.m</code> in <code>package2.m</code>. How can I load (safely) <code>package1</code> from within <code>package2</code>?</p> <p>At the moment, I load manually both packages as follows:</p> <pre><code>SetDirectory[StringJoin[NotebookDirectory[], "packages"]]; Needs["package1`"] Needs["package2`"] </code></pre> <p>from a notebook saved in <code>~/path/to/my</code>. I want to load manually <em>only</em> <code>package2</code> which in turn will load automatically and safely <code>package1</code>. In general I want a solution which changes as little as possible paths etc. of mathematica. What should be the best practice to accomplish this?</p> <p><em>PS</em>: By safely I mean that in the future, when I'll define <code>package3</code> which will be using <code>vecNorm</code> as well and will be loading <code>package1</code> as well no conflicts will happen.</p>
8,385,424
1
0
null
2011-12-05 12:29:52.113 UTC
12
2020-12-24 18:12:27.587 UTC
null
null
null
null
671,013
null
1
13
wolfram-mathematica|mathematical-packages
2,631
<p>There are two generally recommended ways to load a package. One is so-called public import, and in your setting it will be done as</p> <pre><code>BeginPackage["package2`",{"package1`"}] (* Usage messages etc *) Begin["`Private`"] (* code here *) End[] EndPackage[] </code></pre> <p>Here, you indicate the context name of the package you want to load, in the list which is a second optional argument to <code>BeginPackage</code>. This way of importing is called public because the loaded package will remain on the <code>$ContextPath</code> after your main package is loaded, and will thus be publicly available.</p> <p>The second method is called private import, and is schematically done as</p> <pre><code>BeginPackage["package2`"] (* Usage messages etc *) Begin["`Private`"] Needs["package1`"] (* code here *) End[] EndPackage[] </code></pre> <p>In this method, your loaded second package will only be available to the package that loads it (with <code>Needs</code>), thus private import. </p> <p>Which way you need will depend on the situation. I try to make all my imports private unless I have to make them public. For debugging, however, it may be handy to first make a public import, since then you can play with the second package directly at the top-level.</p> <p>As for the safety, you can load a package by any number of packages, and this will be safe. When you load several packages into the same context simultaneously, this will be safe as long as those packages don't have public symbols with the same short name. Otherwise, you will run into what is called a shadowing problem, but it is best to make the effort needed to avoid that (it is always possible).</p>
8,515,453
Can phonegap just display my mobile website in an embedded browser?
<p>I have a website built in django, its responsive so works from 320px to 960px.</p> <p>I've noticed when i tell people the first thing they do is go to their native app-stores and search for the "site" when that fails they then go for good old google...</p> <p>So i want to build native versions of the site but there will be no extra functionality.. they are just like convenient "bookmarks" which exist inside app-stores and on the mobile desktops of users instead of the WWW.</p> <p>Given i don't want any extra native functionality can I just use phonegap and embed my whole site in a browser window?</p> <p>I'd much rather do that than start from scratch, convert the site to an API and built templates/assets into phonegap.</p> <p>Cheers,</p> <p>Asim.</p>
8,518,993
4
0
null
2011-12-15 05:17:13.287 UTC
12
2014-06-14 14:23:19.123 UTC
null
null
null
null
134,085
null
1
22
cordova
23,404
<p>This depends: Apple won't let you upload an app where the UI has to be loaded from a remote server.</p> <p>So for the app store you need to have some presentation logic on the client.</p> <p>In general: If you don't use a local html file you won't be able to use phonegap functionality (like the camera), but your "app" should run fine if you whitelist your server. But this app won`t be a first class citizen because you always have to online and you will feel a slow connection in the responsiveness of your "app".</p>
8,893,572
Fetching one row only with MySQLi
<p>How can I only fetch one INDEXED row with MySQLi? I'm currently doing this:</p> <pre><code>$row = $result-&gt;fetch(MYSQLI_ASSOC); $row = $row[0]; </code></pre> <p>Is there another way?</p> <p>I'm aware of mysqli_fetch_row but it doesn't return an associative array.</p>
8,893,607
1
0
null
2012-01-17 11:08:03.94 UTC
7
2018-04-12 13:34:43.02 UTC
null
null
null
null
816,137
null
1
28
php|mysqli
62,144
<p>Use <code>$row = $result-&gt;fetch_assoc();</code> - it's the same as <code>fetch_row()</code> but returns an associative array.</p>
55,205,472
Is nesting React Context Provider and consuming those with useContext a problem?
<p>What problem can I encounter with a deep nested React context provider?</p> <pre class="lang-js prettyprint-override"><code>const AllContextProvider = props =&gt; { return ( &lt;UserProvider&gt; &lt;ThemeProvider&gt; &lt;NotifProvider&gt; &lt;TimelineProvider&gt; &lt;CertProvider&gt; &lt;MenusProvider&gt; {props.children} &lt;/MenusProvider&gt; &lt;/CertProvider&gt; &lt;/TimelineProvider&gt; &lt;/NotifProvider&gt; &lt;/ThemeProvider&gt; &lt;/UserProvider&gt; ); }; </code></pre> <p>And consuming those nested providers with a Context dependencie like this :</p> <pre class="lang-js prettyprint-override"><code>import React, { useContext } from "react"; import { UserContext } from "./UserContext"; import { useLocalStoragePerUser } from "./useLocalStoragePerUser"; const MenusContext = React.createContext(); const { Provider } = MenusContext; const MenusProvider = props =&gt; { // Is this context dependencie always "re-trigger" the Menu Context Provider? const { user } = useContext(UserContext); // Menus Context const [menu, setMenu] = useLocalStoragePerUser( "menus", { icons: false, labels: true, leftMenu: true, }, user ); return ( &lt;Provider value={{ menu, setMenu}} &gt; {props.children} &lt;/Provider&gt; ); }; export { MenusProvider, MenusContext }; </code></pre> <p>Is this context dependencie always "re-trigger" the Menu Context Provider? => especially concerning useless re-renders?</p>
55,205,936
1
0
null
2019-03-17 09:07:00.553 UTC
6
2019-03-17 10:10:28.47 UTC
null
null
null
null
11,171,246
null
1
29
reactjs|react-hooks
18,408
<p>Having nested Contexts will not cause any issues in your code. In the above case if you subscribe to <code>UserContext</code> in <code>MenuContext</code>, the <code>MenuContext</code> will only re-render when the <code>UserContext</code> has changed the value supplied to its provider. However unless the MenuContext changes the value it passes to the <code>MenuContext Provider</code> its children who are subscribing to <code>MenuContext</code> will not re-render and also no other children will be re-rendered</p> <pre><code>import React from "react"; import ReactDOM from "react-dom"; import { UserProvider } from "./UserProvider"; import { ThemeProvider } from "./ThemeProvider"; import { MenusProvider } from "./MenuProvider"; import "./styles.css"; function Child() { console.log("Child render"); return &lt;div&gt;Menus Child&lt;/div&gt;; } function App() { return ( &lt;div className="App"&gt; &lt;h1&gt;Hello CodeSandbox&lt;/h1&gt; &lt;h2&gt;Start editing to see some magic happen!&lt;/h2&gt; &lt;UserProvider&gt; &lt;ThemeProvider&gt; &lt;MenusProvider&gt; &lt;Child /&gt; &lt;/MenusProvider&gt; &lt;/ThemeProvider&gt; &lt;/UserProvider&gt; &lt;/div&gt; ); } const rootElement = document.getElementById("root"); ReactDOM.render(&lt;App /&gt;, rootElement); </code></pre> <p>You can see a <strong><a href="https://codesandbox.io/s/93l66qjwzo" rel="noreferrer">DEMO in the codeSandbox here</a></strong></p> <blockquote> <p><strong>P.S.</strong> However you must make sure that you are not creating a new object while passing the value to a Provider otherwise everytime the Provider re-renders all children which subscribe to its context will re-render</p> </blockquote>
55,497,800
Populate IConfiguration for unit tests
<p>.NET Core configuration allows so many options to add values (environment variables, json files, command line args).</p> <p>I just can't figure out and find an answer how to populate it via code.</p> <p>I am writing unit tests for extension methods to configurations and I thought populating it in the unit tests via code would be easier than loading dedicated json files for each test.</p> <p>My current code:</p> <pre class="lang-cs prettyprint-override"><code>[Fact] public void Test_IsConfigured_Positive() { // test against this configuration IConfiguration config = new ConfigurationBuilder() // how to populate it via code .Build(); // the extension method to test Assert.True(config.IsConfigured()); } </code></pre> <p>Update:</p> <p>One special case is the &quot;empty section&quot; which would look like this in json.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;MySection&quot;: { // the existence of the section activates something triggering IsConfigured to be true but does not overwrite any default value } } </code></pre> <hr /> <p>Update 2:</p> <p>As Matthew pointed out in the comments having an empty section in the json gives the same result as not having the section at all. I distilled an example and yes, that is the case. I was wrong expecting a different behaviour.</p> <p>So what do I do and what did I expect:</p> <p>I am writing unit tests for 2 extension methods for IConfiguration (actually because the binding of values in Get...Settings method does not work for some reason (but thats a different topic). They look like this:</p> <pre class="lang-cs prettyprint-override"><code>public static bool IsService1Configured(this IConfiguration configuration) { return configuration.GetSection(&quot;Service1&quot;).Exists(); } public static MyService1Settings GetService1Settings(this IConfiguration configuration) { if (!configuration.IsService1Configured()) return null; MyService1Settings settings = new MyService1Settings(); configuration.Bind(&quot;Service1&quot;, settings); return settings; } </code></pre> <p>My missunderstanding was that if I place an empty section in the appsettings the <code>IsService1Configured()</code> method would return <code>true</code> (which is obviously wrong now). The difference I expected is with having an empty section now the <code>GetService1Settings()</code> method returns <code>null</code> and not as I expected the <code>MyService1Settings</code> with all default values.</p> <p>Fortunately this still works for me since I won't have empty sections (or now know that I have to avoid those cases). It was just one theoretical case I came across while writing the unit tests.</p> <p>Further down the road (for those interested in).</p> <p>For what do I use it? Configuration based service activation/deactivation.</p> <p>I have an application which has a service / some services compiled into it. Depending on the deployment I need to activate/deactivate the services completly. This is because some (local or testings setups) do not have full access to a complete infrastructure (helper services like caching, metrics...). And I do that via the appsettings. If the service is configured (the config section exists) it will be added. If the config section is not present it will not be used.</p> <hr /> <p>The full code for the distilled example is below.</p> <ul> <li>in Visual Studio create a new API named WebApplication1 from the templates (without HTTPS and Authentication)</li> <li>delete the Startup class and appsettings.Development.json</li> <li>replace the code in Program.cs with the code below</li> <li>now in appsettings.json you can activate/deactivate the services by adding/removing <code>Service1</code> and <code>Service2</code> section</li> </ul> <pre class="lang-cs prettyprint-override"><code>using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; namespace WebApplication1 { public class MyService1Settings { public int? Value1 { get; set; } public int Value2 { get; set; } public int Value3 { get; set; } = -1; } public static class Service1Extensions { public static bool IsService1Configured(this IConfiguration configuration) { return configuration.GetSection(&quot;Service1&quot;).Exists(); } public static MyService1Settings GetService1Settings(this IConfiguration configuration) { if (!configuration.IsService1Configured()) return null; MyService1Settings settings = new MyService1Settings(); configuration.Bind(&quot;Service1&quot;, settings); return settings; } public static IServiceCollection AddService1(this IServiceCollection services, IConfiguration configuration, ILogger logger) { MyService1Settings settings = configuration.GetService1Settings(); if (settings == null) throw new Exception(&quot;loaded MyService1Settings are null (did you forget to check IsConfigured in Startup.ConfigureServices?) &quot;); logger.LogAsJson(settings, &quot;MyServiceSettings1: &quot;); // do what ever needs to be done return services; } public static IApplicationBuilder UseService1(this IApplicationBuilder app, IConfiguration configuration, ILogger logger) { // do what ever needs to be done return app; } } public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) =&gt; WebHost.CreateDefaultBuilder(args) .ConfigureLogging ( builder =&gt; { builder.AddDebug(); builder.AddConsole(); } ) .UseStartup&lt;Startup&gt;(); } public class Startup { public IConfiguration Configuration { get; } public ILogger&lt;Startup&gt; Logger { get; } public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; Logger = loggerFactory.CreateLogger&lt;Startup&gt;(); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // flavour 1: needs check(s) in Startup method(s) or will raise an exception if (Configuration.IsService1Configured()) { Logger.LogInformation(&quot;service 1 is activated and added&quot;); services.AddService1(Configuration, Logger); } else Logger.LogInformation(&quot;service 1 is deactivated and not added&quot;); // flavour 2: checks are done in the extension methods and no Startup cluttering services.AddOptionalService2(Configuration, Logger); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); // flavour 1: needs check(s) in Startup method(s) or will raise an exception if (Configuration.IsService1Configured()) { Logger.LogInformation(&quot;service 1 is activated and used&quot;); app.UseService1(Configuration, Logger); } else Logger.LogInformation(&quot;service 1 is deactivated and not used&quot;); // flavour 2: checks are done in the extension methods and no Startup cluttering app.UseOptionalService2(Configuration, Logger); app.UseMvc(); } } public class MyService2Settings { public int? Value1 { get; set; } public int Value2 { get; set; } public int Value3 { get; set; } = -1; } public static class Service2Extensions { public static bool IsService2Configured(this IConfiguration configuration) { return configuration.GetSection(&quot;Service2&quot;).Exists(); } public static MyService2Settings GetService2Settings(this IConfiguration configuration) { if (!configuration.IsService2Configured()) return null; MyService2Settings settings = new MyService2Settings(); configuration.Bind(&quot;Service2&quot;, settings); return settings; } public static IServiceCollection AddOptionalService2(this IServiceCollection services, IConfiguration configuration, ILogger logger) { if (!configuration.IsService2Configured()) { logger.LogInformation(&quot;service 2 is deactivated and not added&quot;); return services; } logger.LogInformation(&quot;service 2 is activated and added&quot;); MyService2Settings settings = configuration.GetService2Settings(); if (settings == null) throw new Exception(&quot;some settings loading bug occured&quot;); logger.LogAsJson(settings, &quot;MyService2Settings: &quot;); // do what ever needs to be done return services; } public static IApplicationBuilder UseOptionalService2(this IApplicationBuilder app, IConfiguration configuration, ILogger logger) { if (!configuration.IsService2Configured()) { logger.LogInformation(&quot;service 2 is deactivated and not used&quot;); return app; } logger.LogInformation(&quot;service 2 is activated and used&quot;); // do what ever needs to be done return app; } } public static class LoggerExtensions { public static void LogAsJson(this ILogger logger, object obj, string prefix = null) { logger.LogInformation(prefix ?? string.Empty) + ((obj == null) ? &quot;null&quot; : JsonConvert.SerializeObject(obj, Formatting.Indented))); } } } </code></pre>
55,497,919
7
0
null
2019-04-03 14:37:59.423 UTC
13
2022-07-07 07:37:21.32 UTC
2021-04-23 04:45:43.397 UTC
null
1,402,846
null
639,019
null
1
80
asp.net-core|.net-core|xunit|asp.net-core-2.2|.net-core-2.2
47,081
<p>You can use <code>MemoryConfigurationBuilderExtensions</code> to provide it via a dictionary.</p> <pre class="lang-cs prettyprint-override"><code>using Microsoft.Extensions.Configuration; var myConfiguration = new Dictionary&lt;string, string&gt; { {&quot;Key1&quot;, &quot;Value1&quot;}, {&quot;Nested:Key1&quot;, &quot;NestedValue1&quot;}, {&quot;Nested:Key2&quot;, &quot;NestedValue2&quot;} }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(myConfiguration) .Build(); </code></pre> <p>The equivalent JSON would be:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;Key1&quot;: &quot;Value1&quot;, &quot;Nested&quot;: { &quot;Key1&quot;: &quot;NestedValue1&quot;, &quot;Key2&quot;: &quot;NestedValue2&quot; } } </code></pre> <p>The equivalent Environment Variables would be (assuming no prefix / case insensitive):</p> <pre><code>Key1=Value1 Nested__Key1=NestedValue1 Nested__Key2=NestedValue2 </code></pre> <p>The equivalent Command Line parameters would be:</p> <pre><code>dotnet myapp.dll \ -- \ --Key1=Value1 \ --Nested:Key1=NestedValue1 \ --Nested:Key2=NestedValue2 </code></pre>
30,533,372
Run an Ansible task only when the hostname contains a string
<p>I have multiple tasks in a role as follows. I do not want to create another <code>yml</code> file to handle this task. I already have an include for the web servers, but a couple of our Perl servers require some web packages to be installed.</p> <pre><code>- name: Install Perl Modules command: &lt;command&gt; with_dict: perl_modules - name: Install PHP Modules command: &lt;command&gt; with_dict: php_modules when: &lt;Install php modules only if hostname contains the word "batch"&gt; </code></pre> <p>Host inventory file</p> <pre><code>[webs] web01 web02 web03 [perl] perl01 perl02 perl03 perl-batch01 perl-batch02 </code></pre>
30,534,171
2
0
null
2015-05-29 15:23:38.77 UTC
6
2018-06-28 17:25:32.92 UTC
null
null
null
null
166,836
null
1
31
ansible
94,847
<p>Below should do the trick:</p> <pre><code>- name: Install PHP Modules command: &lt;command&gt; with_dict: php_modules when: "'batch' in inventory_hostname" </code></pre> <p>Note you'll have a couple of skipped hosts during playbook run.</p> <p><code>inventory_hostname</code> is one of Ansible's "magic" variables:</p> <blockquote> <p>Additionally, inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file. This can be useful for when you don’t want to rely on the discovered hostname ansible_hostname or for other mysterious reasons. If you have a long FQDN, inventory_hostname_short also contains the part up to the first period, without the rest of the domain.</p> </blockquote> <p>Source: <a href="https://docs.ansible.com/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts">Ansible Docs - Magic variables and how to access information about other hosts</a></p>
576,892
Non-US tax from Appstore earnings?
<p>Does Apple "withhold a part of the earnings for tax purposes" even for non-US developers? I've seen <a href="https://stackoverflow.com/questions/124093/tax-on-iphone-developer-payments">this related question</a> but it's not clear what happens to non-US developers. There's a reference to a form "W-8BEN" but I don't understand it -- is this what I have to fill out when I'm non-US and I want to avoid Apple to withhold the tax?</p> <p>I know for instance earnings from <a href="http://www.dreamhost.com" rel="nofollow noreferrer">Dreamhost</a> referral reward programs are only taxed for US citizens -- it is explicitly stated that for non-US people the full reward is paid out and they must handle the tax issue themselves. It's this kind of explicit statement that I'm looking for regarding earnings from the app store.</p>
576,914
3
2
null
2009-02-23 08:29:05.3 UTC
9
2009-02-23 09:16:36.683 UTC
2017-05-23 12:25:02.703 UTC
Aron Rotteveel
-1
torbengb
20,571
null
1
12
iphone|app-store
8,691
<p>A W8BEN form allows a non-US company to declare that the US should not withhold taxes. A valid reason must be supplied. In ours we simple state the section of the NAFTA treaty that applies to cross border trade (part II, #10: "Article VII", "0%", for type of income "software license", reason "Corporation is a resident of Canada.")</p> <p>Never had a problem getting full payment once the form has been filed with the customer. </p> <p>Frankly it's a bit annoying but we've gotten used to it (and the form doesn't need to be customized, just recently dated).</p> <p>Basically all Apple is looking for is the paper work so they can check the "0% withholding tax" checkbox in their accounts payable system.</p>
543,049
Default XML namespace, JDOM, and XPath
<p>I want to use JDOM to read in an XML file, then use XPath to extract data from the JDOM Document. It creates the Document object fine, but when I use XPath to query the Document for a List of elements, I get nothing.</p> <p>My XML document has a default namespace defined in the root element. The funny thing is, when I remove the default namespace, it successfully runs the XPath query and returns the elements I want. What else must I do to get my XPath query to return results?</p> <p>XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;collection xmlns="http://www.foo.com"&gt; &lt;dvd id="A"&gt; &lt;title&gt;Lord of the Rings: The Fellowship of the Ring&lt;/title&gt; &lt;length&gt;178&lt;/length&gt; &lt;actor&gt;Ian Holm&lt;/actor&gt; &lt;actor&gt;Elijah Wood&lt;/actor&gt; &lt;actor&gt;Ian McKellen&lt;/actor&gt; &lt;/dvd&gt; &lt;dvd id="B"&gt; &lt;title&gt;The Matrix&lt;/title&gt; &lt;length&gt;136&lt;/length&gt; &lt;actor&gt;Keanu Reeves&lt;/actor&gt; &lt;actor&gt;Laurence Fishburne&lt;/actor&gt; &lt;/dvd&gt; &lt;/collection&gt; </code></pre> <p>Java:</p> <pre><code>public static void main(String args[]) throws Exception { SAXBuilder builder = new SAXBuilder(); Document d = builder.build("xpath.xml"); XPath xpath = XPath.newInstance("collection/dvd"); xpath.addNamespace(d.getRootElement().getNamespace()); System.out.println(xpath.selectNodes(d)); } </code></pre>
543,120
3
0
null
2009-02-12 20:17:41.953 UTC
13
2015-06-11 17:15:40.01 UTC
null
null
null
mangst
13,379
null
1
13
java|xml|xpath|jdom
16,849
<p><strong>XPath 1.0</strong> doesn't support the concept of a default namespace (<strong>XPath 2.0</strong> does). Any unprefixed tag is always assumed to be part of the no-name namespace. </p> <p>When using <strong>XPath 1.0</strong> you need something like this:</p> <pre><code>public static void main(String args[]) throws Exception { SAXBuilder builder = new SAXBuilder(); Document d = builder.build("xpath.xml"); XPath xpath = XPath.newInstance("x:collection/x:dvd"); xpath.addNamespace("x", d.getRootElement().getNamespaceURI()); System.out.println(xpath.selectNodes(d)); } </code></pre>
675,349
Deserialize unknown type with protobuf-net
<p>I have 2 networked apps that should send serialized protobuf-net messages to each other. I can serialize the objects and send them, however, <b>I cannot figure out how to deserialize the received bytes</b>.</p> <p>I tried to deserialize with this and it failed with a NullReferenceException.</p> <pre><code>// Where "ms" is a memorystream containing the serialized // byte array from the network. Messages.BaseMessage message = ProtoBuf.Serializer.Deserialize&lt;Messages.BaseMessage&gt;(ms); </code></pre> <p>I am passing a header before the serialized bytes that contains message type ID, which I can use in a giant switch statement to return the expected sublcass Type. With the block below, I receive the error: System.Reflection.TargetInvocationException ---> System.NullReferenceException.</p> <pre><code>//Where "ms" is a memorystream and "messageType" is a //Uint16. Type t = Messages.Helper.GetMessageType(messageType); System.Reflection.MethodInfo method = typeof(ProtoBuf.Serializer).GetMethod("Deserialize").MakeGenericMethod(t); message = method.Invoke(null, new object[] { ms }) as Messages.BaseMessage; </code></pre> <p>Here's the function I use to send a message over the network:</p> <pre><code>internal void Send(Messages.BaseMessage message){ using (System.IO.MemoryStream ms = new System.IO.MemoryStream()){ ProtoBuf.Serializer.Serialize(ms, message); byte[] messageTypeAndLength = new byte[4]; Buffer.BlockCopy(BitConverter.GetBytes(message.messageType), 0, messageTypeAndLength, 0, 2); Buffer.BlockCopy(BitConverter.GetBytes((UInt16)ms.Length), 0, messageTypeAndLength, 2, 2); this.networkStream.Write(messageTypeAndLength); this.networkStream.Write(ms.ToArray()); } } </code></pre> <p>This the class, with base class, I'm serializing:</p> <pre><code>[Serializable, ProtoContract, ProtoInclude(50, typeof(BeginRequest))] abstract internal class BaseMessage { [ProtoMember(1)] abstract public UInt16 messageType { get; } } [Serializable, ProtoContract] internal class BeginRequest : BaseMessage { [ProtoMember(1)] public override UInt16 messageType { get { return 1; } } } </code></pre> <p><hr> <b>Fixed</b> using Marc Gravell's suggestion. I removed the ProtoMember attribute from the readonly properties. Also switched to using SerializeWithLengthPrefix. Here's what I have now:</p> <pre><code>[Serializable, ProtoContract, ProtoInclude(50, typeof(BeginRequest))] abstract internal class BaseMessage { abstract public UInt16 messageType { get; } } [Serializable, ProtoContract] internal class BeginRequest : BaseMessage { public override UInt16 messageType { get { return 1; } } } </code></pre> <p>To receive an object:</p> <pre><code>//where "this.Ssl" is an SslStream. BaseMessage message = ProtoBuf.Serializer.DeserializeWithLengthPrefix&lt;BaseMessage&gt;( this.Ssl, ProtoBuf.PrefixStyle.Base128); </code></pre> <p>To send an object:</p> <pre><code>//where "this.Ssl" is an SslStream and "message" can be anything that // inherits from BaseMessage. ProtoBuf.Serializer.SerializeWithLengthPrefix&lt;BaseMessage&gt;( this.Ssl, message, ProtoBuf.PrefixStyle.Base128); </code></pre>
675,638
3
5
null
2009-03-23 21:40:58.39 UTC
11
2012-06-15 12:34:39.657 UTC
2009-03-24 15:36:32.33 UTC
Nick VanderPyle
62,054
Nick VanderPyle
62,054
null
1
23
c#|serialization|protocol-buffers|protobuf-net
22,891
<p>First; for network usage, there is <code>SerializeWithLengthPrefix</code> and <code>DeserializeWithLengthPrefix</code> which handle length for you (optionally with a tag). The <code>MakeGenericMethod</code> looks OK at first glance; and this actually ties in very closely to the pending commit of the work I've been doing to implement an RPC stack: the pending code <code>has an override of DeserializeWithLengthPrefix</code> that takes (essentially) a <code>Func&lt;int,Type&gt;</code>, to resolve a tag to a type to make it easier to deserialize unexpected data on the fly.</p> <p>If the message type actually relates to the inheritance between <code>BaseMessage</code> and <code>BeginRequest</code>, then you don't need this; it always goes to the top-most contract type in the hierarchy and works its way down (due to some wire details).</p> <p>Also - I haven't had chance to test it, but the following might be upsetting it:</p> <pre><code>[ProtoMember(1)] public override UInt16 messageType { get { return 1; } } </code></pre> <p>It is marked for serialization, but has no mechanism for setting the value. Maybe this is the issue? Try removing the <code>[ProtoMember]</code> here, since I don't this is useful - it is (as far as serialization is concerned), largely a duplicate of the <code>[ProtoInclude(...)]</code> marker.</p>
22,007,641
How to check if a variable has a value in a SQL Server 2008 stored procedure
<p>I need to check whether a variable has a value or not. </p> <pre><code>declare @name varchar(20) set @name = (SELECT Product_Name FROM tb_new_product_Name_id WHERE Product_Name = @productName) if (@name ) // here I need to check it </code></pre> <p>How to do it? thanks</p>
22,007,742
6
0
null
2014-02-25 07:42:24.637 UTC
null
2017-04-24 17:29:24.387 UTC
2014-02-25 08:58:31.383 UTC
null
13,302
null
3,170,098
null
1
7
sql|sql-server
40,580
<p>Try this</p> <pre><code>if (@name is null or @value = '') //it will indicate whether it contains a value or not </code></pre>
22,174,310
Windows - Commit Size vs Virtual Size
<p>i would like to know the exact difference between <strong>Commit Size</strong> (visible in the <em>Task Manager</em>) and <strong>Virtual Size</strong> (visible in SysInternals' <em>Process Explorer</em>).</p> <p>The <em>Virtual Size</em> parameter in <em>Process Explorer</em> looks like a more accurate indicator of Total Virtual Memory usage by a process. However the <em>Commit Size</em> is always smaller than the <em>Virtual Size</em> and I guess it does not include all virtual memory in use by the process. I would like somebody to explain what is exactly included in these parameters.</p>
22,174,816
3
0
null
2014-03-04 14:13:00.003 UTC
16
2017-10-18 19:58:26.72 UTC
2017-10-18 19:58:26.72 UTC
null
971,141
null
2,046,805
null
1
37
windows|memory|virtual-memory
39,644
<p>Memory can be reserved, committed, first accessed, and be part of the working set. When memory is <em>reserved</em>, a portion of address space is set aside, nothing else happens.</p> <p>When memory is <em>committed</em>, the operating system guarantees that the corresponding pages <em>could</em> in principle exist either in physical RAM or on the page file. In other words, it counts toward its hard limit of total available pages on the system, and it <em>formally</em> creates pages. That is, it creates pages and pretends that they exist (when in reality they don't exist yet).</p> <p>When memory is <em>accessed</em> for the first time, the pages that <em>formally</em> exist are created so they <em>truly</em> exist. Either a zero page is supplied to the process, or data is read into a page from a mapping. The page is moved into the <em>working set</em> of the process (but will not necessarily remain in there forever).</p> <p>Every running process has a number of pages which are <em>factually and logically</em> in RAM, that is these pages exist, and they exist "officially", too. This is the process' working set.<br> Further, every running process has pages that are <em>factually</em> in RAM, but do not officially exist in RAM any more. They may be on what's called the "standby list" or part of the buffer cache, or something different. When these are accessed, the OS may simply move them into the working set again.<br> Lastly, every process has pages that are not in RAM at all (either on swap or they don't exist yet).</p> <p><strong>Virtual size</strong> comprises the size of all pages that the process has <em>reserved</em>.</p> <p><strong>Commit size</strong> only comprises pages that have been <em>committed</em>.</p> <p>That is, in layman terms, "virtual size" is pretty much your own problem, and only limited by the size of your address space, whereas "commit size" is everybody's problem since it consumes a global limited resource (RAM plus swap). It therefore <em>affects other processes</em>.</p>
6,369,062
How do I add elements dynamically to a view created with XML
<p>I'm trying to add dynamic content to a view that has been created with XML.</p> <p>I have a view "profile_list" that has a ScrollView that I like to add some elements to.</p> <p>Here is some code of what I'm trying to do.</p> <pre><code>// Find the ScrollView ScrollView sv = (ScrollView) this.findViewById(R.id.scrollView1); // Create a LinearLayout element LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); // Add text tv = new TextView(this); tv.setText("my text"); ll.addView(tv); // Add the LinearLayout element to the ScrollView sv.addView(ll); // Display the view setContentView(R.layout.profile_list); </code></pre> <p>The plan is to add a TableLayout and fill it dynamically and not just a dummy text but first I must get this to work.</p> <p>Any help is welcome.</p> <p>Kind Regards Olle</p> <h1>I found the solution! </h1> <p>Stupid me I had left a element in my ScrollView in my XML-file!</p> <p>Anyway her is a working example:</p> <pre><code>LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.profile_list, null); // Find the ScrollView ScrollView sv = (ScrollView) v.findViewById(R.id.scrollView1); // Create a LinearLayout element LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); // Add text TextView tv = new TextView(this); tv.setText("my text"); ll.addView(tv); // Add the LinearLayout element to the ScrollView sv.addView(ll); // Display the view setContentView(v); </code></pre> <p>And the XML-file to match</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;ScrollView android:id="@+id/scrollView1" android:clickable="true" android:layout_weight="1" android:layout_width="fill_parent" android:layout_marginBottom="50px" android:layout_height="fill_parent"&gt; &lt;/ScrollView&gt; &lt;/LinearLayout&gt; </code></pre> <p>Hope this will help someone. Thanks for all help!</p>
6,369,162
1
2
null
2011-06-16 08:28:39.227 UTC
5
2015-11-23 10:16:19.89 UTC
2013-01-17 15:52:59.39 UTC
null
492,624
null
792,356
null
1
29
android|android-layout
43,304
<p>The way that you are adding things to the view is basically right - you just get the container object by its ID and then add them.</p> <p>It looks like you are setting the content view to be the wrong view though. You should inflate the view, add the children and set it as the content view, or set the content view from a resource ID then do the manipulation. What you are doing is manipulating a view and then adding a different one. Try moving your setContentView(...) to the start of the block. </p>
28,717,016
HTML5 generating video from images
<p>i'm wondering, since HTML and with javascript are mesmerizing together, if there is a solution in HTML5 to generate a video-file from many images?</p> <p>For example, you're able to load a video into a canvas and make it appear as greyscaled video, by manipulating the canvas. However, I would like to know, if there is somewhat a method to generate a video-file out of that greyscaled version. Would make sense, if you want to send the video via whatsapp etc.</p> <p>Thank you</p>
28,728,122
3
1
null
2015-02-25 10:48:50.383 UTC
10
2022-05-24 08:24:10.633 UTC
null
null
null
null
4,151,345
null
1
14
javascript|jquery|html|html5-canvas|html5-video
27,277
<p>There are currently no built-in API to do video encoding in HTML5. There are <a href="http://www.w3.org/2009/dap/#mediacapture" rel="noreferrer">work in progress</a> though, to allow basic video and audio recording - but it's not available at this time (audio recording is available in FireFox - it is also limited to <em>streams</em>).</p> <p>If you are OK with gif animation you can encode the frames as a gif using one of the encoders out there (see below).</p> <p>For video - there has been attempts, more or less successful, (the project I had in mind does not seem to be available anymore) but there has been issues from one browser to another.</p> <p>There is the option of building an encoder yourself low-level style, following video encoding and file format specifications. It's doable but it's not a small project.</p> <p>In any case, encoding video is a pretty performance hungry task even for native compiled applications. Running such a task in the browser will be a even more slow process and probably not practical for many users (and mobile devices will suck on those batteries).</p> <p>The better approach IMO (at the moment at least, until the aforementioned API becomes available), is to send images to server and have a server in the back handling encoding jobs, then send the result to client. This way you can use multi-threading, offload the client, use native compiled encoders such as ffmpeg, and the resulting video can be streamed back.</p> <p><strong>Some resources</strong></p> <ul> <li><a href="https://w3c.github.io/mediacapture-record/MediaRecorder.html" rel="noreferrer">MediaStream Recording API</a></li> <li><a href="https://jnordberg.github.io/gif.js/" rel="noreferrer">Gif encoder 1</a></li> <li><a href="https://github.com/twolfson/gif-encoder" rel="noreferrer">Gif encoder 2 (NodeJS)</a></li> <li><a href="http://hdfvr.com/html5-video-recording" rel="noreferrer">HTML5 Video recording information and status</a></li> <li><a href="http://blog.romanliutikov.com/post/76000554454/node-js-real-time-video-encoding" rel="noreferrer">Realtime video encoder (NodeJS/ffmpeg)</a></li> <li><a href="https://bitbucket.org/desmaj/libvpx.js/src" rel="noreferrer">libvpx (requires emscripten/asm.js)</a></li> </ul>
28,610,365
How can I add an event for a one time click to a function?
<p>I would like to add a click event listener to a function but would only like it to happen once. How could i do this?</p> <p>I would like to stay clear of JQuery as well if it is possible please.</p> <p>EDITED</p> <p>As the answers that I am getting for this are fully satisfying my need i thought i may make it a bit more clear with context.</p> <p>I am writing a function to draw a rectangle, first with one click on a button to initiate the rectangle function. Then there are two click event listeners in the drawRectangle function. These are the events i would like to happen only once in the function. Allowing the user to then create another rectangle if they click on the rectangle initiation button again.</p>
46,291,530
10
2
null
2015-02-19 15:35:28.737 UTC
12
2022-06-17 13:58:56.98 UTC
2021-02-27 22:26:40.35 UTC
null
4,300,537
null
4,300,537
null
1
31
javascript
51,528
<h1>Use modern JavaScript!</h1> <pre><code>EventTarget.addEventListener(&quot;click&quot;, function() { // Do something cool }, {once : true}); </code></pre> <blockquote> <p>A Boolean indicating that the listener should be invoked at most once after being added. If <code>true</code>, the listener would be automatically removed when invoked.</p> <p>- <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters" rel="noreferrer">MDN web docs</a></p> </blockquote> <p><a href="http://caniuse.com/#feat=once-event-listener" rel="noreferrer">All modern browsers</a> support this feature</p> <p><a href="https://developers.google.com/web/updates/2016/10/addeventlistener-once" rel="noreferrer">Other reference</a></p>
42,761,820
How to get another branch instead of default branch with go get
<p>I have 2 repositories. Let say them repo_a and repo_b. I imported repo_a in repo_b</p> <p>When I ran go get, it will get repo_a master branch. Is there any way to get develop branch using go get or another command from repo_b?</p> <p>I do not want to git pull on each specific package (in this case repo_a)</p>
55,302,537
3
1
null
2017-03-13 10:52:50.88 UTC
12
2021-07-31 16:29:42.183 UTC
null
null
null
null
3,528,220
null
1
58
git|github|go
71,678
<p>Starting with Go 1.11, this is possible when using <a href="https://github.com/golang/go/wiki/Modules" rel="noreferrer">Go modules</a>. When installing a dependency for a Go module, you can specify a <a href="https://tip.golang.org/cmd/go/#hdr-Module_queries" rel="noreferrer">module query</a> which may contain a branch or tag name:</p> <pre><code>$ go get &lt;path-to-repo&gt;@&lt;branch&gt; </code></pre>
5,765,654
TextField Validation With Regular Expression
<p>I need help with code that looks at a textfield make sure it starts with either a (+ or -) then has 3 integers after it. </p> <p>So valid data looks like +234 or -888</p> <p>So I have started this code but there are 2 problems with it </p> <ol> <li><p>It correctly validates that only 4 characters are entered. But for some reason you have to take focus off the textfield in order for the Done button on the keyboard to fire and hide the keyboard. If I only put less than 4 characters in the textfield then the Done button works fine. But I dont want the user to enter anything but 4 characters and then press Done and hide the keyboard. Thats the first problem....</p></li> <li><p>I am not familar with regular expressions and how to use them in iphone. So I need to add to this code regular expression for the above requirement.</p> <pre><code>-(BOOL)textField:(UITextField*)textFieldshouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; return !([newString length] &gt; 4); } //Done button to hide the keyboard -(IBAction)Done:(id)sender { } </code></pre></li> </ol>
5,784,131
4
0
null
2011-04-23 17:10:21.653 UTC
20
2014-08-07 05:37:47.11 UTC
2013-11-04 20:12:36.28 UTC
null
1,082,583
null
245,926
null
1
11
iphone|regex|cocoa-touch|ios4
20,703
<p>I am not sure how you'd like to handle user input and feedback. First I'll show a simple way to keep the user in the editing mode of the textField if her input is not valid.</p> <p><strong>First of all two delegate methods:</strong></p> <pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)aTextField { [aTextField resignFirstResponder]; return YES; } - (BOOL)textFieldShouldEndEditing:(UITextField *)aTextField { return [self validateInputWithString:aTextField.text]; } </code></pre> <p><strong>The testing method, which just returns YES or NO whether the input is valid or not:</strong></p> <pre><code>- (BOOL)validateInputWithString:(NSString *)aString { NSString * const regularExpression = @"^([+-]{1})([0-9]{3})$"; NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression options:NSRegularExpressionCaseInsensitive error:&amp;error]; if (error) { NSLog(@"error %@", error); } NSUInteger numberOfMatches = [regex numberOfMatchesInString:aString options:0 range:NSMakeRange(0, [aString length])]; return numberOfMatches &gt; 0; } </code></pre> <p>That's it. However I'd recommend showing some live status to the user whether his input is ok or not. Add the following notifcation, for example in your viewDidLoad method:</p> <pre><code>- (void)viewDidLoad { // ... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(validateInputCallback:) name:@"UITextFieldTextDidChangeNotification" object:nil]; } - (void)validateInputCallback:(id)sender { if ([self validateInputWithString:textField.text]) { // For example turn a label green and let it say: "OK" } else { // For example turn a label red and let it say: "Allowed: + or minus followed by exactly three digits" } } </code></pre> <p><strong>Finally:</strong> If you need to access the capture groups (+ or - and the number) of the regular expression the following code will help: </p> <pre><code>// ... reg ex creation ... NSArray *matches = [regex matchesInString:aString options:0 range:NSMakeRange(0, [aString length])]; for (NSTextCheckingResult *match in matches) { for (int i = 0; i &lt; [match numberOfRanges]; i++) { NSLog(@"range %d: %d %d", i, [match rangeAtIndex:i].location, [match rangeAtIndex:i].length); NSLog(@"substring %d: %@", i, [aString substringWithRange:[match rangeAtIndex:i]]); } } </code></pre>
6,183,882
how to query LIST using linq
<p>Suppose if I add person class instance to list and then I need to query the list using linq.</p> <pre><code>List lst=new List(); lst.add(new person{ID=1,Name="jhon",salary=2500}); lst.add(new person{ID=2,Name="Sena",salary=1500}); lst.add(new person{ID=3,Name="Max",salary=5500}); lst.add(new person{ID=4,Name="Gen",salary=3500}); </code></pre> <p>Now I want to query the above list with linq. Please guide me with sample code.</p>
6,184,069
4
0
null
2011-05-31 06:41:38.273 UTC
12
2020-05-27 11:19:18.79 UTC
2020-02-04 15:13:05.253 UTC
null
8,330,162
null
728,750
null
1
23
c#|linq-to-objects
121,665
<p>I would also suggest <a href="http://www.linqpad.net/" rel="noreferrer">LinqPad</a> as a convenient way to tackle with Linq for both advanced and beginners.</p> <p>Example:<br /><img src="https://i.stack.imgur.com/NFsiB.png" alt="enter image description here"></p>
1,998,972
Log4Net Levels Numeric Values
<p>I can't seem to find the numeric values for the predefined levels in Log4Net. Can anybody point me to them?</p>
1,999,001
2
0
null
2010-01-04 11:28:23.697 UTC
9
2017-03-24 15:31:10.82 UTC
null
null
null
null
26,521
null
1
16
log4net
10,110
<p>Here is an excerpt from the Level class (decompiled with .net reflector)</p> <pre><code> public static readonly Level Alert = new Level(0x186a0, "ALERT"); public static readonly Level All = new Level(-2147483648, "ALL"); public static readonly Level Critical = new Level(0x15f90, "CRITICAL"); public static readonly Level Debug = new Level(0x7530, "DEBUG"); public static readonly Level Emergency = new Level(0x1d4c0, "EMERGENCY"); public static readonly Level Error = new Level(0x11170, "ERROR"); public static readonly Level Fatal = new Level(0x1adb0, "FATAL"); public static readonly Level Fine = new Level(0x7530, "FINE"); public static readonly Level Finer = new Level(0x4e20, "FINER"); public static readonly Level Finest = new Level(0x2710, "FINEST"); public static readonly Level Info = new Level(0x9c40, "INFO"); private readonly string m_levelDisplayName; private readonly string m_levelName; private readonly int m_levelValue; public static readonly Level Notice = new Level(0xc350, "NOTICE"); public static readonly Level Off = new Level(0x7fffffff, "OFF"); public static readonly Level Severe = new Level(0x13880, "SEVERE"); public static readonly Level Trace = new Level(0x4e20, "TRACE"); public static readonly Level Verbose = new Level(0x2710, "VERBOSE"); public static readonly Level Warn = new Level(0xea60, "WARN"); </code></pre>
1,961,030
Ruby ampersand colon shortcut
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby">What does map(&amp;:name) mean in Ruby?</a> </p> </blockquote> <p>In Ruby, I know that if I do:</p> <pre><code>some_objects.each(&amp;:foo) </code></pre> <p>It's the same as</p> <pre><code>some_objects.each { |obj| obj.foo } </code></pre> <p>That is, <code>&amp;:foo</code> creates the block <code>{ |obj| obj.foo }</code>, turns it into a Proc, and passes it to each. Why does this work? Is it just a Ruby special case, or is there reason why this works as it does?</p>
1,961,118
2
1
null
2009-12-25 11:35:57.353 UTC
169
2020-09-28 21:46:20.84 UTC
2017-05-23 11:47:20.273 UTC
null
-1
null
235,663
null
1
339
ruby
101,791
<p>Your question is wrong, so to speak. What's happening here isn't &quot;ampersand and colon&quot;, it's &quot;ampersand and object&quot;. The colon in this case is for the symbol. So, there's <code>&amp;</code> and there's <code>:foo</code>.</p> <p>The <code>&amp;</code> calls <code>to_proc</code> on the object, and passes it as a block to the method. In Ruby, <code>to_proc</code> is implemented on <code>Symbol</code>, so that these two calls are equivalent:</p> <pre><code>something {|i| i.foo } something(&amp;:foo) </code></pre> <p>So, to sum up: <code>&amp;</code> calls <code>to_proc</code> on the object and passes it as a block to the method, and Ruby implements <code>to_proc</code> on <code>Symbol</code>.</p>
2,361,124
using __init__.py
<p>I am having difficulty understanding the usage scenarios or design goals of python's <code>__init__.py</code> files in my projects.</p> <p>Assume that I have 'model' directory (refers as a package) which contains the following files</p> <ol> <li><code>__init__.py</code></li> <li><code>meta.py</code></li> <li><code>solrmodel.py</code></li> <li><code>mongomodel.py</code></li> <li><code>samodel.py</code></li> </ol> <p>I found two ways of using <code>__init__.py</code>:</p> <ol> <li><p>I have common a definition which needs to be used in <code>solrmodel.py</code>, <code>mongomodel.py</code>, <code>samodel.py</code>. Can I use <code>__init__.py</code> as a base/common definition for all the *model.py classes? This means that I have to import <code>model/__init__.py</code>.</p></li> <li><p>Or, the <code>__init__.py</code> shall have imported definitions of solrmodel.py, mongomodel.py, samodel.py in its own and it allows the easy import of classes or function like this:</p> <pre><code># file: __init__.py from mongomodel import * from solrmodel import * from samodel import * </code></pre> <p>(I am aware that <code>import *</code> is not recommended and I just used it as a convention)</p></li> </ol> <p>I could not decide between above two scenarios. Are there more usage scenarios for <code>__init__.py</code> and can you explain the usage?</p>
2,361,278
2
2
null
2010-03-02 05:36:24.143 UTC
20
2015-10-16 23:01:37.96 UTC
2015-10-16 23:01:37.96 UTC
null
339,490
user90150
null
null
1
66
python|module|initialization|package
41,551
<p>The vast majority of the <code>__init__.py</code> files I write are empty, because many packages don't have anything to initialize.</p> <p>One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's <strong>much</strong> nicer to put that reading in a private function in the package's <code>__init__.py</code> rather than have a separate "initialization module" and redundantly import that module from every single real module in the package (uselessly repetitive and error-prone: that's obviously a case in which relying on the language's guarantee that the package's <code>__init__.py</code> <em>is</em> loaded once before any module in the package is obviously much more Pythonic!).</p> <p>For other concrete and authoritative expressions of opinion, look at the different approaches taken in the various packages that are part of Python's standard library.</p>
39,490,150
How to remotely trigger Jenkins multibranch pipeline project build?
<p>Title mostly says it. How can you trigger a Jenkins multibranch pipeline project build from a remote git repository?</p> <p>The "Trigger builds remotely" build trigger option does not seem to work, since no tokens that you set are saved.</p>
39,490,151
4
0
null
2016-09-14 12:11:57.443 UTC
10
2018-05-08 21:12:38.837 UTC
null
null
null
null
584,405
null
1
21
git|jenkins|githooks|multibranch-pipeline
21,508
<p>At the moment (Jenkins 2.22) the "Trigger builds remotely" build trigger option is visible in the multibranch pipeline job configuration, but does not work (if you check it and specify a token, it gets reset after saving anyway). According to <a href="https://issues.jenkins-ci.org/browse/JENKINS-35310" rel="noreferrer">this</a>, it is intentional that the trigger cannot be set, but a bug that it appears as an option at all. </p> <p>In the same thread they explain how to trigger builds for each individual project (branch) in a multibranch pipeline project. What I needed was a dynamic setup that would work for branches created after setting up the trigger, so rather than the suggested endpoint from the thread (<code>/job/project-name/job-name/build</code>, which should have been <code>/job/job-name/project-name/build</code> , since projects are created from branches in a job), I found that the endpoint to use is <code>/job/job-name/build</code>. In order for that to work you have to create a user with an API token (go to Manage Jenkins -> Manage Users -> Gear icon -> Show API Token), and use those as username and password in your request.</p> <p>The solution might be obvious for those used to working with Jenkins REST API, but when you are new to both multibranch pipeline projects and the REST API, it doesn't hurt to be explicit.</p>
33,283,350
What happen to Git tags pointing to a removed commit
<p>Say I do the following:</p> <ol> <li>Create branch <code>X</code></li> <li>Create Tag <code>t</code> (to branch <code>X</code>)</li> <li>Push</li> <li>Remove branch <code>X</code></li> </ol> <p>What happen to tag <code>t</code>? is it just floating there? is it considered as garbage?</p> <p>Should I remove all tags pointing at branch before removing the branch itself?</p> <h3>Reference</h3> <p>From <a href="https://git-scm.com/book/en/v2/Git-Basics-Tagging" rel="noreferrer">Git Basics - Tagging</a>:</p> <blockquote> <p>Git uses two main types of tags: lightweight and annotated. A lightweight tag is very much like a branch that doesn’t change – <strong>it’s just a pointer to a specific commit.</strong></p> </blockquote>
33,284,908
3
0
null
2015-10-22 14:21:18.223 UTC
5
2021-05-12 04:43:57.92 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,798,187
null
1
57
git|git-branch|git-tag
20,325
<blockquote> <p>What happen to tag t?</p> </blockquote> <p>Let's say you created branch <code>x</code> from a commit <code>E</code> and then tagged that commit with tag <code>t</code>. E.g.</p> <pre><code> x (branch) | V A-----B------C------D------E ^ | t (tag) </code></pre> <p>If you remove branch <code>x</code> nothing happens to tag <code>t</code>.</p> <pre><code>git branch -D x </code></pre> <p>The tag still points to commit <code>E</code>.</p> <pre><code>A-----B------C------D------E ^ | t (tag) </code></pre> <blockquote> <p>is it considered as garbage?</p> </blockquote> <p>No, because the commit is still referenced by tag <code>t</code>.</p> <blockquote> <p>What if the commit is removed?</p> </blockquote> <p>You do not remove commits. You remove pointers to commits and if commits are no longer referenced git will garbage collect them some day (depending on your configuration).</p> <p>See <a href="https://www.kernel.org/pub/software/scm/git/docs/git-gc.html" rel="noreferrer"><code>git gc</code></a></p> <p>Even if you removed all ordinary refs, like branches and tags, the commits will still be referenced in the reflog for some time and you can access them, e.g. re-create a branch, tag them or cherry-pick and so on.</p> <p>You can see the reflog using <a href="https://git-scm.com/docs/git-reflog" rel="noreferrer"><code>git reflog</code></a>. Also take a look at <code>gc.reflogExpireUnreachable</code> and <code>gc.reflogExpire</code></p> <hr /> <p><strong>EDIT</strong></p> <p>If <strong>somehow git's object database is corrupted</strong>. Either a <strong>file from <code>.git/objects</code> was deleted</strong> (e.g. you accidentially deleted it using your file explorer or a command-line command) or a <strong>ref points to a non-existent git object</strong> (like a commit, tree or blob object), you will get errors if git tries to access these objects.</p> <p>Here is a list of errors that might occur when git tries to access an object that does not exist or if a non-existent object is referenced.</p> <ul> <li><p>commit</p> <pre><code>fatal: Could not parse object '&lt;ref-name&gt;'. </code></pre> <p>example:</p> <pre><code>fatal: Could not parse object 'master'. </code></pre> </li> <li><p>tree</p> <pre><code>fatal: unable to read tree &lt;tree-sha1&gt; </code></pre> <p>example:</p> <pre><code>fatal: unable to read tree 13a3e0908e4f6fc7526056377673a5987e753fc8 </code></pre> </li> <li><p>blob</p> <pre><code>error: unable to read sha1 file of &lt;blob-name&gt; (&lt;blob-sha1&gt;) </code></pre> <p>example:</p> <pre><code>error: unable to read sha1 file of test.txt (e69de29bb2d1d6434b8b29ae775ad8c2e48c5391) </code></pre> </li> </ul> <p>Take a look at <a href="https://git-scm.com/book/en/v2/Git-Internals-Git-Objects" rel="noreferrer">Git Internals</a> for a deeper understanding.</p>
21,706,455
How do I split my module across multiple files in Typescript with node.js
<p>It seems that the information on how to actually structure code when writing Typescript is next to non-existent.</p> <p>I want to make a server in node. It has external dependencies like socket.io. The server will be too big to put it all in one file (as I imagine is the case most of the time) so I figured I'd split it up. I want to have each class in a separate file and I want to be able to use them in the whole project without needing to do something crazy like</p> <pre><code>import vector = require("vector.ts"); var vec = new vector.Vector(); </code></pre> <p>How do I do that? So far it seems that I'm fighting on two fronts. When I get tsc to actually compile, node complains on runtime, but when I modify the code so that node would work, it doesn't compile.</p> <p>I'd appreciate if someone could take the time to go through this step by step.</p>
37,480,976
4
0
null
2014-02-11 15:46:52.58 UTC
7
2021-10-16 14:06:02.877 UTC
null
null
null
null
1,031,627
null
1
40
typescript
29,737
<p>Actually you can (by now):</p> <p>file: class1.ts:</p> <pre><code>export class Class1 { name: string; constructor(name: string){ this.name = name; } } </code></pre> <p>file: class2.ts:</p> <pre><code>export class Class2 { name: string; } </code></pre> <p>consolidating module file: classes.ts:</p> <pre><code>export { Class1 } from "./class1"; export { Class2 } from "./class2"; </code></pre> <p>consuming file:</p> <pre><code>import { Class1, Class2 } from "./classes"; let c1 = new Class1("Herbert"); let c2 = new Class2(); </code></pre> <p>In this manner you can have one class (or interface) per file. In one consolidating module file (classes.ts) you then reference all entities that make up your "module".</p> <p>Now you only have to reference (import) on single module file to access all of your classes. You still have a neat compartmentalization between files.</p> <p>Hope this helps anyone still looking.</p>
50,193,885
Failed to resolve: com.google.android.material:material:1.0.0-alpha1
<p>So I'm following the official documentation to add the Material Components library to my project <a href="https://github.com/material-components/material-components-android/blob/master/docs/getting-started.md" rel="noreferrer">https://github.com/material-components/material-components-android/blob/master/docs/getting-started.md</a></p> <p>But it throws me the following error "Failed to resolve: com.google.android.material:material:1.0.0-alpha1"</p> <p>I've tried installing the repository and sync project that Android Studio suggest to no avail.</p> <p>My project config</p> <pre><code>buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.2' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.google.gms:google-services:3.2.1' } } allprojects { repositories { google() jcenter() maven { url "https://maven.google.com" } } task clean(type: Delete) { delete rootProject.buildDir } </code></pre> <p>and the app config</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 27 defaultConfig { applicationId "mlluell.eftremp" minSdkVersion 21 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:cardview-v7:27.1.1' implementation 'com.android.support:customtabs:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.0' implementation 'com.google.firebase:firebase-auth:15.1.0' implementation 'com.google.android.gms:play-services-auth:15.0.1' implementation 'com.google.firebase:firebase-database:15.0.1' implementation 'com.google.firebase:firebase-storage:15.0.2' implementation 'com.android.support:design:27.1.1' implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.google.android.material:material:1.0.0-alpha1' //imatges recyclerview implementation 'com.android.support:recyclerview-v7:27.1.1' implementation 'com.github.bumptech.glide:glide:4.6.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1' // FirebaseUI for Firebase Realtime Database implementation 'com.firebaseui:firebase-ui-database:3.3.0' // FirebaseUI for Firebase Auth implementation 'com.firebaseui:firebase-ui-auth:3.3.0' // FirebaseUI for Cloud Storage implementation 'com.firebaseui:firebase-ui-storage:3.3.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } apply plugin: 'com.google.gms.google-services' </code></pre>
50,243,620
7
2
null
2018-05-05 20:45:49.437 UTC
3
2021-09-16 15:07:41.993 UTC
null
null
null
null
1,559,684
null
1
25
android|gradle
50,512
<p>Thought I'd share what fixed this for me now that I|O has started. </p> <p>I had about the same initial setup as you. To get it working I had to change the following: </p> <ul> <li>compileSdkVersion to <code>'android-P'</code></li> <li>Support Libraries to <code>'28.0.0-alpha1'</code></li> <li>include <code>api 'com.android.support:design:28.0.0-alpha1'</code> in the dependencies block. </li> <li>SDK Platform update - Android P Preview (latest)</li> <li>targetSdkVersion <code>'P'</code></li> </ul> <p>I then did the ritualistic 'Invalidate Caches / Restart' and rebuilt the project for good measure.</p>
20,819,826
How to pass parameters to mysql query callback in nodejs
<p>I'm trying to figure out the correct way of passing custom data to a query call to be made available in the callback. I'm using MySQL library in nodejs (all latest versions).</p> <p>I have a call to connection.query(sql, function(err, result) {...});</p> <p>I couldn't find a way to 1) pass custom data/parameter to the call so that 2) it can be made available when the callback is invoked. So what is the proper way of doing so?</p> <p>I have the following (pseudo-code):</p> <pre><code>... for (ix in SomeJSONArray) { sql = "SELECT (1) FROM someTable WHERE someColumn = " + SomeJSONArray[ix].id; connection.query(sql, function (err, result) { ... var y = SomeJSONArray[ix].id; }; } </code></pre> <p>From the code above, I need to be able to pass the current value of "ix" used in the query to the callback itself.</p> <p>How do I do that?</p>
20,819,874
4
0
null
2013-12-28 21:59:54.87 UTC
6
2021-11-07 16:20:14.533 UTC
2013-12-30 03:17:48.607 UTC
null
1,368,599
null
1,368,599
null
1
28
mysql|node.js|callback
86,036
<p>If you are using node-mysql, do it like the docs say:</p> <pre><code>connection.query( 'SELECT * FROM table WHERE id=? LIMIT ?, 5',[ user_id, start ], function (err, results) { } ); </code></pre> <p>The docs also have code for proper escaping of strings, but using the array in the query call automatically does the escaping for you.</p> <p><a href="https://github.com/felixge/node-mysql" rel="noreferrer">https://github.com/felixge/node-mysql</a></p>
27,566,867
PL/SQL exception handling: do nothing (ignore exception)
<p>This is a question I am asked very frequently. Since I couldn't find any exact duplicate on stackoverflow, I thought I'd post it as a reference. </p> <p>Question: In PL/SQL, I know how to catch exceptions and execute code when they are caught, and how to propagate them to the calling block. For example, in the following procedure, the NO_DATA_FOUND exception is handled directly, while all other exceptions are raised to the calling block:</p> <pre><code>CREATE OR REPLACE PROCEDURE MY_PROCEDURE() IS BEGIN do_stuff(); EXCEPTION WHEN NO_DATA_FOUND THEN -- Do something handle_exception(); WHEN OTHERS THEN -- Propagate exception RAISE; END; </code></pre> <p>But what command should I use to ignore one or all raised exceptions and return execution control back to the calling block?</p>
27,566,868
2
0
null
2014-12-19 13:11:10.987 UTC
5
2017-04-26 14:21:14.843 UTC
null
null
null
null
4,350,421
null
1
42
oracle|exception|plsql|exception-handling
84,623
<p>While I agree that 99% of the time it is bad practice to silently ignore exceptions without at least logging them somewhere, there are specific situations where this is perfectly acceptable. </p> <p>In these situations, NULL is your friend:</p> <pre><code>[...] EXCEPTION WHEN OTHERS THEN NULL; END; </code></pre> <p>Two typical situations where ignoring exceptions might be desirable are:</p> <p>1) Your code contains a statement which you know will fail occasionally and you don't want this fact to interrupt your program flow. In this case, you should enclose you statement in a nested block, as the following example shows:</p> <pre><code>CREATE OR REPLACE PROCEDURE MY_PROCEDURE() IS l_empoyee_name EMPLOYEES.EMPLOYEE_NAME%TYPE; BEGIN -- Catch potential NO_DATA_FOUND exception and continue BEGIN SELECT EMPLOYEE_NAME INTO l_empoyee_name FROM EMPLOYEES WHERE EMPLOYEE_ID = 12345; EXCEPTION WHEN NO_DATA_FOUND THEN NULL; WHEN OTHERS THEN RAISE; END; do_stuff(); EXCEPTION WHEN OTHERS THEN -- Propagate exception RAISE; END; </code></pre> <p>Note that PL/SQL generally does not allow for the On Error Resume Next type of exception handling known from Visual Basic, where all exceptions are ignored and the program continues to run as if nothing happened (see <a href="https://stackoverflow.com/questions/23913404/on-error-resume-next-type-of-error-handling-in-pl-sql-oracle">On error resume next type of error handling in PL/SQL oracle</a>). You need to explicitly enclose potentially failing statements in a nested block.</p> <p>2) Your procedure is so unimportant that ignoring all exceptions it throws will not affect your main program logic. (However, this is very rarely the case and can often result in a debugging nightmare in the long run)</p> <pre><code>BEGIN do_stuff(); EXCEPTION WHEN OTHERS THEN -- Ignore all exceptions and return control to calling block NULL; END; </code></pre>
7,240,341
Doctrine 2 - Get all Records
<p>Does anyone know is there is a quick way to get all the records in a table using Doctrine with out using the DQL. </p> <p>Did I miss something or did you need to just write the public function in the class?</p>
7,242,210
1
0
null
2011-08-30 08:07:36.823 UTC
null
2018-11-15 03:07:03.75 UTC
2017-05-12 14:18:05.037 UTC
null
2,883,328
null
354,266
null
1
24
doctrine-orm|orm
45,045
<p>If you have an entity class (<a href="https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/tutorials/getting-started.html#entity-repositories" rel="noreferrer">Doctrine Repository manual</a>):</p> <pre><code>$records = $em-&gt;getRepository("Entities\YourTargetEntity")-&gt;findAll(); </code></pre> <p>If you don't have entity class (<a href="http://www.php.net/manual/en/book.pdo.php" rel="noreferrer">PDO manual</a>):</p> <pre><code>$pdo = $em-&gt;getCurrentConnection()-&gt;getDbh(); $result = $pdo-&gt;query("select * from table"); //plain sql query here, it's just PDO $records = $pdo-&gt;fetchAll(); </code></pre>
25,312,987
django REST framework - limited queryset for nested ModelSerializer?
<p>I have a <code>ModelSerializer</code>, but by default it serializes all the objects in my model. I would like to limit this queryset to only the most recent 500 (as opposed to all 50 million). How do I do this?</p> <p>What I have currently is the following:</p> <pre><code>class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel </code></pre> <p>The reason I don't think I can just specify the queryset in my viewset is that this is in fact the nested portion of another serializer.</p> <h2>models.py</h2> <pre><code>class Container(models.Model): size = models.CharField(max_length=20) shape = models.CharField(max_length=20) class Item(models.Model): container = models.ForeignKey(Container, related_name='items') name = models.CharField(max_length=20) color = models.CharField(max_length=20) </code></pre> <h2>views.py</h2> <pre><code>class ContainerViewSet(viewsets.ModelViewSet): queryset = Container.objects.all() # only a handful of containers serializer_class = ContainerSerializer </code></pre> <h2>serializers.py</h2> <pre><code>class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('name', 'color') class ContainerSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True) # millions of items per container class Meta: model = Container fields = ('size', 'shape', 'items') </code></pre>
25,313,145
2
0
null
2014-08-14 16:24:16.707 UTC
13
2020-02-19 00:21:57.73 UTC
2020-02-19 00:21:57.73 UTC
null
28,360
null
1,701,170
null
1
34
django|serialization|django-rest-framework
19,847
<p>In your View Set you may specify the queryset like follows:</p> <pre><code>from rest_framework import serializers, viewsets class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all()[:500] serializer_class = MyModelSerializer </code></pre> <p>I think what you are looking for is the <a href="http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield"><code>SerializerMethodField</code></a>.</p> <p>So your code would look as follows:</p> <pre><code>class ContainerSerializer(serializers.ModelSerializer): items = SerializerMethodField('get_items') class Meta: model = Container fields = ('size', 'shape', 'items') def get_items(self, container): items = Item.objects.filter(container=container)[:500] # Whatever your query may be serializer = ItemSerializer(instance=items, many=True) return serializer.data </code></pre> <p>The one catch is that the <code>SerializerMethodField</code> is read only.</p>
29,402,528
Append data frames together in a for loop
<p>I have a <code>for loop</code> which produces a data frame after each iteration. I want to append all data frames together but finding it difficult. Following is what I am trying, please suggest how to fix it:</p> <pre><code>d = NULL for (i in 1:7) { # vector output model &lt;- #some processing # add vector to a dataframe df &lt;- data.frame(model) } df_total &lt;- rbind(d,df) </code></pre>
29,419,402
9
0
null
2015-04-01 23:20:17.513 UTC
50
2022-08-24 15:27:15.433 UTC
2018-07-03 14:16:32.607 UTC
null
4,411,559
null
1,801,769
null
1
90
r
183,774
<p>Don't do it inside the loop. Make a list, then combine them outside the loop.</p> <pre><code>n = 5 datalist = list() # or pre-allocate for slightly more efficiency datalist = vector(&quot;list&quot;, length = n) for (i in 1:n) { # ... make some data dat &lt;- data.frame(x = rnorm(10), y = runif(10)) dat$i &lt;- i # maybe you want to keep track of which iteration produced it? datalist[[i]] &lt;- dat # add it to your list } big_data = do.call(rbind, datalist) # or big_data &lt;- dplyr::bind_rows(datalist) # or big_data &lt;- data.table::rbindlist(datalist) </code></pre> <p>This is a much more R-like way to do things. It can also be substantially faster, especially if you use <code>dplyr::bind_rows</code> or <code>data.table::rbindlist</code> for the final combining of data frames.</p>
53,693,987
Test Python Google Cloud Functions locally
<p>I'm trying out the Python3.7 runtime on Google Cloud Functions. I am able to deploy the functions and make them work once deployed, however, I can't seem to run the emulator to test them locally before I deploy.</p> <p>Google's documentation is a little inconsistent where they tell you to install the google functions emulator here: <a href="https://cloud.google.com/functions/docs/emulator" rel="noreferrer">https://cloud.google.com/functions/docs/emulator</a></p> <p>But over on Firebase they tell you to <code>npm install</code> firebase-admin, firebase-tools and firebase-functions.</p> <p>All of the emulator documentation references examples written in JS, none in Python so I'm wondering if these emulator even run Python functions locally?</p> <p>Thanks</p>
53,700,497
4
1
null
2018-12-09 15:47:23.273 UTC
14
2020-06-03 11:53:31.65 UTC
null
null
null
null
1,317,191
null
1
28
python-3.x|firebase|google-cloud-platform|google-cloud-functions
10,955
<p>You can use the <a href="https://github.com/GoogleCloudPlatform/functions-framework-python" rel="noreferrer">Functions Framework for Python</a> to run the function locally.</p> <p>Given a function in a file named <code>main.py</code> like so:</p> <pre class="lang-py prettyprint-override"><code>def my_function(request): return 'Hello World' </code></pre> <p>You can do:</p> <pre><code>$ pip install functions-framework $ functions-framework --target my_function </code></pre> <p>Which will start a local development server at <a href="http://localhost:8080" rel="noreferrer">http://localhost:8080</a>.</p> <p>To invoke it locally for an HTTP function:</p> <pre><code>$ curl http://localhost:8080 </code></pre> <p>For a background function with non-binary data:</p> <pre><code>$ curl -d '{"data": {"hi": "there"}}' -X POST \ -H "Content-Type: application/json" \ http://localhost:8080 </code></pre> <p>For a background function with binary data:</p> <pre><code>$ curl -d "@binary_file.file" -X POST \ -H "Ce-Type: true" \ -H "Ce-Specversion: true" \ -H "Ce-Source: true" \ -H "Ce-Id: true" \ -H "Content-Type: application/json" \ http://localhost:8080 </code></pre>
32,147,805
ffmpeg generate higher quality images for MJPEG encoding
<p>I have a bunch of mov / H.264 files, that I'd like to encode into mov/MJPEG. However I'm getting very low quality output. Here's what I tried:</p> <pre><code>ffmpeg -i a.mov -an -crf 11 -preset slower -pix_fmt yuv420p -vcodec mjpeg -f mov -y b.mov </code></pre> <p>For H.264 encoding the <code>-crf</code> and <code>-preset</code> flags generate higher quality. But that doesn't seem to work for MJPEG.</p>
32,151,594
1
1
null
2015-08-21 19:14:34.687 UTC
8
2019-12-17 03:14:35.64 UTC
2015-08-22 02:17:54.79 UTC
null
1,109,017
null
761,529
null
1
14
ffmpeg|h.264
50,926
<h1>Use <code>-q:v</code> to control (M)JPEG quality</h1> <p>The effective range is a linear scale of 2-31, and a lower value will result in a higher quality output.</p> <h3>Examples</h3> <p>Make MJPEG video in MOV container:</p> <pre><code>ffmpeg -i input.mov -c:v mjpeg -q:v 3 -an output.mov </code></pre> <p>Output a series of JPG images:</p> <pre><code>ffmpeg -i input.mov -q:v 2 images_%04d.jpg </code></pre> <p>Files will be named <code>images_0001.jpg</code>, <code>images_0002.jpg</code>, <code>images_0003.jpg</code>, etc.</p> <hr> <h1>Private options</h1> <blockquote> <p>For H.264 encoding the <code>-crf</code> and <code>-preset</code> flags generate higher quality. But that doesn't seem to work for MJPEG.</p> </blockquote> <p>The MJPEG encoder does not use <code>-crf</code> and <code>-preset</code>; these are <a href="https://ffmpeg.org/ffmpeg.html#AVOptions" rel="noreferrer">"private" options</a> for some encoders such as libx264, libx265, and libvpx. You can see private options like this: <code>ffmpeg -h encoder=mjpeg</code>.</p>
6,018,701
How is "mvn clean install" different from "mvn install"?
<p>What is the difference between <code>mvn clean install</code> and <code>mvn install</code>?</p>
6,018,748
5
0
null
2011-05-16 14:15:05.87 UTC
47
2020-11-24 00:16:07.223 UTC
2016-04-06 17:29:15.317 UTC
null
2,581,872
null
434,460
null
1
255
java|build|maven|maven-3
356,714
<p><code>clean</code> is its own build lifecycle phase (which can be thought of as an action or task) in Maven. <code>mvn clean install</code> tells Maven to do the <code>clean</code> phase in each module before running the <code>install</code> phase for each module.</p> <p>What this does is clear any compiled files you have, making sure that you're really compiling each module from scratch.</p>
5,910,817
Does a break leave just the try/catch or the surrounding loop?
<p>If I have a <code>try ... catch</code> block inside a <code>while</code> loop, and there#s a <code>break</code> inside the <code>catch</code>, does program execution leave the loop?</p> <p>As in:</p> <pre><code>while (!finished) { try { doStuff(); } catch (Exception e) { break; } } </code></pre> <p>Will an exception thrown in doStuff() exit the loop?</p>
5,910,875
6
1
null
2011-05-06 11:33:58.17 UTC
6
2018-07-31 17:01:09.293 UTC
null
null
null
null
2,077
null
1
50
java
53,407
<p>Yes, it will. Easiest way to find out is to try it.</p> <pre><code>public static void main(String[] args) { int i=0; while (i&lt;10) { System.out.println(i); try { if(i ==7){ throw new Exception(); } i++; } catch (Exception e) { break; } } System.out.println("out of loop"); } </code></pre> <p>It will print</p> <pre><code>0 1 2 3 4 5 6 7 out of loop </code></pre> <p>The output starts with 0.</p>
6,034,503
Multiple string comparison with C#
<p>Let's say I need to compare if string x is "A", "B", or "C".</p> <p>With Python, I can use in operator to check this easily.</p> <pre class="lang-python prettyprint-override"><code>if x in ["A","B","C"]: do something </code></pre> <p>With C#, I can do</p> <pre><code>if (String.Compare(x, "A", StringComparison.OrdinalIgnoreCase) || ...) do something </code></pre> <p>Can it be something more similar to Python?</p> <h2>ADDED</h2> <p>I needed to add <code>System.Linq</code> in order to use case insensitive Contain().</p> <pre><code>using System; using System.Linq; using System.Collections.Generic; class Hello { public static void Main() { var x = "A"; var strings = new List&lt;string&gt; {"a", "B", "C"}; if (strings.Contains(x, StringComparer.OrdinalIgnoreCase)) { Console.WriteLine("hello"); } } } </code></pre> <p>or</p> <pre><code>using System; using System.Linq; using System.Collections.Generic; static class Hello { public static bool In(this string source, params string[] list) { if (null == source) throw new ArgumentNullException("source"); return list.Contains(source, StringComparer.OrdinalIgnoreCase); } public static void Main() { string x = "A"; if (x.In("a", "B", "C")) { Console.WriteLine("hello"); } } } </code></pre>
6,034,535
7
0
null
2011-05-17 17:09:29.053 UTC
8
2020-02-05 10:27:35.203 UTC
2017-08-15 22:15:36.323 UTC
null
3,357,935
null
260,127
null
1
34
c#|string
58,017
<p>Use <a href="http://msdn.microsoft.com/en-us/library/bb339118.aspx" rel="noreferrer"><code>Enumerable.Contains&lt;T&gt;</code></a> which is an extension method on <code>IEnumerable&lt;T&gt;</code>:</p> <pre><code>var strings = new List&lt;string&gt; { "A", "B", "C" }; string x = // some string bool contains = strings.Contains(x, StringComparer.OrdinalIgnoreCase); if(contains) { // do something } </code></pre>
5,834,025
How to preserve request url with nginx proxy_pass
<p>I was trying to use <a href="http://code.macournoyer.com/thin/" rel="noreferrer">Thin</a> app server and had one issue.</p> <p>When nginx <a href="http://wiki.nginx.org/HttpProxyModule#proxy_pass" rel="noreferrer">proxies</a> the request to Thin (or Unicorn) using <code>proxy_pass http://my_app_upstream;</code> the application receives the modified URL sent by nginx (<code>http://my_app_upstream</code>). </p> <p>What I want is to pass the original URL and the original request from client with no modification as the app relies heavily on it.</p> <p>The nginx' <a href="http://wiki.nginx.org/HttpProxyModule#proxy_pass" rel="noreferrer">doc</a> says:</p> <blockquote> <p>If it is necessary to transmit URI in the unprocessed form then directive proxy_pass should be used without URI part.</p> </blockquote> <p>But I don't understand how exactly to configure that as the related sample is actually using URI:</p> <pre><code>location /some/path/ { proxy_pass http://127.0.0.1; } </code></pre> <p>So could you please help me figuring out how to <strong>preserve the original request URL</strong> from the client?</p>
5,834,665
8
1
null
2011-04-29 15:28:53.663 UTC
33
2021-09-20 11:10:49.927 UTC
2016-10-27 16:31:21.2 UTC
null
322,020
null
148,473
null
1
99
ruby|proxy|nginx|thin|unicorn
172,434
<p>I think the <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header" rel="noreferrer"><code>proxy_set_header</code></a> directive could help:</p> <pre><code>location / { proxy_pass http://my_app_upstream; proxy_set_header Host $host; # ... } </code></pre>
18,126,967
Unit testing on Android NDK
<p>How do you run unit tests on Android native code (native C/C++, <em>not</em> Java)? So far I've only found <a href="https://groups.google.com/forum/#!topic/android-ndk/Juvhzcoa38w">one</a> similar question, and the answer says use junit with JNI, which I don't want to do (adding JNI calls seems unnecessarily complicated for unit testing, and is not really a unit test of the native code anyway).</p> <p>Does CppUnit (also suggested there) really work on Android? Note that I want the tests to run natively on the device, not on the host development environment. <a href="http://sourceforge.net/p/cppunit/patches/68/">This</a> looks like an Android port, is it worth looking at?</p> <p>An official Google test framework like <a href="https://code.google.com/p/googletest/">googletest</a> would be ideal, but that doesn't seem to work with the NDK. </p>
18,137,842
1
0
null
2013-08-08 13:11:17.23 UTC
9
2013-08-08 23:20:29.87 UTC
null
null
null
null
2,594,114
null
1
23
unit-testing|android-ndk
11,478
<p>I use googletest through NDK I use a $(call import-module to bring in the main .so and then have a single file in the executable that looks like</p> <pre><code>int main(int argc, char *argv[]) { #if RUN_GTEST INIT_GTESTS(&amp;argc,(char**)argv); RUN_ALL_GTESTS(); #endif } </code></pre> <p>And then I build that with BUILD_EXECUTABLE, deploy it like:</p> <pre><code>find libs/ -type f -print -exec adb push {} /data/local/tmp \; </code></pre> <p>and run it like</p> <pre><code>adb shell LD_LIBRARY_PATH=/data/local/tmp:/vendor/lib:/system/lib /data/local/tmp/gtest </code></pre> <p>So it doesn't test the application life cycle but it tests all the unit tests.</p> <p>If I needed to test something with a UI I could do something similar but make what's now 'main' a native function and invoke it when the activity is loaded.</p>
5,143,068
Call private method retaining call stack
<p>I am trying to find a solution to 'break into non-public methods'.</p> <p>I just want to call <code>RuntimeMethodInfo.InternalGetCurrentMethod(...)</code>, passing my own parameter (so I can implement <code>GetCallingMethod()</code>), or directly use <code>RuntimeMethodInfo.InternatGetCurrentMethod(ref StackCrawlMark.LookForMyCaller)</code> in my logging routines. <code>GetCurrentMethod</code> is implemented as:</p> <pre><code>[MethodImpl(MethodImplOptions.NoInlining)] public static MethodBase GetCurrentMethod() { StackCrawlMark lookForMyCaller = StackCrawlMark.LookForMyCaller; return RuntimeMethodInfo.InternalGetCurrentMethod(ref lookForMyCaller); } </code></pre> <p>where <code>InternalGetCurrentMethod</code> is declared: internal :-).</p> <p>I have no problem calling the method using reflection, but this messes up the call stack and that is just the one thing that has to be preserved, otherwise it defeats its purpose.</p> <p>What are my odds of keeping the stacktrace close to the original (at least within the distance of the allowed <code>StackCrawlMark</code>s, which are <code>LookForMe</code>, <code>LookForMyCaller</code> and <code>LookForMyCallersCaller</code>. Is there some complex way to achieve what I want?</p>
5,143,727
1
0
null
2011-02-28 14:13:04.303 UTC
9
2014-12-09 20:22:55.853 UTC
2014-12-09 20:22:55.853 UTC
null
147,617
null
622,819
null
1
13
c#|reflection|methods|private
2,503
<p>If there's one thing I love about C#, it's dynamic methods.</p> <p>They let you bypass every goal and intention of the .NET creators. :D</p> <p>Here's a (thread-safe) solution:</p> <p>(Eric Lippert, please don't read this...)</p> <pre><code>enum MyStackCrawlMark { LookForMe, LookForMyCaller, LookForMyCallersCaller, LookForThread } delegate MethodBase MyGetCurrentMethodDelegate(ref MyStackCrawlMark mark); static MyGetCurrentMethodDelegate dynamicMethod = null; static MethodBase MyGetCurrentMethod(ref MyStackCrawlMark mark) { if (dynamicMethod == null) { var m = new DynamicMethod("GetCurrentMethod", typeof(MethodBase), new Type[] { typeof(MyStackCrawlMark).MakeByRefType() }, true //Ignore all privilege checks :D ); var gen = m.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); //NO type checking here! gen.Emit(OpCodes.Call, Type.GetType("System.Reflection.RuntimeMethodInfo", true) .GetMethod("InternalGetCurrentMethod", BindingFlags.Static | BindingFlags.NonPublic)); gen.Emit(OpCodes.Ret); Interlocked.CompareExchange(ref dynamicMethod, (MyGetCurrentMethodDelegate)m.CreateDelegate( typeof(MyGetCurrentMethodDelegate)), null); } return dynamicMethod(ref mark); } [MethodImpl(MethodImplOptions.NoInlining)] static void Test() { var mark = MyStackCrawlMark.LookForMe; //"Me" is Test's _caller_, NOT Test var method = MyGetCurrentMethod(ref mark); Console.WriteLine(method.Name); } </code></pre>
4,843,806
WinAPI: Create a window with a specified client area size
<p>I was wondering how can I create a window using Win32 API with a specific <em>client area size</em>.</p> <p>When trying to create a window using the following piece of code, the entire window is 640x480, with the window's chrome taking some of the client area:</p> <pre><code>HWND hWnd; WNDCLASSEX WndClsEx; ZeroMemory(&amp;WndClsEx, sizeof(WNDCLASSEX)); WndClsEx.cbSize = sizeof(WNDCLASSEX); WndClsEx.style = CS_HREDRAW | CS_VREDRAW; WndClsEx.lpfnWndProc = DefWindowProc; WndClsEx.cbClsExtra = 0; WndClsEx.cbWndExtra = 0; WndClsEx.hIcon = LoadIcon(NULL, IDI_APPLICATION); WndClsEx.hCursor = LoadCursor(NULL, IDC_ARROW); WndClsEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); WndClsEx.lpszMenuName = NULL; WndClsEx.lpszClassName = TEXT("Title"); WndClsEx.hInstance = hInstance; WndClsEx.hIconSm = LoadIcon(NULL, IDI_APPLICATION); RegisterClassEx(&amp;WndClsEx); hWnd = CreateWindowEx( NULL, TEXT("Title"), TEXT("Title"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL); </code></pre> <p><em><strong>Assuming simple math won't quite solve the problem, how do I take the chrome size into account?</em></strong></p> <p><em>Note:</em> I'm using SDL after creating the window, but I'm guessing it's bound to the window size and makes no difference to its size.</p>
4,843,828
1
0
null
2011-01-30 15:54:12.197 UTC
6
2011-10-17 13:53:53.773 UTC
null
null
null
null
242,826
null
1
40
c++|winapi|window|createwindowex
25,835
<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/ms632665(VS.85).aspx" rel="noreferrer">AdjustWindowRect</a> or <a href="http://msdn.microsoft.com/en-us/library/ms632667(v=vs.85).aspx" rel="noreferrer">AdjustWindowRectEx</a> function to calculate the window size given a desired client area size.</p>
49,361,243
Overlapping items in CSS Grid
<p>I'm trying to do a responsive layout with css grid by getting two elements to overlap each other halfway. On wide screens they are in one row and overlapping horizontally, but on narrow screens they should be in one column and overlap vertically.</p> <p>Here is an illustration of what I'm trying to achieve:</p> <p><a href="https://i.stack.imgur.com/YHaZN.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/YHaZN.jpg" alt="enter image description here"></a></p> <p>Is this behavior possible with css grid? Here is how far I got but now I'm stuck trying to get the vertical overlap.</p> <h1>CSS</h1> <pre><code>.wrapper { background: white; display: grid; grid-template-columns: repeat(auto-fit, minmax(444px, 1fr)); } .wrapper__red, .wrapper__green { align-self: center; } .wrapper__red { z-index: 1; background: red; } .wrapper__green { justify-self: end; height: 100%; background: green; } </code></pre> <h1>HTML</h1> <pre><code>&lt;div class="wrapper"&gt; &lt;h1 class="wrapper__red"&gt;Title text goes here&lt;/h1&gt; &lt;img class="wrapper__green" src="/a.jpg" /&gt; &lt;/div&gt; </code></pre>
49,373,879
2
2
null
2018-03-19 10:54:49.683 UTC
7
2021-11-09 10:50:49.257 UTC
2018-03-19 23:00:50.613 UTC
null
3,597,276
null
4,214,582
null
1
19
html|css|css-grid
47,166
<p>In CSS Grid you can create overlapping grid areas.</p> <p>Grid makes this simple and easy with <strong>line-based placement</strong>.</p> <p><em>From the spec:</em></p> <blockquote> <p><a href="http://www.w3.org/TR/css3-grid-layout/#line-placement" rel="noreferrer"><strong>8.3. Line-based Placement</strong></a></p> <p>The <code>grid-row-start</code>, <code>grid-column-start</code>, <code>grid-row-end</code>, and <code>grid-column-end</code> properties determine a grid item’s size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the inline-start, block-start, inline-end, and block-end edges of its grid area.</p> </blockquote> <p><em>note: re-size demo below to transition from desktop to mobile view</em></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>article { display: grid; grid-template-columns: repeat(6, 1fr); grid-auto-rows: 50px; grid-gap: 5px; } section:nth-child(1) { grid-column: 1 / 4; grid-row: 1; z-index: 1; } section:nth-child(2) { grid-column: 3 / 5; grid-row: 1; } section:nth-child(3) { grid-column: 5 / 7; grid-row: 1; } @media ( max-width: 500px ) { article { grid-template-columns: 100px; justify-content: center; } section:nth-child(1) { grid-row: 1 / 4; grid-column: 1; } section:nth-child(2) { grid-row: 3 / 5; grid-column: 1; } section:nth-child(3) { grid-row: 5 / 7; grid-column: 1; } } /* non-essential demo styles */ section:nth-child(1) { background-color: lightgreen; } section:nth-child(2) { background-color: orange; } section:nth-child(3) { background-color: aqua; } section { display: flex; justify-content: center; align-items: center; font-size: 1.2em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;article&gt; &lt;section&gt;&lt;span&gt;1&lt;/span&gt;&lt;/section&gt; &lt;section&gt;&lt;span&gt;2&lt;/span&gt;&lt;/section&gt; &lt;section&gt;&lt;span&gt;3&lt;/span&gt;&lt;/section&gt; &lt;/article&gt;</code></pre> </div> </div> </p> <h2><a href="https://jsfiddle.net/pog9bwpq/" rel="noreferrer">jsFiddle demo</a></h2>
24,847,062
How can I access my ViewModel from code behind
<p>I don't understand how I can create a command to create a MVVM clickable rectangle. Here is my code:</p> <pre><code>&lt;Rectangle x:Name="Color01" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="10,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100" MouseDown="Color_MouseDown" /&gt; &lt;Rectangle x:Name="Color02" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="115,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/&gt; &lt;Rectangle x:Name="Color03" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="220,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/&gt; &lt;Rectangle x:Name="Color04" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="325,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/&gt; </code></pre> <p>On my first rectangle you can see I created a code behind event. First I don't know how to access my ViewModel from the code behind. Two it's not really MVVM.</p> <pre><code>public partial class MainWindow : Window { /// &lt;summary&gt; /// Initializes a new instance of the MainWindow class. /// &lt;/summary&gt; public MainWindow() { InitializeComponent(); Closing += (s, e) =&gt; ViewModelLocator.Cleanup(); } private void Color_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { // So what ??? } } </code></pre> <p>I just need to be able to change a simple boolean value stored in a list stored in my viewModel when someone click on my rectangle. Why it is so complicate to do with MVVM?</p>
24,847,186
4
2
null
2014-07-20 03:30:03.533 UTC
7
2020-12-23 15:18:34.197 UTC
2014-07-20 03:36:20.287 UTC
null
196,526
null
196,526
null
1
20
c#|wpf|mvvm
48,169
<p>This isn't too difficult. First, create an instance of your ViewModel inside your Window XAML:</p> <p><strong>View XAML:</strong></p> <pre><code>&lt;Window x:Class=&quot;BuildAssistantUI.BuildAssistantWindow&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:VM=&quot;clr-namespace:MySolutiom.ViewModels&quot;&gt; &lt;Window.DataContext&gt; &lt;VM:MainViewModel /&gt; &lt;/Window.DataContext&gt; &lt;/Window&gt; </code></pre> <p>After that, you can <a href="http://msdn.microsoft.com/en-us/library/system.windows.interactivity.invokecommandaction(v=expression.40).aspx" rel="nofollow noreferrer"><code>System.Windows.Interactivity.InvokeCommandAction</code></a> to translate your event to a command:</p> <p><strong>View XAML:</strong></p> <pre><code>&lt;Grid&gt; &lt;Rectangle x:Name=&quot;Color01&quot; Fill=&quot;#FFF4F4F5&quot; HorizontalAlignment=&quot;Left&quot; Height=&quot;100&quot; Margin=&quot;10,29,0,0&quot; Stroke=&quot;Black&quot; VerticalAlignment=&quot;Top&quot; Width=&quot;100&quot; MouseDown=&quot;Color_MouseDown&quot;&gt; &lt;interactivity:Interaction.Triggers&gt; &lt;interactivity:EventTrigger EventName=&quot;MouseDown&quot;&gt; &lt;interactivity:InvokeCommandAction Command=&quot;{Binding MyCommand}&quot;/&gt; &lt;/interactivity:EventTrigger&gt; &lt;/interactivity:Interaction.Triggers&gt; &lt;/Rectangle&gt; &lt;/Grid&gt; </code></pre> <p>Now, in your ViewModel, set up an <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand(v=vs.110).aspx" rel="nofollow noreferrer"><code>ICommand</code></a> and the <a href="http://msdn.microsoft.com/en-us/library/ff654132.aspx" rel="nofollow noreferrer"><code>DelegateCommand</code></a> implementation to bind to that event:</p> <p><strong>ViewModel:</strong></p> <pre><code>public class ViewModel { public ICommand MyCommand { get; set; } public ViewModel() { MyCommand = new DelegateCommand(OnRectangleClicked); } public void OnRectangleClicked() { // Change boolean here } } </code></pre>
24,864,613
Delete multiple object properties?
<p>I create an object with multiple properties -</p> <pre><code>var objOpts = { option1: 'Option1', option2: 'Option2', option2: 'Option3' }; </code></pre> <p>I then add some more properties later on -</p> <pre><code>objOpts.option4 = 'Option4' objOpts.option5 = 'Option5' </code></pre> <p>I'm then done with the two latter created properties ('Option4' &amp; 'Option5') and I want to clear/delete both.</p> <p>Currently I'd do it like so -</p> <pre><code>delete objOpts.option4 delete objOpts.option5 </code></pre> <p>Is there another way to go about doing this? Imagine I'd added 5 more properties and needed to clear/delete them all that'd be five lines of almost identical 'delete' code</p>
24,864,729
9
2
null
2014-07-21 12:01:41.23 UTC
10
2020-10-21 18:52:19.96 UTC
2014-07-21 12:12:56.2 UTC
null
1,541,374
null
3,568,695
null
1
53
javascript|oop|object
63,818
<p>I'm sure you are trying to add custom properties to an object.</p> <p>A simpler way I would suggest is by creating a sub property:</p> <pre><code>objOpts.custom.option4 = 'Option4' objOpts.custom.option5 = 'Option5' </code></pre> <p>this way you could <code>delete objOpts.custom</code> and get done with it. Note that after this step you would have to recreate <code>objOpts.custom = {}</code>.</p> <p>Moreover this way would also feel closer to OOP, since your public properties would easily be distinguishable from private ones.</p> <p>If you are beginning with deleting objects in JavaScript, I'd like to point to to an excellently written article on the topic: <a href="http://perfectionkills.com/understanding-delete/" rel="noreferrer">http://perfectionkills.com/understanding-delete/</a></p> <p>You could play around with the meta properties which allow you to protect properties from being deleted etc. (to create an even better coding flow for your case)</p> <p><em>EDIT:</em> </p> <p>I'd like to add that instead of deleting and recreating the property, you could simply say <code>objOpts.custom = {}</code> which would release the <code>option4</code> and <code>option5</code> from memory (eventually, via Garbage Collection).</p>
44,659,040
Pandas: assign category based on where value falls in range
<p>I have the following ranges and a pandas DataFrame:</p> <pre><code>x &gt;= 0 # success -10 &lt;= x &lt; 0 # warning X &lt; -10 # danger df = pd.DataFrame({'x': [2, 1], 'y': [-7, -5], 'z': [-30, -20]}) </code></pre> <p>I'd like to categorize the values in the DataFrame based on where they fall within the defined ranges. So I'd like the final DF to look something like this:</p> <pre><code> x y z x_cat y_cat z_cat 0 2 -7 -30 success warning danger 1 1 -5 -20 success warning danger </code></pre> <p>I've tried using the <code>category</code> datatype but it doesn't appear I can define a range anywhere.</p> <pre><code>for category_column, value_column in zip(['x_cat', 'y_cat', 'z_cat'], ['x', 'y', 'z']): df[category_column] = df[value_column].astype('category') </code></pre> <p>Can I use the <code>category</code> datatype? If not, what can I do here?</p>
44,659,158
5
1
null
2017-06-20 16:59:10.49 UTC
9
2017-06-20 17:17:54.597 UTC
2017-06-20 17:07:52.697 UTC
null
6,611,672
null
6,611,672
null
1
13
python|pandas|categories
19,941
<p><strong><code>pandas.cut</code></strong> </p> <pre><code>c = pd.cut( df.stack(), [-np.inf, -10, 0, np.inf], labels=['danger', 'warning', 'success'] ) df.join(c.unstack().add_suffix('_cat')) x y z x_cat y_cat z_cat 0 2 -7 -30 success warning danger 1 1 -5 -20 success warning danger </code></pre> <p><strong><code>numpy</code></strong> </p> <pre><code>v = df.values cats = np.array(['danger', 'warning', 'success']) code = np.searchsorted([-10, 0], v.ravel()).reshape(v.shape) cdf = pd.DataFrame(cats[code], df.index, df.columns) df.join(cdf.add_suffix('_cat')) x y z x_cat y_cat z_cat 0 2 -7 -30 success warning danger 1 1 -5 -20 success warning danger </code></pre>
9,378,609
Disabling a submit button after one click
<p>Here's my code : </p> <pre><code>&lt;form name='frm' id='frm' action='load.asp' method='post' onSubmit='return OnSubmit(this)' style='margin-top:15px'&gt; &lt;input type='submit' name='send' id='send' onclick="this.disabled=true;return true;" value='Send' title='test'&gt; &lt;/form&gt; </code></pre> <p>I want my onsubmit function to be executed and I want the page to be submited. In my website, no submit and no function</p> <p>I've tried to duplicate it here, but the form seems to be posted and my function never gets executed ... <a href="http://jsfiddle.net/V7B3T/1/" rel="noreferrer">http://jsfiddle.net/V7B3T/1/</a></p> <p>And I don't know when I should reactivate the button.</p> <p>Should I do it in the document.ready, or in the onSubmit function ?</p> <p>So if someone can fixed the fiddle :) and after that I'll compare it with my code. I think :S I'm lost</p> <p>Thanks all</p>
9,378,878
4
0
null
2012-02-21 13:41:46.177 UTC
2
2016-03-02 15:52:14.013 UTC
2012-06-03 08:49:22.3 UTC
null
741,249
null
920,917
null
1
7
jquery|button|submit|page-lifecycle
62,932
<p>If you want to validate the form or make any changes the before submitting and only submit if the form is valid you can do something like this:</p> <pre><code>&lt;form id="frm" action="load.asp" method="post" enctype="multipart/form-data"&gt; &lt;input type="submit" name="send" id="send" value="Send" title="test"&gt; &lt;/form&gt; </code></pre> <p>and the JavaScript code:</p> <pre><code>$('#frm').bind('submit', function (e) { var button = $('#send'); // Disable the submit button while evaluating if the form should be submitted button.prop('disabled', true); var valid = true; // Do stuff (validations, etc) here and set // "valid" to false if the validation fails if (!valid) { // Prevent form from submitting if validation failed e.preventDefault(); // Reactivate the button if the form was not submitted button.prop('disabled', false); } }); </code></pre> <p>Here's a working <a href="http://jsfiddle.net/V7B3T/631/" rel="noreferrer">fiddle</a>.</p>
9,433,851
Converting utc time string to datetime object
<p>I'm using the Paypal API and I get back a timestamp in the following format. I try to parse this to a datetime object using strptime, but I get the following error:</p> <pre><code>(Pdb) datetime.strptime('2012-03-01T10:00:00Z','%Y-%M-%dT%H:%M:%SZ') *** error: redefinition of group name 'M' as group 5; was group 2 </code></pre> <p>Also, as this format is supposed to be quite a standard format isn't there a function available for this?</p> <p>EDIT:</p> <p>Ok seems to be a typo. First %M should be %m</p>
9,433,907
4
0
null
2012-02-24 15:58:13.02 UTC
5
2021-09-28 13:13:33.557 UTC
2021-09-28 13:13:33.557 UTC
null
1,069,285
null
1,069,285
null
1
33
python|python-2.7
65,676
<p>Looks like you're mixing <code>%M</code> (minute) and <code>%m</code> (month).</p>
34,149,226
Portable Android Studio
<p>I want to install android studio on my portable usb hard drive to run andoid studio in my school without install. Its is possible? Or maybe exist a portable version of android studio ? Thanks</p>
35,376,806
2
2
null
2015-12-08 06:13:21.317 UTC
8
2018-06-08 12:16:59.783 UTC
null
null
null
null
5,016,242
null
1
17
android|android-studio
38,874
<p><strong>AS (Android Studio)</strong> itself is portable, however the <strong>JDK (Java Development Kit)</strong> which is required to run AS, is not. So you still need to install JDK on each computer you use.</p> <p>You can download the AS versions here:<br /> <a href="http://tools.android.com/download/studio/stable" rel="nofollow noreferrer">http://tools.android.com/download/studio/stable</a></p> <p><strong>EDIT:</strong><br /> You need to save the AS together with <strong>SDK</strong> files: <br /> <a href="http://developer.android.com/sdk/index.html" rel="nofollow noreferrer">http://developer.android.com/sdk/index.html</a></p> <p>and if you have problems with <strong>gradle</strong>, it can be downloaded here:<br /> <a href="https://services.gradle.org/distributions/" rel="nofollow noreferrer">https://services.gradle.org/distributions/</a></p> <p>To set up gradle for offline, go to:<br /> <kbd>File</kbd> > <kbd>Settings</kbd> > <kbd>Build, Execution, Deployment</kbd> > <kbd>Gradle</kbd> then check <kbd>Offline Work</kbd>. You will need to assign the service directory path (the path where gradle lives) or just paste the downloaded gradle zip into default directory, which is <code>C:/Users/&lt;CurrentUser&gt;/.gradle</code>.<br /></p>
22,514,373
Start a service in a separate process android
<p>I want to start a service in a separate process (i.e when I go to my Application manager in the settings and then go to running services, it should show my service in a separate process).</p> <p>My Android Manifest is as follows:</p> <pre><code>&lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.example.timerapp.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;service android:name="com.example.timerapp.WorkerThread" android:process="com.moizali"&gt;&lt;/service&gt; &lt;/application&gt; </code></pre> <p>I am starting the service in my MainActivity so obviously when I kill the application the service shuts down as well. Can anyone tell me how to start the service as a different process.</p>
38,318,003
2
1
null
2014-03-19 18:00:31.71 UTC
12
2018-04-06 22:40:30.843 UTC
null
null
null
null
1,182,140
null
1
41
android|multithreading|service|process
49,657
<p>Check out the <code>process</code> attribute for <code>service</code> in <code>AndroidManifest.xml</code>. You need to change your <code>android:process</code> value to start with a <code>:</code>.</p> <p><a href="http://developer.android.com/guide/topics/manifest/service-element.html" rel="noreferrer">http://developer.android.com/guide/topics/manifest/service-element.html</a></p> <p>The relevant section:</p> <blockquote> <p>If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the service runs in that process. If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.</p> </blockquote> <p>The other answer provided doesn't really answer the question of how to start a service in a separate process.</p> <hr> <p><strong>Defining a Process of a Service</strong></p> <p>The <code>android:process</code> field defines the name of the process where the service is to run. Normally, all components of an application run in the default process created for the application. However, a component can override the default with its own process attribute, allowing you to spread your application across multiple processes.</p> <p>If the name assigned to this attribute begins with a colon (':'), the service will run in its own separate process.</p> <pre><code>&lt;service android:name="com.example.appName" android:process=":externalProcess" /&gt; </code></pre> <p>If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.</p>
7,175,509
Which is better, return "ModelAndView" or "String" on spring3 controller
<p>The way of return ModelAndView</p> <pre><code>@RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView list( @UserAuth UserAuth user, ModelAndView mav) { if (!user.isAuthenticated()) { mav.setViewName("redirect:http://www.test.com/login.jsp"); return mav; } mav.setViewName("list"); mav.addObject("articles", listService.getLists()); return mav; } </code></pre> <p>The way of return String</p> <pre><code>@RequestMapping(value = "/list", method = RequestMethod.GET) public String list( @UserAuth UserAuth user, Model model) { if (!user.isAuthenticated()) { return "redirect:http://www.test.com/login.jsp"; } model.addAttribute("articles", listService.getLists()); return "list"; } </code></pre> <p>These work same. which is better way? and what is difference?</p>
7,175,586
2
0
null
2011-08-24 12:36:49.503 UTC
46
2015-07-17 09:53:54.143 UTC
2011-08-24 12:42:39.62 UTC
null
21,234
null
889,158
null
1
118
spring-mvc|controller
92,159
<p>There is no better way. Both are perfectly valid. Which one you choose to use depends which one suits your application better - Spring allows you to do it either way.</p> <p>Historically, the two approaches come from different versions of Spring. The <code>ModelAndView</code> approach was the primary way of returning both model and view information from a controller in pre-Spring 2.0. Now you can combine the <code>Model</code> parameter and the <code>String</code> return value, but the old approach is still valid.</p>
31,237,042
What's the difference between select_related and prefetch_related in Django ORM?
<p>In Django doc,</p> <blockquote> <p><a href="https://docs.djangoproject.com/en/stable/ref/models/querysets/#select-related" rel="noreferrer"><code>select_related()</code></a> &quot;follows&quot; foreign-key relationships, selecting additional related-object data when it executes its query.</p> <p><a href="https://docs.djangoproject.com/en/stable/ref/models/querysets/#prefetch-related" rel="noreferrer"><code>prefetch_related()</code></a> does a separate lookup for each relationship, and does the &quot;joining&quot; in Python.</p> </blockquote> <p>What does it mean by &quot;doing the joining in python&quot;? Can someone illustrate with an example?</p> <p>My understanding is that for foreign key relationship, use <code>select_related</code>; and for M2M relationship, use <code>prefetch_related</code>. Is this correct?</p>
31,237,071
4
3
null
2015-07-06 02:31:40.52 UTC
156
2022-09-07 09:40:10.49 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
954,376
null
1
447
python|django|django-models|django-orm
246,145
<p>Your understanding is mostly correct. You use <code>select_related</code> when the object that you're going to be selecting is a single object, so <code>OneToOneField</code> or a <code>ForeignKey</code>. You use <code>prefetch_related</code> when you're going to get a "set" of things, so <code>ManyToManyField</code>s as you stated or reverse <code>ForeignKey</code>s. Just to clarify what I mean by "reverse <code>ForeignKey</code>s" here's an example:</p> <pre><code>class ModelA(models.Model): pass class ModelB(models.Model): a = ForeignKey(ModelA) ModelB.objects.select_related('a').all() # Forward ForeignKey relationship ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship </code></pre> <p>The difference is that <code>select_related</code> does an SQL join and therefore gets the results back as part of the table from the SQL server. <code>prefetch_related</code> on the other hand executes another query and therefore reduces the redundant columns in the original object (<code>ModelA</code> in the above example). You may use <code>prefetch_related</code> for anything that you can use <code>select_related</code> for.</p> <p>The tradeoffs are that <code>prefetch_related</code> has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.</p> <p>Everything discussed above is basically about the communications with the database. On the Python side however <code>prefetch_related</code> has the extra benefit that a single object is used to represent each object in the database. With <code>select_related</code> duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.</p>
18,944,345
ImportError: No module named jinja2
<p>Using google-app-engine tutorial, I got the following error stack message:</p> <pre><code>Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 239, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 298, in _LoadHandler handler, path, err = LoadObject(self._handler) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 84, in LoadObject obj = __import__(path[0]) File "D:\Dev\SandBoxes\web\omaha\omaha.py", line 4, in &lt;module&gt; import jinja2 ImportError: No module named jinja2 </code></pre> <p>Even though I declared it in the libraries from app.yaml:</p> <pre><code>application: *** version: 1 runtime: python27 api_version: 1 threadsafe: true libraries: - name: jinja2 version: latest - name: webapp2 version: latest handlers: - url: /css static_dir: css - url: /js static_dir: js - url: /img static_dir: img - url: /.* script: omaha.application </code></pre> <p>Has anyone had a similar problem?</p>
18,951,369
6
0
null
2013-09-22 13:28:02.18 UTC
8
2021-12-11 00:07:12.223 UTC
2014-03-08 12:07:29.903 UTC
null
2,255,305
null
1,591,720
null
1
30
python|google-app-engine|python-2.7
110,591
<p>Need to restart application in AEL.</p> <p>The application in Google App Engine Launcher must be restarted for new library calls to be taken into account. I was mislead by the fact all other changes dont need actual restart of the server.</p>
17,858,537
Spring MVC - HTTP status code 400 (Bad Request) for missing field which is defined as being not required
<p>I have Spring MVC application with this controller method.</p> <pre><code>@RequestMapping(value = "/add", method = RequestMethod.POST) public String addNumber(@RequestParam(value="number", required=false) Long number) { ... return "redirect:/showAll/"; } </code></pre> <p>In my JSP I have a standard HTML form which is posting a value named "number" to the controller method above. However, if I leave out the value (do not enter anything into the text field) and POST the data to the controller, before the controller method is called my browser shows</p> <pre><code>HTTP Status 400 - Required Long parameter 'number' is not present </code></pre> <p>although the controller method annotation clearly defines the "number"-parameter as <strong>not</strong> required.</p> <p>Does anyone have a slight idea of what could be going on?</p> <p>Thank you.</p> <p>PS: The exception that is being thrown is as follows:</p> <pre><code>org.springframework.web.bind.MissingServletRequestParameterException: Required Long parameter 'number' is not present </code></pre> <p><strong>EDIT: This is a Spring 3.2.3.RELEASE bug ( <a href="https://jira.springsource.org/browse/SPR-10592" rel="noreferrer">see here</a>). With version 3.1.4.RELEASE I do not have this problem anymore.</strong></p>
19,213,987
2
4
null
2013-07-25 12:50:43.427 UTC
2
2020-09-11 17:58:07.13 UTC
2013-07-25 14:09:18.733 UTC
null
911,651
null
911,651
null
1
10
spring|spring-mvc|spring-annotations
55,102
<p>I came across the same situation, and this happens when your parameter is present in the request with an empty value. </p> <p>That is, if your POST body contains "number=" (with empty value), then Spring throws this exception. However, if the parameter is not present at all in the request, it should work without any errors.</p>
2,024,238
Read text from an image with PHP
<p>I would like to try to read some of text from an image with PHP. </p> <p>So if I have an image like this:</p> <p><img src="https://i.stack.imgur.com/J6ggX.png" alt="enter image description here"></p> <p>How can I extract the text "Some text" into a string.</p> <p>All help and suggestions are appreciated.</p>
2,024,270
3
1
null
2010-01-07 22:43:11.85 UTC
9
2018-06-08 19:57:52.797 UTC
2014-05-27 08:17:23.853 UTC
null
247,893
null
222,159
null
1
35
php|image
78,475
<p>The process you are looking for is called Optical Character Recognition. </p> <p><a href="http://en.wikipedia.org/wiki/Optical_character_recognition" rel="noreferrer">http://en.wikipedia.org/wiki/Optical_character_recognition</a></p> <p>There is a package available, called phpOCR, that does exactly what you need. </p> <p><a href="http://sourceforge.net/projects/phpocr/" rel="noreferrer">http://sourceforge.net/projects/phpocr/</a></p>
8,875,247
iOS facebook check if friends have app installed
<p>Is there already a way with the facebook ios API to get a list of friends who have your app installed? I basically require something similar to "Words with Friends" where they can determine which of your FB friends are playing the game. I have one solution which requires some extra database use but was hoping maybe the FB api had something built in for this kind of query.</p>
12,280,544
4
1
null
2012-01-16 02:38:06.917 UTC
9
2013-08-01 20:44:00.597 UTC
2012-01-16 02:48:17.18 UTC
null
1,141,832
null
1,141,832
null
1
12
iphone|ios|facebook|api
9,278
<p>Create a <code>FBFriendPickerDelegate</code> delegate class and override this function:</p> <pre><code>-(BOOL)friendPickerViewController:(FBFriendPickerViewController *)friendPicker shouldIncludeUser:(id&lt;FBGraphUser&gt;)user{ BOOL installed = [user objectForKey:@"installed"] != nil; return installed; } </code></pre> <p>For users that do not have your app installed, <code>installed</code> field will be <code>nil</code>, but you have to request it when you load data:</p> <pre><code>self.friendsController = [[FBFriendPickerViewController alloc] initWithNibName:nil bundle:nil]; //... NSSet *fields = [NSSet setWithObjects:@"installed", nil]; self.friendPickerController.fieldsForRequest = fields; //... [self.friendsController loadData]; </code></pre>
27,008,641
Save images with phimagemanager to custom album?
<p>I am making an app that takes pictures with AVFoundation and I want to save them to a custom album that I can then query and show in my app. (I'd prefer to not have them in the general photo roll, unless the user wants that) I can't really find anything showing how to do this in Swift... or at all. Is there a different way I am supposed to do this?</p> <p>I found this example on SO but it doesn't make sense to me and I can't get it to work. </p> <pre><code> func savePhoto() { var albumFound : Bool = false var assetCollection: PHAssetCollection! var photosAsset: PHFetchResult! var assetThumbnailSize:CGSize! // Create the album if does not exist (in viewDidLoad) if let first_Obj:AnyObject = collection.firstObject{ //found the album self.albumFound = true self.assetCollection = collection.firstObject as PHAssetCollection }else{ //Album placeholder for the asset collection, used to reference collection in completion handler var albumPlaceholder:PHObjectPlaceholder! //create the folder NSLog("\nFolder \"%@\" does not exist\nCreating now...", albumName) PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName) albumPlaceholder = request.placeholderForCreatedAssetCollection }, completionHandler: {(success:Bool, error:NSError!)in NSLog("Creation of folder -&gt; %@", (success ? "Success":"Error!")) self.albumFound = (success ? true:false) if(success){ let collection = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([albumPlaceholder.localIdentifier], options: nil) self.assetCollection = collection?.firstObject as PHAssetCollection } }) } let bundle = NSBundle.mainBundle() let myFilePath = bundle.pathForResource("highlight1", ofType: "mov") let videoURL:NSURL = NSURL.fileURLWithPath(myFilePath!)! let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0), { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ //let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL) let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photosAsset) albumChangeRequest.addAssets([assetPlaceholder]) }, completionHandler: {(success, error)in dispatch_async(dispatch_get_main_queue(), { NSLog("Adding Image to Library -&gt; %@", (success ? "Sucess":"Error!")) //picker.dismissViewControllerAnimated(true, completion: nil) }) }) }) } </code></pre> <p>Any help/explanations would be great!</p>
27,660,747
5
3
null
2014-11-19 03:50:00.37 UTC
22
2020-04-27 06:24:17.023 UTC
null
null
null
null
2,433,617
null
1
38
ios|swift|uiimage|ios8|phasset
28,201
<p>This is how I do:</p> <p>At the top:</p> <pre><code>import Photos var image: UIImage! var assetCollection: PHAssetCollection! var albumFound : Bool = false var photosAsset: PHFetchResult! var assetThumbnailSize:CGSize! var collection: PHAssetCollection! var assetCollectionPlaceholder: PHObjectPlaceholder! </code></pre> <p>Creating the album:</p> <pre><code>func createAlbum() { //Get PHFetch Options let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "title = %@", "camcam") let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions) //Check return value - If found, then get the first album out if let _: AnyObject = collection.firstObject { self.albumFound = true assetCollection = collection.firstObject as! PHAssetCollection } else { //If not found - Then create a new album PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle("camcam") self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection }, completionHandler: { success, error in self.albumFound = success if (success) { let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil) print(collectionFetchResult) self.assetCollection = collectionFetchResult.firstObject as! PHAssetCollection } }) } } </code></pre> <p>When saving the photo:</p> <pre><code>func saveImage(){ PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(self.image) let assetPlaceholder = assetRequest.placeholderForCreatedAsset let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photosAsset) albumChangeRequest!.addAssets([assetPlaceholder!]) }, completionHandler: { success, error in print("added image to album") print(error) self.showImages() }) } </code></pre> <p>Showing the images from that album:</p> <pre><code>func showImages() { //This will fetch all the assets in the collection let assets : PHFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil) print(assets) let imageManager = PHCachingImageManager() //Enumerating objects to get a chached image - This is to save loading time assets.enumerateObjectsUsingBlock{(object: AnyObject!, count: Int, stop: UnsafeMutablePointer&lt;ObjCBool&gt;) in if object is PHAsset { let asset = object as! PHAsset print(asset) let imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) let options = PHImageRequestOptions() options.deliveryMode = .FastFormat imageManager.requestImageForAsset(asset, targetSize: imageSize, contentMode: .AspectFill, options: options, resultHandler: {(image: UIImage?, info: [NSObject : AnyObject]?) in print(info) print(image) }) } } </code></pre>
299,512
How do I connect to SQL Server using Emacs?
<p>What steps do I take? Any gotchas to be aware of or tips to enhance the IDE experience that are specific to SQL Server when using Emacs?</p>
299,816
4
0
null
2008-11-18 17:40:00.18 UTC
14
2015-08-30 20:45:41.783 UTC
2010-07-01 07:52:30.267 UTC
null
2,422
Ray Vega
4,872
null
1
24
sql-server|emacs|ide|database-connection|sql-mode
10,920
<p><strong>Connecting</strong></p> <p>To connect to a SQL Server database instance from Emacs:</p> <pre><code>M-x sql-ms RET M-x sql-mode </code></pre> <p>You will be prompted for standard connection information specifically the following: </p> <ul> <li>User </li> <li>Password</li> <li>Server</li> <li>Database</li> </ul> <p>For SQL Server Authentication, type in the necessary user and password info. However, if connecting via Windows Authentication, then press RETURN for both user and password leaving them blank.</p> <p><strong>Viewing Output Results</strong></p> <p>Note that to see the text of any output results in the *SQL* buffer, the 'go' statement should be called at some point. A couple of ways of doing this.</p> <p>For example, this sql statement will execute but it will not show any result text in the *SQL* buffer in its current format:</p> <pre><code>select 'foo' as bar </code></pre> <p>However, if a 'go' is appended to the end:</p> <pre><code>select 'foo' as bar go </code></pre> <p>the following will be displayed in the *SQL* buffer:</p> <pre><code> bar ----- foo (1 row affected) </code></pre> <p>Alternatively, if you do not want to have 'go' statements littering the text of your SQL script then call 'go' on the fly to see all output results since the last time that the previous 'go' statement was sent to the sql process:</p> <pre><code>C-c C-s go RET </code></pre> <p>This is helpful if you need to view any error messages that might not initially show in the *SQL* buffer.</p>
47,893,677
Why are numpy functions so slow on pandas series / dataframes?
<p>Consider a small MWE, taken from <a href="https://stackoverflow.com/q/47881048/4909087">another question</a>:</p> <pre><code>DateTime Data 2017-11-21 18:54:31 1 2017-11-22 02:26:48 2 2017-11-22 10:19:44 3 2017-11-22 15:11:28 6 2017-11-22 23:21:58 7 2017-11-28 14:28:28 28 2017-11-28 14:36:40 0 2017-11-28 14:59:48 1 </code></pre> <p>The goal is to clip all values with an upper bound of 1. My answer uses <code>np.clip</code>, which works fine.</p> <pre><code>np.clip(df.Data, a_min=None, a_max=1) array([1, 1, 1, 1, 1, 1, 0, 1]) </code></pre> <p>Or, </p> <pre><code>np.clip(df.Data.values, a_min=None, a_max=1) array([1, 1, 1, 1, 1, 1, 0, 1]) </code></pre> <p>Both of which return the same answer. My question is about the relative performance of these two methods. Consider - </p> <pre><code>df = pd.concat([df]*1000).reset_index(drop=True) %timeit np.clip(df.Data, a_min=None, a_max=1) 1000 loops, best of 3: 270 µs per loop %timeit np.clip(df.Data.values, a_min=None, a_max=1) 10000 loops, best of 3: 23.4 µs per loop </code></pre> <p>Why is there such a massive difference between the two, just by calling <code>values</code> on the latter? In other words...</p> <p><strong>Why are numpy functions so slow on pandas objects?</strong></p>
47,947,335
4
12
null
2017-12-19 19:09:34.713 UTC
7
2022-02-27 09:44:13.137 UTC
null
null
null
null
4,909,087
null
1
40
python|performance|pandas|numpy
3,686
<p>Yes, it seems like <code>np.clip</code> is a lot slower on <code>pandas.Series</code> than on <code>numpy.ndarray</code>s. That's correct but it's actually (at least asymptotically) not that bad. 8000 elements is still in the regime where constant factors are major contributors in the runtime. I think this is a very important aspect to the question, so I'm visualizing this (borrowing from <a href="https://stackoverflow.com/a/44468758/5393381">another answer</a>):</p> <pre><code># Setup import pandas as pd import numpy as np def on_series(s): return np.clip(s, a_min=None, a_max=1) def on_values_of_series(s): return np.clip(s.values, a_min=None, a_max=1) # Timing setup timings = {on_series: [], on_values_of_series: []} sizes = [2**i for i in range(1, 26, 2)] # Timing for size in sizes: func_input = pd.Series(np.random.randint(0, 30, size=size)) for func in timings: res = %timeit -o func(func_input) timings[func].append(res) %matplotlib notebook import matplotlib.pyplot as plt import numpy as np fig, (ax1, ax2) = plt.subplots(1, 2) for func in timings: ax1.plot(sizes, [time.best for time in timings[func]], label=str(func.__name__)) ax1.set_xscale('log') ax1.set_yscale('log') ax1.set_xlabel('size') ax1.set_ylabel('time [seconds]') ax1.grid(which='both') ax1.legend() baseline = on_values_of_series # choose one function as baseline for func in timings: ax2.plot(sizes, [time.best / ref.best for time, ref in zip(timings[func], timings[baseline])], label=str(func.__name__)) ax2.set_yscale('log') ax2.set_xscale('log') ax2.set_xlabel('size') ax2.set_ylabel('time relative to {}'.format(baseline.__name__)) ax2.grid(which='both') ax2.legend() plt.tight_layout() </code></pre> <p><a href="https://i.stack.imgur.com/NXQXu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NXQXu.png" alt="enter image description here" /></a></p> <p>It's a log-log plot because I think this shows the important features more clearly. For example it shows that <code>np.clip</code> on a <code>numpy.ndarray</code> is faster but it also has a much smaller constant factor in that case. The difference for large arrays is only ~3! That's still a big difference but way less than the difference on small arrays.</p> <p>However, that's still not an answer to the question where the time difference comes from.</p> <p>The solution is actually quite simple: <code>np.clip</code> delegates to the <code>clip</code> <strong>method</strong> of the first argument:</p> <pre><code>&gt;&gt;&gt; np.clip?? Source: def clip(a, a_min, a_max, out=None): &quot;&quot;&quot; ... &quot;&quot;&quot; return _wrapfunc(a, 'clip', a_min, a_max, out=out) &gt;&gt;&gt; np.core.fromnumeric._wrapfunc?? Source: def _wrapfunc(obj, method, *args, **kwds): try: return getattr(obj, method)(*args, **kwds) # ... except (AttributeError, TypeError): return _wrapit(obj, method, *args, **kwds) </code></pre> <p>The <code>getattr</code> line of the <code>_wrapfunc</code> function is the important line here, because <code>np.ndarray.clip</code> and <code>pd.Series.clip</code> are different methods, yes, <strong>completely different methods</strong>:</p> <pre><code>&gt;&gt;&gt; np.ndarray.clip &lt;method 'clip' of 'numpy.ndarray' objects&gt; &gt;&gt;&gt; pd.Series.clip &lt;function pandas.core.generic.NDFrame.clip&gt; </code></pre> <p>Unfortunately is <code>np.ndarray.clip</code> a C-function so it's hard to profile it, however <code>pd.Series.clip</code> is a regular Python function so it's easy to profile. Let's use a Series of 5000 integers here:</p> <pre><code>s = pd.Series(np.random.randint(0, 100, 5000)) </code></pre> <p>For the <code>np.clip</code> on the <code>values</code> I get the following line-profiling:</p> <pre><code>%load_ext line_profiler %lprun -f np.clip -f np.core.fromnumeric._wrapfunc np.clip(s.values, a_min=None, a_max=1) Timer unit: 4.10256e-07 s Total time: 2.25641e-05 s File: numpy\core\fromnumeric.py Function: clip at line 1673 Line # Hits Time Per Hit % Time Line Contents ============================================================== 1673 def clip(a, a_min, a_max, out=None): 1674 &quot;&quot;&quot; ... 1726 &quot;&quot;&quot; 1727 1 55 55.0 100.0 return _wrapfunc(a, 'clip', a_min, a_max, out=out) Total time: 1.51795e-05 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55 Line # Hits Time Per Hit % Time Line Contents ============================================================== 55 def _wrapfunc(obj, method, *args, **kwds): 56 1 2 2.0 5.4 try: 57 1 35 35.0 94.6 return getattr(obj, method)(*args, **kwds) 58 59 # An AttributeError occurs if the object does not have 60 # such a method in its class. 61 62 # A TypeError occurs if the object does have such a method 63 # in its class, but its signature is not identical to that 64 # of NumPy's. This situation has occurred in the case of 65 # a downstream library like 'pandas'. 66 except (AttributeError, TypeError): 67 return _wrapit(obj, method, *args, **kwds) </code></pre> <p>But for <code>np.clip</code> on the <code>Series</code> I get a totally different profiling result:</p> <pre><code>%lprun -f np.clip -f np.core.fromnumeric._wrapfunc -f pd.Series.clip -f pd.Series._clip_with_scalar np.clip(s, a_min=None, a_max=1) Timer unit: 4.10256e-07 s Total time: 0.000823794 s File: numpy\core\fromnumeric.py Function: clip at line 1673 Line # Hits Time Per Hit % Time Line Contents ============================================================== 1673 def clip(a, a_min, a_max, out=None): 1674 &quot;&quot;&quot; ... 1726 &quot;&quot;&quot; 1727 1 2008 2008.0 100.0 return _wrapfunc(a, 'clip', a_min, a_max, out=out) Total time: 0.00081846 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55 Line # Hits Time Per Hit % Time Line Contents ============================================================== 55 def _wrapfunc(obj, method, *args, **kwds): 56 1 2 2.0 0.1 try: 57 1 1993 1993.0 99.9 return getattr(obj, method)(*args, **kwds) 58 59 # An AttributeError occurs if the object does not have 60 # such a method in its class. 61 62 # A TypeError occurs if the object does have such a method 63 # in its class, but its signature is not identical to that 64 # of NumPy's. This situation has occurred in the case of 65 # a downstream library like 'pandas'. 66 except (AttributeError, TypeError): 67 return _wrapit(obj, method, *args, **kwds) Total time: 0.000804922 s File: pandas\core\generic.py Function: clip at line 4969 Line # Hits Time Per Hit % Time Line Contents ============================================================== 4969 def clip(self, lower=None, upper=None, axis=None, inplace=False, 4970 *args, **kwargs): 4971 &quot;&quot;&quot; ... 5021 &quot;&quot;&quot; 5022 1 12 12.0 0.6 if isinstance(self, ABCPanel): 5023 raise NotImplementedError(&quot;clip is not supported yet for panels&quot;) 5024 5025 1 10 10.0 0.5 inplace = validate_bool_kwarg(inplace, 'inplace') 5026 5027 1 69 69.0 3.5 axis = nv.validate_clip_with_axis(axis, args, kwargs) 5028 5029 # GH 17276 5030 # numpy doesn't like NaN as a clip value 5031 # so ignore 5032 1 158 158.0 8.1 if np.any(pd.isnull(lower)): 5033 1 3 3.0 0.2 lower = None 5034 1 26 26.0 1.3 if np.any(pd.isnull(upper)): 5035 upper = None 5036 5037 # GH 2747 (arguments were reversed) 5038 1 1 1.0 0.1 if lower is not None and upper is not None: 5039 if is_scalar(lower) and is_scalar(upper): 5040 lower, upper = min(lower, upper), max(lower, upper) 5041 5042 # fast-path for scalars 5043 1 1 1.0 0.1 if ((lower is None or (is_scalar(lower) and is_number(lower))) and 5044 1 28 28.0 1.4 (upper is None or (is_scalar(upper) and is_number(upper)))): 5045 1 1654 1654.0 84.3 return self._clip_with_scalar(lower, upper, inplace=inplace) 5046 5047 result = self 5048 if lower is not None: 5049 result = result.clip_lower(lower, axis, inplace=inplace) 5050 if upper is not None: 5051 if inplace: 5052 result = self 5053 result = result.clip_upper(upper, axis, inplace=inplace) 5054 5055 return result Total time: 0.000662153 s File: pandas\core\generic.py Function: _clip_with_scalar at line 4920 Line # Hits Time Per Hit % Time Line Contents ============================================================== 4920 def _clip_with_scalar(self, lower, upper, inplace=False): 4921 1 2 2.0 0.1 if ((lower is not None and np.any(isna(lower))) or 4922 1 25 25.0 1.5 (upper is not None and np.any(isna(upper)))): 4923 raise ValueError(&quot;Cannot use an NA value as a clip threshold&quot;) 4924 4925 1 22 22.0 1.4 result = self.values 4926 1 571 571.0 35.4 mask = isna(result) 4927 4928 1 95 95.0 5.9 with np.errstate(all='ignore'): 4929 1 1 1.0 0.1 if upper is not None: 4930 1 141 141.0 8.7 result = np.where(result &gt;= upper, upper, result) 4931 1 33 33.0 2.0 if lower is not None: 4932 result = np.where(result &lt;= lower, lower, result) 4933 1 73 73.0 4.5 if np.any(mask): 4934 result[mask] = np.nan 4935 4936 1 90 90.0 5.6 axes_dict = self._construct_axes_dict() 4937 1 558 558.0 34.6 result = self._constructor(result, **axes_dict).__finalize__(self) 4938 4939 1 2 2.0 0.1 if inplace: 4940 self._update_inplace(result) 4941 else: 4942 1 1 1.0 0.1 return result </code></pre> <p>I stopped going into the subroutines at that point because it already highlights where the <code>pd.Series.clip</code> does much more work than the <code>np.ndarray.clip</code>. Just compare the total time of the <code>np.clip</code> call on the <code>values</code> (55 timer units) to one of the first checks in the <code>pandas.Series.clip</code> method, the <code>if np.any(pd.isnull(lower))</code> (158 timer units). At that point the pandas method didn't even start at clipping and it already takes 3 times longer.</p> <p>However several of these &quot;overheads&quot; become insignificant when the array is big:</p> <pre><code>s = pd.Series(np.random.randint(0, 100, 1000000)) %lprun -f np.clip -f np.core.fromnumeric._wrapfunc -f pd.Series.clip -f pd.Series._clip_with_scalar np.clip(s, a_min=None, a_max=1) Timer unit: 4.10256e-07 s Total time: 0.00593476 s File: numpy\core\fromnumeric.py Function: clip at line 1673 Line # Hits Time Per Hit % Time Line Contents ============================================================== 1673 def clip(a, a_min, a_max, out=None): 1674 &quot;&quot;&quot; ... 1726 &quot;&quot;&quot; 1727 1 14466 14466.0 100.0 return _wrapfunc(a, 'clip', a_min, a_max, out=out) Total time: 0.00592779 s File: numpy\core\fromnumeric.py Function: _wrapfunc at line 55 Line # Hits Time Per Hit % Time Line Contents ============================================================== 55 def _wrapfunc(obj, method, *args, **kwds): 56 1 1 1.0 0.0 try: 57 1 14448 14448.0 100.0 return getattr(obj, method)(*args, **kwds) 58 59 # An AttributeError occurs if the object does not have 60 # such a method in its class. 61 62 # A TypeError occurs if the object does have such a method 63 # in its class, but its signature is not identical to that 64 # of NumPy's. This situation has occurred in the case of 65 # a downstream library like 'pandas'. 66 except (AttributeError, TypeError): 67 return _wrapit(obj, method, *args, **kwds) Total time: 0.00591302 s File: pandas\core\generic.py Function: clip at line 4969 Line # Hits Time Per Hit % Time Line Contents ============================================================== 4969 def clip(self, lower=None, upper=None, axis=None, inplace=False, 4970 *args, **kwargs): 4971 &quot;&quot;&quot; ... 5021 &quot;&quot;&quot; 5022 1 17 17.0 0.1 if isinstance(self, ABCPanel): 5023 raise NotImplementedError(&quot;clip is not supported yet for panels&quot;) 5024 5025 1 14 14.0 0.1 inplace = validate_bool_kwarg(inplace, 'inplace') 5026 5027 1 97 97.0 0.7 axis = nv.validate_clip_with_axis(axis, args, kwargs) 5028 5029 # GH 17276 5030 # numpy doesn't like NaN as a clip value 5031 # so ignore 5032 1 125 125.0 0.9 if np.any(pd.isnull(lower)): 5033 1 2 2.0 0.0 lower = None 5034 1 30 30.0 0.2 if np.any(pd.isnull(upper)): 5035 upper = None 5036 5037 # GH 2747 (arguments were reversed) 5038 1 2 2.0 0.0 if lower is not None and upper is not None: 5039 if is_scalar(lower) and is_scalar(upper): 5040 lower, upper = min(lower, upper), max(lower, upper) 5041 5042 # fast-path for scalars 5043 1 2 2.0 0.0 if ((lower is None or (is_scalar(lower) and is_number(lower))) and 5044 1 32 32.0 0.2 (upper is None or (is_scalar(upper) and is_number(upper)))): 5045 1 14092 14092.0 97.8 return self._clip_with_scalar(lower, upper, inplace=inplace) 5046 5047 result = self 5048 if lower is not None: 5049 result = result.clip_lower(lower, axis, inplace=inplace) 5050 if upper is not None: 5051 if inplace: 5052 result = self 5053 result = result.clip_upper(upper, axis, inplace=inplace) 5054 5055 return result Total time: 0.00575753 s File: pandas\core\generic.py Function: _clip_with_scalar at line 4920 Line # Hits Time Per Hit % Time Line Contents ============================================================== 4920 def _clip_with_scalar(self, lower, upper, inplace=False): 4921 1 2 2.0 0.0 if ((lower is not None and np.any(isna(lower))) or 4922 1 28 28.0 0.2 (upper is not None and np.any(isna(upper)))): 4923 raise ValueError(&quot;Cannot use an NA value as a clip threshold&quot;) 4924 4925 1 120 120.0 0.9 result = self.values 4926 1 3525 3525.0 25.1 mask = isna(result) 4927 4928 1 86 86.0 0.6 with np.errstate(all='ignore'): 4929 1 2 2.0 0.0 if upper is not None: 4930 1 9314 9314.0 66.4 result = np.where(result &gt;= upper, upper, result) 4931 1 61 61.0 0.4 if lower is not None: 4932 result = np.where(result &lt;= lower, lower, result) 4933 1 283 283.0 2.0 if np.any(mask): 4934 result[mask] = np.nan 4935 4936 1 78 78.0 0.6 axes_dict = self._construct_axes_dict() 4937 1 532 532.0 3.8 result = self._constructor(result, **axes_dict).__finalize__(self) 4938 4939 1 2 2.0 0.0 if inplace: 4940 self._update_inplace(result) 4941 else: 4942 1 1 1.0 0.0 return result </code></pre> <p>There are still multiple function calls, for example <code>isna</code> and <code>np.where</code>, that take a significant amount of time, but overall this is at least comparable to the <code>np.ndarray.clip</code> time (that's in the regime where the timing difference is ~3 on my computer).</p> <p>The takeaway should probably be:</p> <ul> <li>Many NumPy functions just delegate to a method of the object passed in, so there can be huge differences when you pass in different objects.</li> <li>Profiling, especially line-profiling, can be a great tool to find the places where the performance difference comes from.</li> <li>Always make sure to test differently sized objects in such cases. You could be comparing constant factors that probably don't matter except if you process lots of small arrays.</li> </ul> <p>Used versions:</p> <pre><code>Python 3.6.3 64-bit on Windows 10 Numpy 1.13.3 Pandas 0.21.1 </code></pre>
31,364,475
Genymotion Error: "Unable to load VirtualBox Engine" on Yosemite. VirtualBox installed
<p>I have a Macbook Pro 13 inch with OS X Yosemite [Memory 8 GB, Graphics Intel Iris Graphics 6100 1536 MB]. I am trying to setup Genymotion as Android Emulator. I installed Oracle VirtualBox first from <a href="https://www.virtualbox.org/wiki/Downloads" rel="noreferrer">https://www.virtualbox.org/wiki/Downloads</a> [VirtualBox-5.0.0-101573-OSX.dmg], and then Genymotion for personal use from <a href="https://www.genymotion.com/#!/" rel="noreferrer">Genymotion</a> [genymotion-2.5.0.dmg]. </p> <p>But I get the following error - </p> <p><img src="https://i.stack.imgur.com/hLZHk.png" alt="Unable to load VirtualBox engine"></p> <p>I checked all the previous answers on StackOverflow and the Google search results, and I did the following, but none of them solved the problem.</p> <p><strong>1.</strong> (a) </p> <blockquote> <p>sudo /Library/Startupitems/VirtualBox/VirtualBox restart</p> </blockquote> <p>OR (b)</p> <blockquote> <p>sudo /Library/Application\ Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh restart</p> </blockquote> <p>Since my <strong>/Library/Startupitems/</strong> is empty, I tried option (b).</p> <p><strong>2.</strong> Open <strong>VirtualBox -> Preferences -> Network</strong>, Under "<strong>Host-only Networks</strong>", I deleted the one that was listed. Under "<strong>Nat Networks</strong>", there is an Active network called "<strong>NatNetwork</strong>", which is checked.</p> <p><strong>3.</strong> <em>vboxmanage</em> is added to path &amp; has nothing under <em>hostonlyifs</em></p> <p>Terminal:</p> <pre><code>$ which vboxmanage /usr/local/bin/vboxmanage $ echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin: &lt;others&gt; $ vboxmanage list hostonlyifs ## no output - prints nothing </code></pre> <p>These are all I found through Google Search. How do I get the Genymotion working for Yosemite ? </p> <p>{ If possible, please provide a solution that is not too technical, since I am new to Mac, and it might also help people using Mac for the first time. I know this is not a new question on StackOverflow. But none of the previous posts had helped me. }</p> <p>Thanks for your help.</p>
31,379,463
9
1
null
2015-07-12 04:51:39.323 UTC
11
2019-04-13 02:30:49.817 UTC
2015-07-21 09:25:50.373 UTC
null
1,682,975
null
1,682,975
null
1
29
android|macos|android-emulator|osx-yosemite|genymotion
26,801
<p>I had the problem that VBoxManage was installed at /usr/local/bin/ which was not in the path for GUI apps. I did:</p> <pre><code>sudo ln -s /usr/local/bin/VBoxManage /usr/bin/VBoxManage </code></pre>
19,959,072
Sending binary data in javascript over HTTP
<p>I'm trying to send a HTTP POST to a device on my network. I want to send four specific bytes of data to the device unfortunately I only seem to be able to send strings to the device. Is there anyway to send raw binary using javascript? </p> <p>Here's the script I'm using to do the POST, it currently doesn't run unless I put a string in the data field. Any ideas?</p> <pre><code>(function ($) { $.ajax({ url: '&lt;IP of Address&gt;', type: 'POST', contentType: 'application/octet-stream', //data:'253,0,128,1', data:0xFD008001, crossDomain: true }); })(jQuery); </code></pre>
19,959,244
4
0
null
2013-11-13 16:24:42.483 UTC
19
2018-11-11 18:47:39.42 UTC
2013-11-13 17:54:48.867 UTC
null
1,229,023
null
2,984,509
null
1
39
javascript|ajax|binary|hex
77,940
<p>By default, jQuery serializes the data (passed in <code>data</code> property) - and it means <code>0xFD008001</code> <em>number</em> gets passed to the server as '4244668417' <em>string</em> (10 bytes, not 4), that's why the server treats it not as expected. </p> <p>It's necessary to prevent such behaviour by setting <code>$.ajax</code> property <code>processData</code> to <code>false</code>:</p> <blockquote> <p>By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.</p> </blockquote> <p>... but that's only part of the whole story: <code>XMLHttpRequest.send</code> implementation has its own <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Browser_Compatibility">restrictions</a>. That's why your best bet, I suppose, is to make your own serializer using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays"><strong>TypedArrays</strong></a>:</p> <pre><code>// Since we deal with Firefox and Chrome only var bytesToSend = [253, 0, 128, 1], bytesArray = new Uint8Array(bytesToSend); $.ajax({ url: '%your_service_url%', type: 'POST', contentType: 'application/octet-stream', data: bytesArray, processData: false }); </code></pre> <p>Or without using jQuery at all:</p> <pre><code>var bytesToSend = [253, 0, 128, 1], bytesArray = new Uint8Array(bytesToSend); var xhr = new XMLHttpRequest(); xhr.open('POST', '%your_service_url%'); xhr.setRequestHeader('Content-Type', 'application/octet-stream'); xhr.send(bytesArray); </code></pre>
4,635,548
Accessing the object in a django admin template
<p>I'm overriding the change_form.html template and want to display links to other related objects. </p> <p>When overriding an admin template, is there a way to access the object that is beeing edited in the template? Or perhaps pass that object to the template when registering it to the admin in some way?</p>
4,636,345
1
0
null
2011-01-08 18:51:47.833 UTC
7
2011-08-01 15:48:43.017 UTC
null
null
null
null
247,004
null
1
42
django|django-admin|django-templates
11,395
<p>A quick look at django.contib.admin.options' change_view method shows the original object is included as a context variable called <code>original</code>. So if you're simply overriding change_form.html itself you can get to the object being edited via <code>{{ original }}</code>. </p>
14,075,893
jquery draggable - containment
<p>I have a little project I'm working on, and have an interesting containment issue using jquery's <code>draggable</code>:</p> <p>Basically, I have two divs - a top &amp; and a bottom. Then, I have a third div that is a .draggable({}) and can be dragged in order to resize the top and bottom div.</p> <p>-- have a look here: <a href="http://jsfiddle.net/Kpt2K/7/" rel="noreferrer">http://jsfiddle.net/Kpt2K/7/</a></p> <p>The issue is, I'm not able to contain the dragging as I would like. In the fiddle above, I put orange <code>&lt;span&gt;</code>s where I'd like the containment to begin and end.</p> <p>Interesting note: I tried doing something of the following:</p> <pre><code>$('#container').innerWrap('&lt;div id='containmentBox' /&gt;'); var containerHeight = $('#container').height(); $('#containmentBox').css({'height': containerHeight - 45); </code></pre> <p>this made the containment work for the bottom, but not the top span. So, I think I'm stuck using <code>containment: [x1,y1,x2,y2]</code>, but haven't quite grasped how to use it.</p> <p>Take a look at the fiddle, and let me know what you can come up with to constrain the draggable movement to inside the two orange spans.</p>
14,076,086
4
0
null
2012-12-28 21:15:26.3 UTC
5
2013-09-09 13:17:40.217 UTC
null
null
null
null
1,434,239
null
1
6
jquery|jquery-ui
42,106
<p>The <a href="http://api.jqueryui.com/draggable/#option-containment" rel="noreferrer">containment option</a> allows an array where to set the positions where to contain it. Try this:</p> <pre><code>var containmentTop = $("#stop-top").position().top; var containmentBottom = $("#stop-bottom").position().top; $('#bar').draggable({axis: 'y', containment : [0,containmentTop,0,containmentBottom] }); </code></pre> <p><a href="http://jsfiddle.net/Kpt2K/11/" rel="noreferrer">JSFiddle example</a></p>
34,788,543
How to use date picker in Angular 2?
<p>I have tried many date picker in my angular2 app but none of them is working.Although the date picker is displaying on the view but the value of selected date is not getting in the ngModel variable.</p>
34,789,262
10
4
null
2016-01-14 11:31:45.677 UTC
7
2022-05-12 16:18:51.667 UTC
2016-03-26 06:38:29.277 UTC
null
5,350,006
null
5,350,006
null
1
32
jquery|datepicker|angular|angular2-forms
84,650
<p>In fact, you can use a datepicker by simply adding the <code>date</code> value into the <code>type</code> attribute of your inputs:</p> <pre><code>&lt;input type="date" [(ngModel)]="company.birthdate"/&gt; </code></pre> <p>In some browsers like Chrome and Microsoft Edge (not in Firefox), you can click on the icon within the input to display the date picker. Icons appear only when you mouse is over the input.</p> <p>To have something cross browsers, you should consider to use Angular2 compliant libraries like:</p> <ul> <li><a href="https://github.com/kekeh/mydatepicker" rel="noreferrer">https://github.com/kekeh/mydatepicker</a></li> <li><a href="https://github.com/jkuri/ng2-datepicker" rel="noreferrer">https://github.com/jkuri/ng2-datepicker</a></li> </ul>
39,461,805
What does JSX stand for?
<p>What does JSX stand for?</p> <p>I am referring to the JSX that is defined as a XML-like syntax extension to ECMAScript, which has become quite popular with the increasing popularity of ReactJS.</p>
39,461,887
6
1
null
2016-09-13 03:31:37.367 UTC
15
2022-01-02 19:13:39.437 UTC
2017-05-21 21:44:56.73 UTC
null
5,647,260
null
2,977,636
null
1
55
javascript|reactjs
30,053
<p>JSX stands for <em><strong>J</strong>ava<strong>S</strong>cript <strong>X</strong>ML</em>. With React, it's an extension for XML-like code for elements and components. Per the React docs and as you mentioned:</p> <blockquote> <p>JSX is a XML-like syntax extension to ECMAScript without any defined semantics</p> </blockquote> <p>From the quote above, you can see that JSX doesn't have defined semantics, it's just an extension to JavaScript that allows to write XML-like code for simplicity and elegance, and then you transpile the JSX into pure JavaScript function calls with <a href="https://facebook.github.io/react/docs/react-api.html#createelement" rel="noreferrer"><code>React.createElement</code></a>. Per the React tutorial:</p> <blockquote> <p>JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.</p> <p>Just like XML, JSX tags have a tag name, attributes, and children. If an attribute value is enclosed in quotes, the value is a string. Otherwise, wrap the value in braces and the value is the enclosed JavaScript expression.</p> </blockquote> <p>Any code in JSX is transformed into plain JavaScript/ECMAScript. Consider a component called <code>Login</code>. Now we render it like so with JSX:</p> <pre><code>&lt;Login foo={...} bar={...} /&gt; </code></pre> <p>As you can see, JSX just allows you to have XML-like syntax for tags, representing components and elements in React. It's transpiled into pure JavaScript:</p> <pre><code>React.createElement(Login, { foo: ..., bar: ... }); </code></pre> <p>You can read more <a href="https://facebook.github.io/react/docs/jsx-in-depth.html" rel="noreferrer">at the docs</a>.</p>
39,497,307
is it dangerous to create a branch with same name as a deleted branch?
<p>I've been working on a feature in a branch; call it 'foo'. I'm done for now and merging it into master and would like to delete it locally and remotely. But sometime in the future I may start working on this feature again and will be tempted to create a new branch also called 'foo'.</p> <p>I don't think this will be a problem for me, but if someone else has their own copy of my current foo branch, and then they try to pull after the new foo branch has been created, will they get screwed up?</p>
39,497,631
1
1
null
2016-09-14 18:29:52.003 UTC
5
2016-09-14 19:04:36.533 UTC
null
null
null
null
1,368,860
null
1
46
git
20,685
<p>No, it's not a problem.</p> <p>The behaviour would be the same, as if the branch has not been deleted: Git will try to merge (or rebase) them when someone pulls the <em>new</em> branch. If there are conflicts, they would be there in either case.</p> <p>Branches are, simply, pointers to commits. If you delete a branch, and create another one with the same name later on another commit, this is the <em>same</em> as if you would <em>reset</em> it to that commit (<code>git reset</code>).</p>
53,375,613
Why is the Java 11 base Docker image so large? (openjdk:11-jre-slim)
<p>Java 11 is announced to be the most recent LTS version. So, we're trying to start new services based on this Java version.</p> <p>However, the base Docker image for Java 11 is much larger than the equivalent for Java 8:</p> <ul> <li><p><a href="https://github.com/docker-library/openjdk/blob/master/8/jre/alpine/Dockerfile" rel="noreferrer"><code>openjdk:8-jre-alpine</code></a>: 84 MB</p></li> <li><p><a href="https://github.com/docker-library/openjdk/blob/master/11/jre/slim/Dockerfile" rel="noreferrer"><code>openjdk:11-jre-slim</code></a>: <strong>283</strong> MB</p></li> </ul> <p>(I'm considering only the <a href="https://hub.docker.com/_/openjdk/" rel="noreferrer"><strong><em>official OpenJDK</em></strong></a> and <strong><em>the most lightweight</em></strong> images for each Java version.)</p> <p>Deeper digging uncovered the following "things":</p> <ul> <li><p>the <a href="https://github.com/docker-library/openjdk/blob/master/11/jre/slim/Dockerfile" rel="noreferrer"><code>openjdk:11-jre-slim</code></a> image uses the base image <code>debian:sid-slim</code>. This brings 2 issues: </p> <ul> <li><p>this is 60 MB larger than <code>alpine:3.8</code></p></li> <li><p>the <a href="https://www.debian.org/releases/sid/" rel="noreferrer">Debian <code>sid</code></a> versions are unstable</p></li> </ul></li> <li><p>the <code>openjdk-11-jre-headless</code> package installed in the image is <strong>3 times larger</strong> than <code>openjdk8-jre</code> (inside running Docker container):</p> <ul> <li><p><code>openjdk:8-jre-alpine</code>: </p> <blockquote> <pre><code>/ # du -hs /usr/lib/jvm/java-1.8-openjdk/jre/lib/ 57.5M /usr/lib/jvm/java-1.8-openjdk/jre/lib/ </code></pre> </blockquote></li> <li><p><code>openjdk:11-jre-slim</code>:</p> <blockquote> <pre><code># du -sh /usr/lib/jvm/java-11-openjdk-amd64/lib/ 179M /usr/lib/jvm/java-11-openjdk-amd64/lib/ </code></pre> </blockquote> <p>Going deeper I discovered the "root" of this heaviness - it's the <code>modules</code> file of the JDK:</p> <blockquote> <pre><code># ls -lhG /usr/lib/jvm/java-11-openjdk-amd64/lib/modules 135M /usr/lib/jvm/java-11-openjdk-amd64/lib/modules </code></pre> </blockquote></li> </ul></li> </ul> <p>So, now the questions which came:</p> <ul> <li><p>Why is <code>alpine</code> not used any more as a base image for Java 11 slim images?</p></li> <li><p>Why is the unstable <em>sid</em> version used for LTS Java images?</p></li> <li><p>Why is the slim/headless/JRE package for OpenJDK 11 so large compared to the similar OpenJDK 8 package? </p> <ul> <li>What is this <em>modules</em> file which brings 135 MB in OpenJDK 11?</li> </ul></li> </ul> <p><strong>UPD</strong>: as a solutions for these challenges one could use this answer: <a href="https://stackoverflow.com/questions/53669151/java-11-application-as-docker-image/53669152#53669152">Java 11 application as docker image</a></p>
53,383,373
4
9
null
2018-11-19 13:24:35.423 UTC
56
2021-07-02 04:16:59.737 UTC
2019-01-18 13:15:15.637 UTC
null
907,576
null
907,576
null
1
197
java|docker|alpine-linux|java-11
137,105
<blockquote> <p>Why is <code>alpine</code> not used any more as a base image for Java 11 slim images?</p> </blockquote> <p>That's because, sadly, there is no official stable OpenJDK 11 build for Alpine currently.</p> <p>Alpine uses musl libc, as opposed to the standard glibc used by most Linuxes out there, which means that a JVM must be compatible with musl libc for supporting vanilla Alpine. The musl OpenJDK port is being developed under OpenJDK's <a href="https://openjdk.java.net/projects/portola" rel="noreferrer">Portola</a> project. </p> <p>The current status is summarized on the <a href="https://jdk.java.net/11/" rel="noreferrer">OpenJDK 11 page</a>: </p> <blockquote> <p>The Alpine Linux build previously available on this page was removed as of JDK 11 GA. It’s not production-ready because it hasn’t been tested thoroughly enough to be considered a GA build. Please use the early-access JDK 12 Alpine Linux build in its place.</p> </blockquote> <p>The only stable OpenJDK versions for Alpine currently are 7 and 8, provided by the <a href="https://icedtea.classpath.org/wiki/Main_Page" rel="noreferrer">IcedTea</a> project.</p> <p>However - if you're willing to consider other than the official OpenJDK, <a href="https://www.azul.com/downloads/zulu" rel="noreferrer">Azul's Zulu</a> OpenJDK offers a compelling alternative: </p> <ul> <li>It supports <a href="https://www.azul.com/downloads/zulu/zulu-download-alpine" rel="noreferrer">Java 11 on Alpine musl</a> (version 11.0.2 as of the time of writing);</li> <li>It is a certified OpenJDK build, verified using the OpenJDK TCK compliance suite; </li> <li>It is free, open source and docker ready (<a href="https://hub.docker.com/r/azul/zulu-openjdk-alpine" rel="noreferrer">Dockerhub</a>).</li> </ul> <p>For support availability and roadmap, see <a href="https://www.azul.com/products/azul_support_roadmap" rel="noreferrer">Azul support roadmap</a>.</p> <p><strong>Update, 3/6/19:</strong> As of yesterday, <code>openjdk11</code> is available in Alpine repositories! It could be grabbed on Alpine using:</p> <pre><code>apk --no-cache add openjdk11 </code></pre> <p>The package is based on the <code>jdk11u</code> OpenJDK branch plus ported fixes from project Portola, introduced with the following <a href="https://github.com/alpinelinux/aports/pull/6469" rel="noreferrer">PR</a>. Kudos and huge thanks to the Alpine team.</p> <blockquote> <p>Why is the unstable <em>sid</em> version used for LTS Java images?</p> </blockquote> <p>That's a fair question / request. There's actually an open ticket for providing Java 11 on a stable Debian release:<br> <a href="https://github.com/docker-library/openjdk/issues/237" rel="noreferrer">https://github.com/docker-library/openjdk/issues/237</a></p> <p><strong>Update, 26/12/18:</strong> The issue has been resolved, and now the OpenJDK 11 slim image is based on <code>stretch-backports</code> OpenJDK 11 which was recently made available (<a href="https://github.com/docker-library/openjdk/pull/259" rel="noreferrer">PR link</a>).</p> <blockquote> <p>Why is the slim/headless/JRE package for OpenJDK 11 so large compared to the similar OpenJDK 8 package? What is this <em>modules</em> file which brings 135 MB in OpenJDK 11?</p> </blockquote> <p>Java 9 introduced the module system, which is a new and improved approach for grouping packages and resources, compared to jar files. This article from Oracle gives a very detailed introduction to this feature:<br> <a href="https://www.oracle.com/corporate/features/understanding-java-9-modules.html" rel="noreferrer">https://www.oracle.com/corporate/features/understanding-java-9-modules.html</a></p> <p>The <code>modules</code> file bundles all modules shipped with the JRE. The complete list of modules could be printed with <code>java --list-modules</code>. <code>modules</code> is indeed a very large file, and as commented, it contains all standard modules, and it is therefore quite bloated.</p> <p>One thing to note however is that it replaces <code>rt.jar</code> and <code>tools.jar</code> which became deprecated, among other things, so when accounting for the size of <code>modules</code> when comparing to pre-9 OpenJDK builds, the sizes of <code>rt.jar</code> and <code>tools.jar</code> should be subtracted (they should take up some 80MB combined).</p>
55,295,593
How to convert asset image to File?
<p>Is there a way to use an asset image as a File. I need a File so it can be used for testing it over the internet using http. I've tried some answers from Stackoverflow.com (<a href="https://stackoverflow.com/questions/49835623/how-to-load-images-with-image-file">How to load images with image.file</a>) but get an error 'Cannot open file, (OS Error: No such file or directory, errno = 2)'. The attached code line also gives an error.</p> <pre><code>File f = File('images/myImage.jpg'); RaisedButton( onPressed: ()=&gt; showDialog( context: context, builder: (_) =&gt; Container(child: Image.file(f),)), child: Text('Show Image'),) </code></pre> <p>Using Image.memory widget(works)</p> <pre><code>Future&lt;Null&gt; myGetByte() async { _byteData = await rootBundle.load('images/myImage.jpg'); } /// called inside build function Future&lt;File&gt; fileByte = myGetByte(); /// Show Image Container(child: fileByte != null ? Image.memory(_byteData.buffer.asUint8List(_byteData.offsetInBytes, _ byteData.lengthInBytes)) : Text('No Image File'))), </code></pre>
55,295,810
3
1
null
2019-03-22 08:28:29.337 UTC
7
2021-03-10 16:28:34.797 UTC
2019-03-22 17:26:50.023 UTC
null
9,501,461
null
9,501,461
null
1
28
dart|flutter
38,030
<p>You can access the <em>byte data</em> via <a href="https://docs.flutter.io/flutter/services/AssetBundle-class.html" rel="noreferrer"><code>rootBundle</code></a>. Then, you can save it to the device's temporary directory which is obtained by <a href="https://pub.dartlang.org/packages/path_provider" rel="noreferrer"><code>path_provider</code></a> (you need to add it as a dependency).</p> <pre><code>import 'dart:async'; import 'dart:io'; import 'package:flutter/services.dart' show rootBundle; import 'package:path_provider/path_provider.dart'; Future&lt;File&gt; getImageFileFromAssets(String path) async { final byteData = await rootBundle.load('assets/$path'); final file = File('${(await getTemporaryDirectory()).path}/$path'); await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes)); return file; } </code></pre> <p>In your example, you would call this function like this:</p> <pre><code>File f = await getImageFileFromAssets('images/myImage.jpg'); </code></pre> <p>For more information on writing the byte data, <a href="https://stackoverflow.com/a/50121777/6509751">check out this answer</a>.</p> <p>You will need to <code>await</code> the <code>Future</code> and in order to do that, make the function <code>async</code>:</p> <pre><code>RaisedButton( onPressed: () async =&gt; showDialog( context: context, builder: (_) =&gt; Container(child: Image.file(await getImageFileFromAssets('images/myImage.jpg')))), child: Text('Show Image')); </code></pre>
7,671,654
Mercurial usage to merge multiple heads
<p>I'm mercurial newbie and want to learn how to use my <a href="http://montao.googlecode.com">repository</a>. Can you tell me how to merge my friend's work with mine? Thanks</p> <pre><code>$ hg update tip abort: crosses branches (merge branches or use --clean to discard changes) $ hg heads changeset: 265:ac5d3c3a03ac tag: tip user: roberto.cr date: Thu Oct 06 07:32:15 2011 +0000 summary: fixing "redirects" links changeset: 261:6acd1aaef950 user: niklasro date: Thu Oct 06 07:53:19 2011 +0000 summary: auth backend + js $ hg update abort: crosses branches (merge branches or use --clean to discard changes) </code></pre> <p>Could I use hg resolve?</p> <pre><code>$ hg resolve abort: no files or directories specified; use --all to remerge all file $ hg glog | more @ changeset: 266:2bf5b62720fc | tag: tip | parent: 261:6acd1aaef950 | user: niklasro | date: Thu Oct 06 12:48:20 2011 +0000 | summary: added | | o changeset: 265:ac5d3c3a03ac | | user: roberto.cr | | date: Thu Oct 06 07:32:15 2011 +0000 | | summary: fixing "redirects" links | | | o changeset: 264:2fd0bf24e90f | | user: roberto.cr | | date: Thu Oct 06 07:29:58 2011 +0000 | | summary: fixing "redirects" links | | | o changeset: 263:29a373aae81e | | user: roberto.cr | | date: Thu Oct 06 07:25:05 2011 +0000 | | summary: fixing "redirects" links | | | o changeset: 262:d75cd4d3e77a | | parent: 260:dfb54b99f84d | | user: roberto.cr | | date: Thu Oct 06 07:24:55 2011 +0000 | | summary: fixing "redirects" links | | o | changeset: 261:6acd1aaef950 |/ user: niklasro | date: Thu Oct 06 07:53:19 2011 +0000 | summary: auth backend + js | o changeset: 260:dfb54b99f84d | user: niklasro | date: Wed Oct 05 05:34:37 2011 +0000 | summary: FB buggfix example.html | o changeset: 259:92fb6b1bc492 | user: niklasro | date: Thu Sep 29 16:42:33 2011 +0000 | summary: changes </code></pre> <p>The solution was <code>hg revert -a</code> and it looks like a success now</p> <pre><code>$ hg glog | more @ changeset: 267:3b2bb6de33eb |\ tag: tip | | parent: 266:2bf5b62720fc | | parent: 265:ac5d3c3a03ac | | user: niklasro | | date: Thu Oct 06 16:06:21 2011 +0000 | | summary: merge | | | o changeset: 266:2bf5b62720fc | | parent: 261:6acd1aaef950 | | user: niklasro | | date: Thu Oct 06 12:48:20 2011 +0000 | | summary: added | | o | changeset: 265:ac5d3c3a03ac | | user: roberto.cr | | date: Thu Oct 06 07:32:15 2011 +0000 | | summary: fixing "redirects" links | | o | changeset: 264:2fd0bf24e90f | | user: roberto.cr | | date: Thu Oct 06 07:29:58 2011 +0000 | | summary: fixing "redirects" links | | o | changeset: 263:29a373aae81e | | user: roberto.cr | | date: Thu Oct 06 07:25:05 2011 +0000 | | summary: fixing "redirects" links | | o | changeset: 262:d75cd4d3e77a | | parent: 260:dfb54b99f84d | | user: roberto.cr | | date: Thu Oct 06 07:24:55 2011 +0000 | | summary: fixing "redirects" links | | | o changeset: 261:6acd1aaef950 |/ user: niklasro | date: Thu Oct 06 07:53:19 2011 +0000 | summary: auth backend + js | o changeset: 260:dfb54b99f84d | user: niklasro | date: Wed Oct 05 05:34:37 2011 +0000 | summary: FB buggfix example.html | o changeset: 259:92fb6b1bc492 | user: niklasro | date: Thu Sep 29 16:42:33 2011 +0000 | summary: changes </code></pre>
7,677,375
3
0
null
2011-10-06 08:06:59.027 UTC
6
2011-10-07 09:03:15.75 UTC
2011-10-06 16:10:35.367 UTC
null
108,207
null
108,207
null
1
13
mercurial
42,195
<p>The basic problem here is that your working directory is not clean. Mercurial prevents people from accidentally jumping between branches with uncommitted changes as this is generally a bad idea.</p> <p>Let's start with that first command:</p> <pre><code>$ hg update tip abort: crosses branches (merge branches or use --clean to discard changes) </code></pre> <p>This is telling you two important things:</p> <ul> <li>you're trying to cross branches</li> <li>you have uncommitted changes</li> </ul> <p>And that you have two options:</p> <ul> <li>merge</li> <li>use hg update --clean to lose your changes</li> </ul> <p>So what are your changes? The first step is to run 'hg status'. As you say 'hg status outputs many files prepended by 1 or ?'. Well those '1s' are actually '!' indicating deleted/missing files (get a better font!). You should doublecheck against summary, which will give you output like this:</p> <pre><code>parent: 15200:fa6f93befffa patch: use more precise pattern for diff header color styling (issue3034) branch: default commit: 1 deleted, 1 unknown (clean) &lt;- your changes update: (current) </code></pre> <p>If you try to merge at this point, you'll get a message like:</p> <pre><code>$ hg merge stable abort: outstanding uncommitted changes (use 'hg status' to list changes) </code></pre> <p>If you have changes other than missing files, you'll want to consider committing them.</p> <p>If these missing files are your only changes, it's probably ok to discard them:</p> <pre><code>hg revert -a </code></pre> <p>After you've done that, you're in a state where Mercurial will let you update or merge without complaining.</p> <p>Finally, you say "hg status output many files from other projects since it starts at .. The file I added is the only file that should get added.". This is a basic misunderstanding of how Mercurial works. Unlike CVS or SVN, <strong>there is only one project</strong> as far as Mercurial is concerned and actions (commit/update/merge/status) work on the entire project tree at once. Subdirectories are not independent projects with separate histories.</p>
7,621,832
Architecture more suitable for web apps than MVC?
<p>I've been learning Zend and its MVC application structure for my new job, and found that working with it just bothered me for reasons I couldn't quite put my finger on. Then during the course of my studies I came across articles such as <a href="http://wardley.org/computers/web/mvc.html">MVC: No Silver Bullet</a> and <a href="http://devzone.zend.com/article/12997">this podcast</a> on the topic of MVC and web applications. The guy in the podcast made a very good case against MVC as a web application architecture and nailed a lot of what was bugging me on the head. </p> <p>However, the question remains, if MVC isn't really a good fit for web applications, what is? </p>
7,622,038
4
2
null
2011-10-01 17:34:12.833 UTC
64
2013-12-16 18:05:36.3 UTC
2013-11-13 19:49:49.743 UTC
null
137,001
null
477,127
null
1
50
php|model-view-controller|web-applications|architecture
23,192
<p>It all depends on your coding style. Here's the secret: <strong>It is impossible to write classical MVC in PHP.</strong></p> <p>Any framework which claims you can is lying to you. The reality is that frameworks themselves cannot even implement MVC -- your code can. But that's not as good a marketing pitch, I guess. </p> <p>To implement a classical MVC it would require for you to have persistent Models to begin with. Additionally, Model should inform View about the changes (observer pattern), which too is impossible in your vanilla PHP page (you can do something close to classical MVC, if you use sockets, but that's impractical for real website).</p> <p>In web development you actually have 4 other MVC-inspired solutions:</p> <ul> <li><p><strong>Model2 MVC</strong>: View is requesting data from the Model and then deciding how to render it and which templates to use. Controller is responsible for changing the state of both View and Model.</p></li> <li><p><strong>MVVM</strong>: Controller is swapped out for a ViewModel, which is responsible for the translation between View's expectations and Models's logic. View requests data from controller, which translates the request so that Model can understand it. </p> <p>Most often you would use this when you have no control over either views or the model layer. </p></li> <li><p><strong>MVP</strong> (what php frameworks call "MVC"): Presenter requests information from Model, collects it, modifies it, and passes it to the passive View.</p> <p>To explore this pattern, I would recommend for you begin with <a href="http://www.wildcrest.com/Potel/Portfolio/mvp.pdf" rel="noreferrer">this publication</a>. It will explain it in detail.</p></li> <li><p><strong>HMVC</strong> (or PAC): differs from Model2 with ability of a controller to execute sub-controllers. Each with own triad of M, V and C. You gain modularity and maintainability, but pay with some hit in performance. </p></li> </ul> <p>Anyway. The bottom line is: you haven't really used MVC.</p> <p>But if you are sick of all the MVC-like structures, you can look into:</p> <ul> <li>event driven architectures</li> <li>n-Tier architecture</li> </ul> <p>And then there is always the <a href="http://en.wikipedia.org/wiki/Data,_Context_and_Interaction" rel="noreferrer">DCI</a> paradigm, but it has some issues when applied to PHP (you cannot cast to a class in PHP .. not without ugly hacks).</p>
24,392,000
Define a 'for' loop macro in C++
<p>Perhaps it is not good programming practice, but is it possible to define a <code>for</code> loop macro?</p> <p>For example,</p> <pre><code>#define loop(n) for(int ii = 0; ii &lt; n; ++ ii) </code></pre> <p>works perfectly well, but does not give you the ability to change the variable name <code>ii</code>.</p> <p>It can be used:</p> <pre><code>loop(5) { cout &lt;&lt; "hi" &lt;&lt; " " &lt;&lt; "the value of ii is:" &lt;&lt; " " &lt;&lt; ii &lt;&lt; endl; } </code></pre> <p>But there is no choice of the name/symbol <code>ii</code>.</p> <p>Is it possible to do something like this?</p> <pre><code>loop(symbol_name, n) </code></pre> <p>where the programmer inserts a symbol name into "<code>symbol_name</code>".</p> <p>Example usage:</p> <pre><code>loop(x, 10) { cout &lt;&lt; x &lt;&lt; endl; } </code></pre>
24,392,091
9
1
null
2014-06-24 16:40:57.24 UTC
10
2020-11-10 10:54:59.907 UTC
2017-05-08 19:34:02.007 UTC
null
4,642,212
null
893,254
null
1
15
c++|loops|for-loop|c-preprocessor
45,358
<pre><code>#define loop(x,n) for(int x = 0; x &lt; n; ++x) </code></pre>
8,173,217
createElement vs. createElementNS
<p>What's the real difference between those two? I mean real, essential difference. What's the future holding for regular <code>createElement</code>?</p> <p>Svg is xml, not html. I get that. So we use <code>createElementNS(ns_string, 'svg')</code> And then <code>setAttributeNS(null,,)</code>. Why? Why not <code>setAttributeNS('my_ns',,)</code>?</p> <p>Why must <code>ns_string</code> be <code>http://www.w3.org/2000/svg</code> and not some random string? What's the purpose of a namespace if there is only one namespace?</p> <p>What's the purpose of <code>ns</code> in regular html? Should I change all instances of <code>createElement</code> to <code>createElementNS</code> in my existing code?</p> <p>I am reading the <a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html">DOM-Level-2</a> spec. but I'm still puzzled.</p>
8,173,365
1
1
null
2011-11-17 19:40:36.33 UTC
30
2017-03-22 19:49:58.63 UTC
2011-11-17 21:17:11.703 UTC
null
592,746
null
352,260
null
1
73
javascript|html|dom|namespaces
31,894
<p>To understand the problem namespaces are trying to solve, consider file extensions. 3-letter file extensions have done a really bad job of describing the content of files. They're ambiguous and don't carry version info. XML namespaces use a larger space of strings, URIs, to solve the same problem, and use short prefixes so you can succinctly mix multiple kinds of XML in the same document.</p> <blockquote> <p>What's the purpose of namespace if there is only one name space?</p> </blockquote> <p>There are many namespaces used to identify different kinds of XML, and different versions of those kind.</p> <p>SVG and MathML are two kinds of XML each with their own namespaces that can be embedded in HTML5, and they often use XLink, another XML namespace. Many other XML schemas, with corresponding namespaces, are used for passing messages between clients and servers and for data storage.</p> <p>XHTML is an attempt to express HTML as valid XML. It has its own namespace.</p> <blockquote> <p>So we use createElementNS(ns_string, 'svg') And then setAttributeNS(null,,). Why? Why not setAttributeNS('my_ns',,)???</p> </blockquote> <p>You should probably try to consistently use <code>setAttributeNS</code> with a namespace URI when using <code>createElementNS</code> with a namespace URI.</p> <p>XML was defined in multiple steps. The first version of the spec said nothing about namespaces but left enough syntax so that XML with namespaces could be specified on top of XML without namespaces by using prefixes and special <code>xmlns</code> attributes. The <a href="http://www.w3.org/TR/2008/REC-xml-20081126/" rel="noreferrer">XML specification</a> says:</p> <blockquote> <p>"The Namespaces in XML Recommendation [XML Names] assigns a meaning to names containing colon characters. Therefore, authors should not use the colon in XML names except for namespace purposes, but XML processors must accept the colon as a name character."</p> </blockquote> <p>XML namespaces let XML processing applications know what they're dealing with, and allow multiple kinds of XML to be mixed together in the same document.</p> <blockquote> <p>Why ns_string must be "<a href="http://www.w3.org/2000/svg" rel="noreferrer">http://www.w3.org/2000/svg</a>"</p> </blockquote> <p>This includes the year that version of SVG was standardized, 2000, so it carries useful information.</p> <p>When used with <code>xmlns:svg</code> it also lets the browser know that the <code>svg:</code> prefix means SVG and not some other dialect of XML.</p>
21,868,857
Removing .xcuserstate and DS_Store files from git
<p>In Xcode I noticed that .DS_Store and *.xcuserstate always change and don't need to be commited. So, I wrote a .gitignore file that contains this:</p> <pre><code>.DS_Store *.xcuserstate </code></pre> <p>among other entries. Then I used:</p> <pre><code>git rm --cached *xcuserstate git rm ---cached .DS_Store </code></pre> <p>To remove the these file types already under version control. However, when I go to merge Xcode tells me that there are changes that need to be committed. Those changes include .DS_Store files and .xcuserstate files.</p> <p>So, I tried this:<a href="https://stackoverflow.com/questions/107701/how-can-i-remove-ds-store-files-from-a-git-repository">How can I Remove .DS_Store files from a Git repository?</a></p> <pre><code>find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch find . -name *.xcuserstate -print0 | xargs -0 git rm --ignore-unmatch </code></pre> <p>and I got the same result. How do I remove these files from source control for good?</p>
21,878,392
2
2
null
2014-02-19 01:01:51.173 UTC
15
2014-02-19 10:55:05.91 UTC
2017-05-23 12:26:09.657 UTC
null
-1
null
2,238,023
null
1
23
ios|xcode|git|gitignore|tree-conflict
14,437
<p>You need to commit your change after removing them from the staging area.</p> <p>As you did already, run:</p> <pre><code>$ git rm --cached path/to/.DS_Store $ git rm --cached *.xcuserstate </code></pre> <p>Note, you may have some in other directories, so you may need several invocations to get them all. At this point, your removals are staged in the index, but there's still more to do: add your <code>.gitignore</code>, and commit the final result:</p> <pre><code>$ git add .gitignore $ git commit -m "Remove and ignore .xcuserstate and .DS_Store files." </code></pre> <p>Now they'll be removed from the repository, and ignored in the future. Note: this will remove the files for other people, even though you used <code>git rm --cached</code> locally. Unfortunately, there isn't much you can do about this. Also, the files are still in your history, so depending on what you do, you may see them in other branches until things get merged and all your branches are based on something that has the new commit.</p>
49,380,052
How to avoid checking for null values in method chaining?
<p>I need to check if some value is null or not. And if its not null then just set some variable to true. There is no else statement here. I got too many condition checks like this.</p> <p>Is there any way to handle this null checks without checking all method return values?</p> <pre><code>if(country != null &amp;&amp; country.getCity() != null &amp;&amp; country.getCity().getSchool() != null &amp;&amp; country.getCity().getSchool().getStudent() != null .....) { isValid = true; } </code></pre> <p>I thought about directly checking variable and ignoring <code>NullpointerException</code>. Is this a good practice?</p> <pre><code>try{ if(country.getCity().getSchool().getStudent().getInfo().... != null) } catch(NullPointerException ex){ //dont do anything. } </code></pre>
49,380,103
6
5
null
2018-03-20 09:06:50.383 UTC
13
2021-08-06 09:26:37.663 UTC
2021-08-06 09:26:37.663 UTC
null
11,455,105
user9521067
null
null
1
53
java|exception|nullpointerexception|null
13,746
<p>No, it is generally not good practice in Java to catch a NPE instead of null-checking your references.</p> <p>You can use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html" rel="noreferrer"><code>Optional</code></a> for this kind of thing if you prefer:</p> <pre><code>if (Optional.ofNullable(country) .map(Country::getCity) .map(City::getSchool) .map(School::getStudent) .isPresent()) { isValid = true; } </code></pre> <p>or simply</p> <pre><code>boolean isValid = Optional.ofNullable(country) .map(Country::getCity) .map(City::getSchool) .map(School::getStudent) .isPresent(); </code></pre> <p>if that is all that <code>isValid</code> is supposed to be checking.</p>