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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12,220,184 | Chrome issues with display-inline for <select> <option> tags | <p>I am having an issue where I cannot get the same bit of CSS to render the same across Firefox and Chrome. Instead of a vertical select box of 24 values, they all appear in a line next to each other in Firefox:</p>
<p><img src="https://i.imgur.com/Lc6Qn.png" alt=""></p>
<p>In Chrome, they appear as a vertical multiple select box.</p>
<p>Complete code for an abbreviated 3 hour example:</p>
<pre><code><html>
<head>
<style type="text/css">
option { display: inline; }
</style>
</head>
<body>
<form>
<select id="aryHours[]" class="select_hours" size="1" multiple="multiple" name="aryHours[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</body>
</html>
</code></pre>
<p>In Chrome, the options do not display inline. </p>
<p>Any explanations why this code does/does not work and are there any other ways to achieve the same layout?</p> | 12,220,618 | 2 | 0 | null | 2012-08-31 17:43:09.103 UTC | null | 2018-01-17 22:22:42.087 UTC | 2015-01-13 17:27:42.597 UTC | null | 1,711,796 | null | 1,639,360 | null | 1 | 30 | css|html|google-chrome | 3,675 | <p>I don't think you should (can?) make <code><option></code> elements inline like that. Try using checkboxes instead. Something like <a href="http://jsfiddle.net/WVNww/" rel="nofollow">this</a>:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Inline Options</title>
<style>
ul {
list-style:none;overflow:hidden;
}
ul li {
lit-style:none;
float:left;
position:relative;
}
ul li input[type="checkbox"] {
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
width:100%;
height:100%;
opacity:0;
}
ul li input:checked + label {
background:blue;
}
</style>
</head>
<body>
<form action="#" method="get">
<ul>
<li>
<input type="checkbox" name="aryHours[]" id="checkbox1" />
<label for="checkbox1" class="">Option 1</label>
</li>
<li>
<input type="checkbox" name="aryHours[]" id="checkbox2" />
<label for="checkbox2" class="">Option 2</label>
</li>
<li>
<input type="checkbox" name="aryHours[]" id="checkbox3" />
<label for="checkbox3" class="">Option 3</label>
</li>
</ul>
</form>
</body>
</html>
</code></pre> |
12,239,006 | How do I resolve a path relative to an ASP.NET MVC 4 application root? | <p>How do I resolve paths relative to an ASP.NET MVC 4 application's root directory? That is, I want to open files belonging to the application from controller actions, referenced like <code>~/Data/data.html</code>. These paths are typically specified in <code>Web.config</code>.</p>
<p><strong>EDIT:</strong></p>
<p>By 'resolve' I mean to transform a path relative to the application's root directory to an absolute path, .e.g. <code>~/Data/data.html</code> → <code>C:\App\Data\Data.html</code>.</p> | 12,239,070 | 5 | 11 | null | 2012-09-02 19:20:58.82 UTC | 5 | 2018-06-21 15:42:42.857 UTC | 2016-01-23 22:56:03.89 UTC | null | 1,741,690 | null | 265,261 | null | 1 | 47 | c#|asp.net-mvc | 104,058 | <p>To get the absolute path use this:</p>
<pre><code>String path = HttpContext.Current.Server.MapPath("~/Data/data.html");
</code></pre>
<p>EDIT: </p>
<p>To get the Controller's Context remove <code>.Current</code> from the above line. By using <code>HttpContext</code> by itself it's easier to Test because it's based on the Controller's Context therefore more localized.</p>
<p>I realize now that I dislike how <code>Server.MapPath</code> works (internally eventually calls <code>HostingEnvironment.MapPath</code>) So I now recommend to always use <code>HostingEnvironment.MapPath</code> because its static and not dependent on the context unless of course you want that...</p> |
19,102,966 | Parallel.ForEach vs Task.Run and Task.WhenAll | <p>What are the differences between using Parallel.ForEach or Task.Run() to start a set of tasks asynchronously?</p>
<p>Version 1:</p>
<pre><code>List<string> strings = new List<string> { "s1", "s2", "s3" };
Parallel.ForEach(strings, s =>
{
DoSomething(s);
});
</code></pre>
<p>Version 2:</p>
<pre><code>List<string> strings = new List<string> { "s1", "s2", "s3" };
List<Task> Tasks = new List<Task>();
foreach (var s in strings)
{
Tasks.Add(Task.Run(() => DoSomething(s)));
}
await Task.WhenAll(Tasks);
</code></pre> | 19,103,047 | 4 | 8 | null | 2013-09-30 20:13:06.96 UTC | 79 | 2021-11-10 13:51:19.413 UTC | null | null | null | null | 1,999,917 | null | 1 | 216 | c#|async-await|parallel.foreach | 129,852 | <p>In this case, the second method will asynchronously wait for the tasks to complete instead of blocking.</p>
<p>However, there is a disadvantage to use <code>Task.Run</code> in a loop- With <code>Parallel.ForEach</code>, there is a <a href="http://msdn.microsoft.com/en-us/library/system.collections.concurrent.partitioner.aspx"><code>Partitioner</code></a> which gets created to avoid making more tasks than necessary. <code>Task.Run</code> will always make a single task per item (since you're doing this), but the <code>Parallel</code> class batches work so you create fewer tasks than total work items. This can provide significantly better overall performance, especially if the loop body has a small amount of work per item.</p>
<p>If this is the case, you can combine both options by writing:</p>
<pre><code>await Task.Run(() => Parallel.ForEach(strings, s =>
{
DoSomething(s);
}));
</code></pre>
<p>Note that this can also be written in this shorter form:</p>
<pre><code>await Task.Run(() => Parallel.ForEach(strings, DoSomething));
</code></pre> |
24,389,091 | Gradle: add dependency for a specific flavour of the library | <p>I have a library project and a application. I'd like to have 2 product flavours (<em>store</em>, <em>dev</em>) for both library and application. When I build the <em>store</em> flavour for the application I want to use the <em>store</em> flavour from the library. Also when I build the <em>dev</em> flavour for the application I want to use the <em>dev</em> flavour from the library. I tried setting the same product flavours for both library and application but it does not work. </p>
<p>Here is my configuration:</p>
<p><em>Library</em></p>
<pre><code>apply plugin: 'android-library'
android {
compileSdkVersion 19
buildToolsVersion "19.1.0"
defaultConfig {
applicationId "ro.amarkovits.graddletest.lib"
minSdkVersion 14
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors{
store{
}
dev{
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
</code></pre>
<p>and I have this files:
src/main/res/values/strings.xml
and
src/store/res/values/strings.xml</p>
<p><em>Application</em></p>
<pre><code>apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion '19.1.0'
defaultConfig {
applicationId 'ro.amarkovits.mymodule.app'
minSdkVersion 14
targetSdkVersion 19
versionCode 1
versionName '1.0'
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors{
store{
}
dev{
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':lib')
}
</code></pre>
<p>In this situation I get this error: Error:(12, 23) No resource found that matches the given name (at 'text' with value '@string/app_name'). The <em>app_name</em> is defined in <em>string.xml</em> in the library (in both <em>main</em> and <em>store</em> directory)</p>
<p>If I remove the productFlavors from the library it builds but always use the <em>values.xml</em> from the <em>main</em> directory</p> | 26,249,615 | 3 | 4 | null | 2014-06-24 14:21:17.123 UTC | 12 | 2017-11-10 07:15:58.64 UTC | 2014-07-11 18:42:04.063 UTC | null | 1,253,844 | null | 979,867 | null | 1 | 46 | android|gradle|library-project|android-productflavors | 24,208 | <p>In your library you need to tell gradle to build every time every variant:</p>
<pre><code>android {
publishNonDefault true
}
</code></pre>
<p>Then in your application, since recently I guess, you can do this:</p>
<pre><code>dependencies {
(...)
devCompile project(path: ':lib', configuration: 'devDebug') // or 'devRelease'
storeCompile project(path: ':lib', configuration: 'storeRelease') // or 'storeDebug'
}
</code></pre>
<p>Found in the official documentation under <a href="http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication" rel="noreferrer">Library Publication</a>.</p>
<p>Edit: </p>
<p>Since version <a href="http://tools.android.com/tech-docs/new-build-system" rel="noreferrer">0.14.3 (2014/11/18)</a>, you can now have Flavor-buildType-Compile directive as well:</p>
<p>In your build.gradle before the android {} scope add the following:</p>
<pre><code>configurations {
devDebugCompile
devReleaseCompile
storeDebugCompile
storeReleaseCompile
}
</code></pre>
<p>Then you can declare and use different versions of your library per Flavor-BuildType:</p>
<pre><code>dependencies {
(...)
devDebugCompile project(path: ':lib', configuration: 'devDebug')
devReleaseCompile project(path: ':lib', configuration: 'devRelease')
storeDebugCompile project(path: ':lib', configuration: 'storeDebug')
storeReleaseCompile project(path: ':lib', configuration: 'storeRelease')
}
</code></pre>
<p>Edit: </p>
<p>Dependency management between modules has changed since <strong>Android Gradle Plugin 3.0.0</strong>. It automatically tries to matches flavours between your app and the libraries/modules it depends on. </p>
<p>See the <a href="https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#variant_aware" rel="noreferrer">documentation for the whole explanation</a>!</p> |
24,011,869 | Handling a Button's Click event in XAML? | <p>This feels like a terribly basic question but I am sure there is a better way to do this. I have a <code>Button</code> in my UI which selects a specific tab and fire a <code>Command</code> from the <code>ViewModel</code></p>
<p>Here is the current code (which works fine):</p>
<p>XAML:</p>
<pre><code><Button Content="Button!" Click="OnButtonClick" Command="{Binding WhateverCommand}" />
</code></pre>
<p>Code behind:</p>
<pre><code>private void OnButtonClick(object sender, RoutedEventArgs e)
{
theTab.IsSelected = true;
}
</code></pre>
<p>Isn't there any cleaner, XAML-only way to do that UI operation? I was thinking about something like:</p>
<pre><code><Button Content="Button!" Click="OnButtonClick" Command="{Binding WhateverCommand}">
<Button.Triggers>
<EventTrigger RoutedEvent="Click">
<Setter TargetName="theTab" Property="IsSelected" Value="True" />
</EventTrigger>
</Button.Trigger>
</Button>
</code></pre>
<p>But unfortunately it seems like the <code>EventTrigger</code> won't support a <code>Click</code> event. Why so? I am still sometimes confused with triggers after a few years working in WPF, and this pretty much sums it up. When trying to build that I have an error on the <code>Setter</code> line:</p>
<pre><code>A value of type 'Setter' cannot be added to a collection or dictionary of type 'TriggerActionCollection'.
</code></pre>
<p>Thank you!</p>
<p><strong>EDIT</strong> since I was ask the XAML structure of my Window, it looks like this:</p>
<pre><code><DockPanel LastChildFill="True">
<Ribbon DockPanel.Dock="Top">
<Button Content="Button!" Click="OnButtonClick" Command="{Binding WhateverCommand}" />
</Ribbon>
<TabControl>
<TabItem x:Name="theTab" />
</TabControl>
</DockPanel>
</code></pre> | 24,012,496 | 3 | 7 | null | 2014-06-03 09:41:51.193 UTC | 6 | 2018-06-03 19:52:57.753 UTC | 2014-06-03 09:53:48.22 UTC | null | 664,237 | null | 664,237 | null | 1 | 7 | c#|wpf|xaml | 61,699 | <p>There definitely is a better way. With the help of the <code>Windows.Interactivity</code> assembly you are able to bind the event source to a singe class, containing only the associated action. With this you can almost do everything you ned. </p>
<p>The action class has to derive from TriggerAction. By overriding the <code>Invoke</code>-method you can specify the action. </p>
<p>Despite this scenario it also possible to bind the <code>EventTrigger</code> to a command (e.g. relay command), allowing a clean MMVM implementation.</p>
<pre><code>xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<Button x:Name="button">
<i:Interaction.Triggers>
<i:EventTrigger SourceName="button" EventName="Click">
<app:MyAction/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</code></pre>
<pre class="lang-vb prettyprint-override"><code>Public Class MyAction
Inherits Interactivity.TriggerAction(Of UIElement)
Protected Overrides Sub Invoke(parameter As Object)
MsgBox("Clicked")
End Sub
End Class
</code></pre>
<p>I updated the code to meet your specific requirements. The <code>TriggerAction</code> class now also contains a dependency property, which can be cound to your tab control:</p>
<pre><code><TabControl x:Name="tab"/>
<Button x:Name="button">
<i:Interaction.Triggers>
<i:EventTrigger SourceName="button" EventName="Click">
<app:MyAction Target="{Binding ElementName=tab}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</code></pre>
<pre class="lang-vb prettyprint-override"><code>Public Class MyAction
Inherits Interactivity.TriggerAction(Of UIElement)
Protected Overrides Sub Invoke(parameter As Object)
DirectCast(Target, TabControl).SelectedIndex = 0
End Sub
Shared Sub New()
_targetProperty = DependencyProperty.Register(
"Target",
GetType(UIElement),
GetType(MyAction),
New UIPropertyMetadata(Nothing))
End Sub
Private Shared _targetProperty As DependencyProperty
Public Shared ReadOnly Property TargetProperty As DependencyProperty
Get
Return _targetProperty
End Get
End Property
Property Target As UIElement
Get
Return DirectCast(GetValue(TargetProperty), UIElement)
End Get
Set(value As UIElement)
SetValue(TargetProperty, value)
End Set
End Property
End Class
</code></pre> |
3,855,919 | IOS AVAudioRecorder, How to record only when audio input present (non-silence) | <p>I'm using AVAudioRecorder to record audio from the iphone's mic but I want to discard the silence periods: start recording when detecting sound, and stop recording when next silence.</p>
<p>Can't figure out how to do that</p>
<p>Any advice?</p>
<p>Thanx!</p> | 3,863,048 | 3 | 0 | null | 2010-10-04 13:57:35.19 UTC | 14 | 2015-11-03 22:05:09.283 UTC | 2010-10-04 14:06:33.367 UTC | null | 448,386 | null | 448,386 | null | 1 | 18 | ios|avaudiorecorder | 13,525 | <p>I've found the way based on Audio Queue Services. It is alot more complicated but alot more fun too as you define your queue buffers for the incoming audio packets. </p>
<p>You need to define the callback when the buffer if full, so you have the buffer full of packets that you can process as you wish, in my case to detect silence and a few more things.</p>
<p>Later having more time ill post the solution. If anyone urged that just cant wait drop me an email and ill be glad to help.</p>
<p>Check speakhere example here: <a href="http://developer.apple.com/library/ios/#samplecode/SpeakHere/Introduction/Intro.html" rel="nofollow">http://developer.apple.com/library/ios/#samplecode/SpeakHere/Introduction/Intro.html</a></p> |
3,752,240 | Join string and None/string using optional delimiter | <p>I am basically looking for the Python equivalent to this VB/VBA string operation:</p>
<pre><code>FullName = LastName & ", " + FirstName
</code></pre>
<p>In VB/VBA <code>+</code> and <code>&</code> are both concatenation operators, but they differ in how they handle a Null value:</p>
<pre><code>"Some string" + Null ==> Null
"Some string" & Null ==> "Some string"
</code></pre>
<p>This hidden feature allows for the first line of code I wrote to include a comma and space between the required LastName and the optional FirstName values. If FirstName is Null (Null is the VB/VBA equiv of Python's None), FullName will be set to LastName with no trailing comma.</p>
<p>Is there a one-line idiomatic way to do this in Python?</p>
<p><em>Technical Note</em>:<br>
gnibbler's and eumiro's answers are not strictly the equivalent of VB/VBA's <code>+</code> and <code>&</code>. Using their approaches, if FirstName is an empty string ("") rather than None, there will be no trailing comma. In almost all cases this would be preferable to VB/VBA's result which would be to add the trailing comma with a blank FirstName.</p> | 3,752,273 | 3 | 0 | null | 2010-09-20 14:08:53.503 UTC | 6 | 2010-09-20 15:17:48.41 UTC | 2010-09-20 15:17:48.41 UTC | null | 154,439 | null | 154,439 | null | 1 | 27 | python|string | 41,698 | <pre><code>FullName = LastName + (", " + FirstName if FirstName else "")
</code></pre> |
4,007,289 | So what exactly does “from __future__ import barry_as_FLUFL” do? | <p>I understand it's an inside joke that's meant to stay (just like “<code>from __future__ import braces</code>”), but what exactly does it do?</p> | 4,007,310 | 3 | 0 | null | 2010-10-24 06:15:22.903 UTC | 12 | 2021-06-24 15:36:36.27 UTC | 2014-05-04 20:29:42.83 UTC | null | 246,246 | null | 6,899 | null | 1 | 85 | python|operators | 20,522 | <p>It's related to <a href="http://www.python.org/dev/peps/pep-0401/" rel="noreferrer">PEP 0401: BDFL Retirement</a></p>
<p>Barry refers to Barry Warsaw, a well-known Python developer. The <code>from __future__ import barry_as_FLUFL</code> basically replaces the <code>!=</code> operator with <code><></code>.</p> |
38,197,964 | Pandas: plot multiple time series DataFrame into a single plot | <p>I have the following pandas DataFrame:</p>
<pre><code> time Group blocks
0 1 A 4
1 2 A 7
2 3 A 12
3 4 A 17
4 5 A 21
5 6 A 26
6 7 A 33
7 8 A 39
8 9 A 48
9 10 A 59
.... .... ....
36 35 A 231
37 1 B 1
38 2 B 1.5
39 3 B 3
40 4 B 5
41 5 B 6
.... .... ....
911 35 Z 349
</code></pre>
<p>This is a dataframe with multiple time series-ques data, from <code>min=1</code> to <code>max=35</code>. Each <code>Group</code> has a time series like this. </p>
<p>I would like to plot each individual time series A through Z against an x-axis of 1 to 35. The y-axis would be the <code>blocks</code> at each time. </p>
<p>I was thinking of using something like an <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html" rel="noreferrer">Andrews Curves plot</a>, which would plot each series against one another. Each "hue" would be set to a different group. (Other ideas are welcome.)</p>
<p><a href="https://i.stack.imgur.com/LgHpj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LgHpj.png" alt="enter image description here"></a></p>
<p>My problem: how do you format this dataframe to plot multiple series? Should the columns be <code>GroupA</code>, <code>GroupB</code>, etc.? </p>
<p>How do you get the dataframe to be in the format:</p>
<pre><code>time GroupA blocksA GroupsB blocksB GroupsC blocksC....
</code></pre>
<p>Is this the correct format for an Andrews plot as shown? </p>
<p>EDIT</p>
<p>If I try:</p>
<pre><code>df.groupby('Group').plot(legend=False)
</code></pre>
<p>the x-axis is completely incorrect. All time series should be plotted from 0 to 35, all in one series. </p>
<p><a href="https://i.stack.imgur.com/V9xB3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V9xB3.png" alt="enter image description here"></a></p>
<p>How do I solve this? </p> | 38,198,715 | 2 | 7 | null | 2016-07-05 07:49:16.363 UTC | 3 | 2018-11-14 19:42:28.473 UTC | 2018-03-13 07:05:26.08 UTC | null | 7,390,366 | null | 4,596,596 | null | 1 | 16 | python|pandas|matplotlib|pandas-groupby | 63,350 | <p>Look at this variants. The first is Andrews' curves and the second is a multiline plot which are grouped by one column <code>Month</code>. The dataframe <code>data</code> includes three columns <code>Temperature</code>, <code>Day</code>, and <code>Month</code>:</p>
<pre><code>import pandas as pd
import statsmodels.api as sm
import matplotlib.pylab as plt
from pandas.tools.plotting import andrews_curves
data = sm.datasets.get_rdataset('airquality').data
fig, (ax1, ax2) = plt.subplots(nrows = 2, ncols = 1)
data = data[data.columns.tolist()[3:]] # use only Temp, Month, Day
# Andrews' curves
andrews_curves(data, 'Month', ax=ax1)
# multiline plot with group by
for key, grp in data.groupby(['Month']):
ax2.plot(grp['Day'], grp['Temp'], label = "Temp in {0:02d}".format(key))
plt.legend(loc='best')
plt.show()
</code></pre>
<p>When you plot Andrews' curve your data salvaged to one function. It means that Andrews' curves that are represented by functions close together suggest that the corresponding data points will also be close together. </p>
<p><a href="https://i.stack.imgur.com/DWvhu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DWvhu.png" alt="enter image description here"></a></p> |
22,493,524 | Decode HResult = -2147467259 | <p>Can someone help me decode this HResult? What does it mean? I know the negative stands for a failure. How about the rest of the 10 bits? </p>
<p>I referenced MSDN HResult article <a href="http://msdn.microsoft.com/en-us/library/cc231198.aspx" rel="noreferrer">here</a>, but I am not sure how to determine what my facility and code bits are. </p>
<p>More info: </p>
<blockquote>
<p>_message: "External component has thrown an exception."<br>
Data: {System.Collections.ListDictionaryInternal}</p>
</blockquote> | 22,493,569 | 4 | 4 | null | 2014-03-18 23:53:27.243 UTC | 14 | 2018-09-06 12:05:33.983 UTC | 2018-09-06 12:05:33.983 UTC | null | 1,671,066 | null | 2,792,608 | null | 1 | 41 | hresult | 56,966 | <p>I'll show you how to do it. Paste the negative number into Calculator (Windows) in programmer mode "Dec" setting. Then convert to "Hex" setting. You get the number: FFFFFFFF80004005. The error is 80004005 which is:</p>
<pre><code>0x80004005
E_FAIL
Unspecified
</code></pre>
<p>Unfortunately the provider of the function that gave you this error did not categorize the error.</p>
<p>Useful links:</p>
<ol>
<li><a href="http://msdn.microsoft.com/en-us/library/cc231198.aspx">MSDN - HRESULT Format</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/cc704587.aspx">MSDN - HRESULT Error List</a></li>
</ol> |
22,747,068 | Is there a max number of arguments JavaScript functions can accept? | <p>I know that JavaScript functions can accept "any" number of arguments.</p>
<pre><code>function f(){};
f(1,2,3,4 /*...*/);
</code></pre>
<p>But I'm wondering if there is actually a limit to how many "any" can be?</p>
<p>E.g., let's say I hand a million arguments to <code>f()</code>. Would that work? Or would the interpreter keel over?</p>
<p>I'm guessing the maximum is either (a) implementation-specific or (b) <code>(2^32)-1</code>, since the <code>arguments</code> object is array-like.</p>
<p>I don't see this mentioned in the language specification, but I might not be connecting some dots.</p> | 22,747,272 | 8 | 8 | null | 2014-03-30 17:12:25.363 UTC | 16 | 2020-02-24 03:41:46.037 UTC | null | null | null | null | 605,880 | null | 1 | 94 | javascript | 38,861 | <p>Although there is nothing specific limiting the <em>theoretical</em> maximum number of arguments in the spec (as <a href="https://stackoverflow.com/a/22747268/1715579"><em>thefortheye</em>'s answer</a> points out). There are of course <em>practical</em> limits. These limits are entirely implementation dependent and most likely, will also depend exactly on <em>how</em> you're calling the function. </p>
<hr>
<p>I created <a href="http://jsfiddle.net/DZn2D/" rel="noreferrer">this fiddle</a> as an experiment. </p>
<pre><code>function testArgs() {
console.log(arguments.length);
}
var argLen = 0;
for (var i = 1; i < 32; i++) {
argLen = (argLen << 1) + 1;
testArgs.apply(null, new Array(argLen));
}
</code></pre>
<p>Here are my results:</p>
<ul>
<li><p>Chrome 33.0.1750.154 m: The last successful test was <strong>65535</strong> arguments. After that it failed with:</p>
<blockquote>
<p>Uncaught RangeError: Maximum call stack size exceeded</p>
</blockquote></li>
<li><p>Firefox 27.0.1: The last successful test was <strong>262143</strong> arguments. After that it failed with:</p>
<blockquote>
<p>RangeError: arguments array passed to Function.prototype.apply is too large</p>
</blockquote></li>
<li><p>Internet Explorer 11: The last successful test was <strong>131071</strong> arguments. After that it failed with:</p>
<blockquote>
<p>RangeError: SCRIPT28: Out of stack space</p>
</blockquote></li>
<li><p>Opera 12.17: The last successful test was <strong>1048576</strong> arguments. After that it failed with:</p>
<blockquote>
<p>Error: Function.prototype.apply: argArray is too large</p>
</blockquote></li>
</ul>
<p>Of course, there may be other factors at play here and you may have different results.</p>
<hr>
<p>And here is an <a href="http://jsfiddle.net/DZn2D/3/" rel="noreferrer">alternate fiddle</a> created using <code>eval</code>. Again, you may get different results.</p>
<ul>
<li><p>Chrome 33.0.1750.154 m: The last successful test was <strong>32767</strong> arguments. After that it failed with:</p>
<blockquote>
<p>Uncaught SyntaxError: Too many arguments in function call (only 32766 allowed)</p>
</blockquote>
<p><sup>This one is particularly interesting because Chrome itself seems to be confused about how many arguments are actually allowed.</sup></p></li>
<li><p>Firefox 27.0.1: The last successful test was <strong>32767</strong> arguments. After that it failed with:</p>
<blockquote>
<p>script too large</p>
</blockquote></li>
<li><p>Internet Explorer 11: The last successful test was <strong>32767</strong> arguments. After that it failed with:</p>
<blockquote>
<p>RangeError: SCRIPT7: Out of memory</p>
</blockquote></li>
<li><p>Opera 12.17: The last successful test was <strong>4194303</strong> arguments. After that it failed with:</p>
<blockquote>
<p>Out of memory; script terminated.</p>
</blockquote></li>
</ul> |
8,487,986 | __FILE__ macro shows full path | <p>The standard predefined macro <code>__FILE__</code> available in C shows the full path to the file. Is there any way to short the path? I mean instead of</p>
<pre><code>/full/path/to/file.c
</code></pre>
<p>I see</p>
<pre><code>to/file.c
</code></pre>
<p>or </p>
<pre><code>file.c
</code></pre> | 8,488,201 | 31 | 9 | null | 2011-12-13 10:57:27.507 UTC | 64 | 2022-06-09 07:46:25.17 UTC | 2020-03-30 16:39:38.187 UTC | null | 995,714 | null | 859,227 | null | 1 | 200 | c|file|macros|path | 185,681 | <p>Try</p>
<pre><code>#include <string.h>
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
</code></pre>
<p>For Windows use '\\' instead of '/'.</p> |
26,307,577 | What's the benefit of std::back_inserter over std::inserter? | <p>As far as I can tell, anywhere <code>std::back_inserter</code> works in an STL algorithm, you could pass an <code>std::inserter</code> constructed with <code>.end()</code> instead:</p>
<pre><code>std::copy(l.begin(), l.end(), std::back_inserter(dest_list));
std::copy(l.begin(), l.end(), std::inserter(dest_list, dest_list.end()));
</code></pre>
<p>AND, unlike <code>back_inserter</code>, as far as I can tell <code>inserter</code> works for ANY STL container!! I tried it successfully for <code>std::vector</code>, <code>std::list</code>, <code>std::map</code>, <code>std::unordered_map</code> before coming here surprised.</p>
<p>I thought that maybe it's because <code>push_back</code> could be faster for some structures than <code>insert(.end())</code>, but I'm not sure...</p>
<p>That doesn't seem to be the case for <code>std::list</code> (makes sense):</p>
<pre><code>// Copying 10,000,000 element-list with std::copy. Did it twice w/ switched order just in case that matters.
Profiling complete (884.666 millis total run-time): inserter(.end())
Profiling complete (643.798 millis total run-time): back_inserter
Profiling complete (644.060 millis total run-time): back_inserter
Profiling complete (623.151 millis total run-time): inserter(.end())
</code></pre>
<p>But it does slightly for <code>std::vector</code>, though I'm not really sure why?:</p>
<pre><code>// Copying 10,000,000 element-vector with std::copy.
Profiling complete (985.754 millis total run-time): inserter(.end())
Profiling complete (746.819 millis total run-time): back_inserter
Profiling complete (745.476 millis total run-time): back_inserter
Profiling complete (739.774 millis total run-time): inserter(.end())
</code></pre>
<p>I guess in a vector there is slightly more overhead figuring out where the iterator is and then putting an element there vs just arr[count++]. Maybe it's that?</p>
<p>But still, is that the main reason?</p>
<p>My followup question, I guess, is "Is it okay to write <code>std::inserter(container, container.end())</code> for a templated function and expect it to work for (almost) any STL container?"</p>
<hr>
<p>I updated the numbers after moving to a standard compiler. Here is my compiler's details:
<br>gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) <br>
Target: x86_64-linux-gnu</p>
<p>My build command:</p>
<pre><code>g++ -O0 -std=c++11 algo_test.cc
</code></pre>
<hr>
<p>I think <a href="https://stackoverflow.com/q/23360656/751061">this question asks the second half of my question</a>, namely, "Can I write a templated function that uses <code>std::inserter(container, container.end())</code> and expect it to work for almost every container?"</p>
<p>The answer there was "Yes, for every container except for <code>std::forward_list</code>." But based on the discussion in the comments below and in <a href="https://stackoverflow.com/users/2746253/user2746253">user2746253</a>'s answer, it sounds like I should be aware that this would be slower for <code>std::vector</code> than using <code>std::back_inserter</code>...</p>
<p>Therefore, I might want to specialize my template for containers using <code>RandomAccessIterator</code>s to use <code>back_inserter</code> instead. Does that make sense? Thanks.</p> | 26,370,967 | 2 | 11 | null | 2014-10-10 20:27:59.24 UTC | 22 | 2018-01-26 03:50:43.537 UTC | 2017-07-09 09:43:58.823 UTC | null | 3,980,929 | null | 751,061 | null | 1 | 72 | c++|vector|stl|iterator|containers | 37,022 | <h2>Iterator types</h2>
<ul>
<li><code>std::back_inserter</code> returns <code>std::back_insert_iterator</code> that uses <code>Container::push_back()</code>.</li>
<li><code>std::inserter</code> returns <code>std::insert_iterator</code> that uses <code>Container::insert()</code>.</li>
</ul>
<h2>std::list</h2>
<p>For lists <code>std::list::push_back</code> is almost the same as <code>std::list::insert</code>. The only difference is that insert returns iterator to inserted element.</p>
<p>bits/stl_list.h</p>
<pre><code>void push_back(const value_type& __x)
{ this->_M_insert(end(), __x); }
void _M_insert(iterator __position, const value_type& __x)
{
_Node* __tmp = _M_create_node(__x);
__tmp->_M_hook(__position._M_node);
}
</code></pre>
<p>bits/list.tcc</p>
<pre><code>template<typename _Tp, typename _Alloc> typename list<_Tp, _Alloc>::iterator
list<_Tp, _Alloc>::insert(iterator __position, const value_type& __x)
{
_Node* __tmp = _M_create_node(__x);
__tmp->_M_hook(__position._M_node);
return iterator(__tmp);
}
</code></pre>
<h2>std::vector</h2>
<p>It looks a little different for <code>std::vector</code>. Push back checks if reallocation is needed, and if not just places value in correct place.</p>
<p>bits/stl_vector.h</p>
<pre><code>void push_back(const value_type& __x)
{
if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)
{
_Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, __x);
++this->_M_impl._M_finish;
}
else
_M_insert_aux(end(), __x);
}
</code></pre>
<p>But in <code>std::vector::insert</code> there are 3 additional things done and it impacts performance.
bits/vector.tcc</p>
<pre><code>template<typename _Tp, typename _Alloc> typename vector<_Tp, _Alloc>::iterator
vector<_Tp, _Alloc>::insert(iterator __position, const value_type& __x)
{
const size_type __n = __position - begin(); //(1)
if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage
&& __position == end()) //(2)
{
_Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, __x);
++this->_M_impl._M_finish;
}
else
{
_M_insert_aux(__position, __x);
}
return iterator(this->_M_impl._M_start + __n); //(3)
}
</code></pre> |
10,905,345 | Pressing 'enter' on a input type="text", how? | <p>I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :</p>
<pre><code> (...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "@ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="@Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
</code></pre>
<p>With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?</p>
<p>Thank you,</p> | 10,905,506 | 4 | 2 | null | 2012-06-05 21:37:06.967 UTC | 1 | 2016-01-20 20:16:45.987 UTC | null | null | null | null | 196,526 | null | 1 | 10 | javascript|jquery|html | 48,804 | <p>You should bind the keypress event to your input</p>
<pre><code>$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
</code></pre> |
11,270,288 | How do I change the Background color of a Kendo UI for MVC grid cell | <p>I'm developing an app using Kendo UI for MVC and I want to be able to change the background of a cell but I don't know how to get the value of the column cell background property so I can set it.</p>
<pre class="lang-razor prettyprint-override"><code> @(Html.Kendo().Grid(Model)
.Name("LineItems")
.Events(e=> e
.DataBound("LineItems_Databound")
)
.Columns(columns =>
{
columns.Bound(o => o.Ui).Title("UI").Width(20);
columns.Bound(o => o.QtyOrdered).Title("Qty Ord").Width(30);
columns.Bound(o => o.Nomenclature).Width(200);
columns.Bound(o => o.QtyShipped).Width(20).Title("Qty Sent");
columns.Bound(o => o.QtyReceived).Width(20).Title("Qty Rx");
columns.Bound(o => o.ReqID).Width(50);
columns.Bound(o => o.JCN_Job).Width(50).Title("Job/JCN");
columns.Bound(o => o.ManPartID).Width(100).Title("Part#");
columns.Bound(o => o.Requestor).Width(100).Title("Requestor");
})
.ToolBar(toolbar =>
{
//toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Sortable()
.Selectable()
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.ID))
.Batch(true)
.ServerOperation(false)
.Read(read => read.Action("Editing_Read", "Shipping"))
.Update(update => update.Action("UpdateShipment", "Shipping"))
//.Destroy(update => update.Action("Editing_Destroy", "Shipping"))
)
)
</code></pre>
<p>In my script I have code that loops through my grid on .databound </p>
<pre class="lang-js prettyprint-override"><code> function LineItems_Databound() {
var grid = $("#LineItems").data("kendoGrid");
var data = grid.dataSource.data();
$.each(data, function (i, row) {
var qtyRx = row.QtyReceived;
var qtySx = row.QtyShipped;
if (qtyRx < qtySx) {
// Change the background color of QtyReceived here
}
});
}
</code></pre> | 11,277,650 | 2 | 0 | null | 2012-06-29 23:49:23.89 UTC | 6 | 2018-10-15 09:31:42.557 UTC | 2018-10-15 09:31:42.557 UTC | null | 1,911,240 | null | 1,018,705 | null | 1 | 16 | kendo-ui | 40,891 | <p><strong>With Ajax Binding</strong></p>
<p>Using jquery, you can select and change the background color of a cell of the grid by using the uid (unique id) of the row and selecting the nth-child of that row.</p>
<pre class="lang-js prettyprint-override"><code>function LineItems_Databound() {
var grid = $("#LineItems").data("kendoGrid");
var data = grid.dataSource.data();
$.each(data, function (i, row) {
var qtyRx = row.QtyReceived;
var qtySx = row.QtyShipped;
if (qtyRx < qtySx) {
//Change the background color of QtyReceived here
$('tr[data-uid="' + row.uid + '"] td:nth-child(5)').css("background-color", "red");
}
});
}
</code></pre>
<p><strong>Update</strong></p>
<p><a href="https://stackoverflow.com/users/1018705/alan-fisher">Alan Fisher</a> in the comments suggested another way to solve this that he learned from the people at KendoUI. The QtyReceived column uses a ClientTemplate that passes parameters to the databound event.</p>
<pre class="lang-razor prettyprint-override"><code>@(Html.Kendo().Grid(Model)
.Name("LineItems")
.Events(e => e.DataBound("LineItems_Databound"))
.Columns(columns =>
{
columns.Bound(o => o.Ui).Title("UI").Width(20);
columns.Bound(o => o.QtyOrdered).Title("Qty Ord").Width(30);
columns.Bound(o => o.Nomenclature).Width(200);
columns.Bound(o => o.Requestor).Width(100);
columns.Bound(o => o.QtyShipped).Width(20).Title("Qty Sent");
columns.Bound(o => o.QtyReceived).Width(20).Title("Qty Rx")
.ClientTemplate("#= LineItems_Databound(QtyShipped,QtyReceived)#");
columns.Bound(o => o.ReqID).Width(50);
columns.Bound(o => o.JCN_Job).Width(50).Title("Job/JCN");
columns.Bound(o => o.ManPartID).Width(100).Title("Part#");
columns.Bound(o => o.ReceivedBy).Width(100).Title("Received By");
columns.Bound(o => o.RecAtSiteDate).Width(100).Title("Received Date")
.Format("{0:dd MMM, yy}");
})
)
<script>
function LineItems_Databound(qtySx, qtyRx) {
if (qtyRx < qtySx) {
return "<div style='background: pink'>" + qtyRx + " </div>";
}
else {
return qtyRx;
}
}
</script>
</code></pre>
<p><strong>With Server Binding</strong></p>
<p>If you are using server data binding and not ajax data binding, CellAction might be a better way to do this.</p>
<pre class="lang-razor prettyprint-override"><code>@(Html.Kendo().Grid(Model)
.Name("LineItems")
.CellAction(cell =>
{
if (cell.Column.Title.Equals("QtyReceived"))
{
if (cell.DataItem.QtyReceived.Value < cell.DataItem.QtyShipped.Value)
{
cell.HtmlAttributes["style"] = "background-color: red";
}
}
})
.Columns(columns =>
{
columns.Bound(o => o.Ui).Title("UI").Width(20);
columns.Bound(o => o.QtyOrdered).Title("Qty Ord").Width(30);
columns.Bound(o => o.Nomenclature).Width(200);
columns.Bound(o => o.QtyShipped).Width(20).Title("Qty Sent");
columns.Bound(o => o.QtyReceived).Width(20).Title("Qty Rx");
columns.Bound(o => o.ReqID).Width(50);
columns.Bound(o => o.JCN_Job).Width(50).Title("Job/JCN");
columns.Bound(o => o.ManPartID).Width(100).Title("Part#");
columns.Bound(o => o.Requestor).Width(100).Title("Requestor");
})
)
</code></pre> |
10,963,653 | What method should I use to write error messages to 'stderr' using 'printf' in a bash script? | <p>I want to direct the output of a <code>printf</code> in a <code>bash</code> script to <code>stderr</code> instead of <code>stdout</code>. </p>
<p>I am <strong>not</strong> asking about redirecting either <code>stderr</code> or <code>stdout</code> from where ever they are currently routed. I just want to be able to send the output from a <code>printf</code> to <code>stderr</code> instead of to the default of <code>stdout</code>.</p>
<p>I experimented a little and found that appending <code>1>&2</code> to the <code>printf</code>, as shown in the example below, appears to do what I want. However, I have <strong><em>no</em></strong> experience using bash. So my <em>primary</em> question is if there is a "<em>better</em>" way to do this in <code>bash</code>? </p>
<p>By "<em>better</em>" I mean is there another way to do this which is more commonly used, more conventional, or more idiomatic? How would a more experienced bash programmer do it?</p>
<pre><code>#!/bin/bash
printf "{%s} This should go to stderr.\n" "$(date)" 1>&2
printf "[(%s)] This should go to stdout.\n" "$(date)"
</code></pre>
<p>I also have a <em>secondary</em> question. I am asking it not so much because I <em>need</em> to know, but more because I am just curious and would like to have a better understanding about what is happening.</p>
<p>It seems the above will only work when it runs inside a shell script. It does not appear to work when I try it from a command line. </p>
<p>Here is an example of what I mean. </p>
<pre class="lang-none prettyprint-override"><code>irrational@VBx64:~$ printf "{%s} Sent to stderr.\n" "$(date)" 1>&2 2> errors.txt
{Sat Jun 9 14:08:46 EDT 2012} Sent to stderr.
irrational@VBx64:~$ ls -l errors.txt
-rw-rw-r-- 1 irrational irrational 0 Jun 9 14:39 errors.txt
</code></pre>
<p>I would expect the <code>printf</code> command above to have no output because the output should go to <code>stderr</code>, which in turn should go to a file. But this does not happen. Huh?</p> | 10,963,704 | 4 | 0 | null | 2012-06-09 18:48:52.197 UTC | 5 | 2017-04-17 15:17:14.74 UTC | 2017-04-17 15:17:14.74 UTC | null | 2,786,884 | null | 348,415 | null | 1 | 35 | bash|stderr|io-redirection|bash4 | 24,752 | <p>First, yes, <code>1>&2</code> is the right thing to do.</p>
<p>Second, the reason your <code>1>&2 2>errors.txt</code> example doesn't work is because of the details of exactly what redirection does.</p>
<p><code>1>&2</code> means "make filehandle 1 point to wherever filehandle 2 does currently" — i.e. stuff that would have been written to stdout now goes to stderr. <code>2>errors.txt</code> means "open a filehandle to <code>errors.txt</code> and make filehandle 2 point to it" — i.e. stuff that would have been written to stderr now goes into <code>errors.txt</code>. But filehandle 1 isn't affected at all, so stuff written to stdout still goes to stderr.</p>
<p>The correct thing to do is <code>2>errors.txt 1>&2</code>, which will make writes to both stderr and stdout go to <code>errors.txt</code>, because the first operation will be "open <code>errors.txt</code> and make stderr point to it", and the second operation will be "make stdout point to where stderr is pointing now".</p> |
11,007,552 | Git: whole file to stdout | <p>Is there a command that can take a ref and a file path, and output the full contents of the file as it was at that commit to STDOUT?</p>
<p>Eg. Something like this:</p>
<pre><code>git show-me-the-file HEAD~2 some/file | do_something_with_piped_output_here
</code></pre> | 11,007,594 | 3 | 6 | null | 2012-06-13 02:40:58.59 UTC | 4 | 2016-04-11 12:21:27.733 UTC | null | null | null | null | 31,092 | null | 1 | 46 | git | 12,985 | <p><code>git show</code></p>
<p>e.g.</p>
<p><code>git show HEAD:./<path_to_file></code></p> |
10,997,005 | What's the difference between request.remote_ip and request.ip in Rails? | <p>As the title goes, you can get the client's ip with both methods. I wonder if there is any differences. Thank you.</p>
<p>in the source code there goes</p>
<p>"/usr/local/rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.3/lib/action
_dispatch/http/request.rb" 257L, 8741C</p>
<pre><code>def ip
@ip ||= super
end
# Originating IP address, usually set by the RemoteIp middleware.
def remote_ip
@remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
end
</code></pre>
<p>but I really don't know the implications.</p> | 10,997,322 | 3 | 0 | null | 2012-06-12 12:49:34.743 UTC | 20 | 2018-02-27 12:08:31.58 UTC | 2017-03-25 07:44:58.213 UTC | null | 8,376 | null | 740,014 | null | 1 | 86 | ruby-on-rails|ruby|rack | 55,453 | <p>From source:</p>
<pre><code>module ActionDispatch
class Request < Rack::Request
# ...
def ip
@ip ||= super
end
def remote_ip
@remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
end
# ...
end
end
</code></pre>
<p>where Rack::Request looks like this</p>
<pre><code>module Rack
class Request
def ip
remote_addrs = split_ip_addresses(@env['REMOTE_ADDR'])
remote_addrs = reject_trusted_ip_addresses(remote_addrs)
return remote_addrs.first if remote_addrs.any?
forwarded_ips = split_ip_addresses(@env['HTTP_X_FORWARDED_FOR'])
if client_ip = @env['HTTP_CLIENT_IP']
# If forwarded_ips doesn't include the client_ip, it might be an
# ip spoofing attempt, so we ignore HTTP_CLIENT_IP
return client_ip if forwarded_ips.include?(client_ip)
end
return reject_trusted_ip_addresses(forwarded_ips).last || @env["REMOTE_ADDR"]
end
end
end
</code></pre>
<p>So <code>remote_ip</code> gives precedence to <code>action_dispatch.remote_ip</code>. That is being set by <code>ActionDispatch::RemoteIp</code> middleware. You can see in that middleware's source that it's checking for spoofing attacks when being called, since it's calling <code>GetIp.new</code> to set that env variable. That's needed since <code>remote_ip</code> reads the ip address even through the local proxies, as Clowerweb explains. </p> |
12,824,577 | How to search all text fields in a DB for some substring with T-SQL | <p>I have a huge schema, with several hundreds of tables and several thousands of columns. I'd know that a specific IP address is stored in this database in several places, but I'm not sure what table(s) or column(s) it is stored in. Basically, I'm trying to find everywhere that this IP address is stored in the DB so I can update it to a new value in all those places.</p>
<p>Here's my first crack at a T-SQL statement to print out the table and column name, and the value, for every text column in the database that has the substring 10.15.13 in it.</p>
<p>Now, this works, sort of. The problem is, when I execute it in Management Studio, the call to sp_executesql will actually return all the empty results from every query that returns nothing (i.e. the column doesn't have any records with that substring), and it fills the result window to its max, and then I don't actually see if anything was printed.</p>
<p>Is there a better way to write this query? Or can I run it in some different way so that it only shows me the Tables and Columns where this substring exists?</p>
<pre><code>DECLARE
@SchemaName VARCHAR(50),
@TableName VARCHAR(50),
@ColumnName VARCHAR(50);
BEGIN
DECLARE textColumns CURSOR FOR
SELECT s.Name, tab.Name, c.Name
FROM Sys.Columns c, Sys.Types t, Sys.Tables tab, Sys.Schemas s
WHERE s.schema_id = tab.schema_id AND tab.object_id = c.object_id AND c.user_type_id = t.user_type_id
AND t.Name in ('TEXT','NTEXT','VARCHAR','CHAR','NVARCHAR','NCHAR');
OPEN textColumns
FETCH NEXT FROM textColumns
INTO @SchemaName, @TableName, @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @sql NVARCHAR(MAX),
@ParamDef NVARCHAR(MAX),
@result NVARCHAR(MAX);
SET @sql = N'SELECT ' + @ColumnName + ' FROM ' + @SchemaName + '.' + @TableName + ' WHERE ' + @ColumnName + ' LIKE ''%10.15.13%''';
SET @ParamDef = N'@resultOut NVARCHAR(MAX) OUTPUT';
EXEC sp_executesql @sql, @ParamDef, @resultOut = @result OUTPUT;
PRINT 'Column = ' + @TableName + '.' + @ColumnName + ', Value = ' + @result;
FETCH NEXT FROM textColumns
INTO @SchemaName, @TableName, @ColumnName
END
CLOSE textColumns;
DEALLOCATE textColumns;
END
</code></pre>
<p>I'd like to see results something like this where it shows the table/column that the substring was found in, and the full value in that column...</p>
<pre><code>Column = SomeTable.SomeTextColumn, Value = 'https://10.15.13.210/foo'
Column = SomeTable.SomeOtherColumn, Value = '10.15.13.210'
</code></pre>
<p>etc.</p> | 12,824,933 | 3 | 3 | null | 2012-10-10 16:58:47.077 UTC | 9 | 2015-10-06 16:51:06.283 UTC | null | null | null | null | 1,246,574 | null | 1 | 17 | sql|sql-server|tsql|dynamic-sql | 30,470 | <p>You'r close. Compare yours with this example: <a href="http://www.mssqltips.com/sqlservertip/1522/searching-and-finding-a-string-value-in-all-columns-in-a-sql-server-table/">Searching and finding a string value in all columns in a SQL Server table</a></p>
<p>The above link is for searching a single table, however here is another link which includes all tables: <a href="http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm">How to search all columns of all tables in a database for a keyword?</a></p>
<p>EDIT : Just in case the link ever goes bad, here's the solution from that link...</p>
<pre><code>CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
EXEC SearchAllTables '<yourSubstringHere>'
</code></pre>
<p>Note:
As the comment suggests in the code snippet, it was tested using older versions of SQL Server. This may not work on SQL Server 2012.</p> |
12,647,154 | mysqli query results to show all rows | <p>I have the following code:</p>
<pre class="lang-php prettyprint-override"><code>include $_SERVER['DOCUMENT_ROOT'].'/include/conn.php';
$query = "SELECT title FROM news_event";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_BOTH);
$row_cnt = $result->num_rows;
$result->free();
$mysqli->close();
</code></pre>
<p>This is fine if there is only one result as I can just echo <code>$row['title']</code> but if there are lots of results, how do I get this to loop through and print every row?</p>
<p>I'm sure this is really simple but I'm just not sure what I need to search for in Google.</p>
<p>I'm looking for a <code>mysqli</code> equivalent of this:</p>
<pre class="lang-php prettyprint-override"><code>while( $row = mysql_fetch_array($result) )
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
</code></pre> | 12,647,178 | 4 | 0 | null | 2012-09-28 20:44:26.61 UTC | 3 | 2020-09-23 14:21:40.713 UTC | 2020-03-05 20:56:52.423 UTC | null | 8,108,407 | null | 457,148 | null | 1 | 17 | php|mysqli|while-loop | 85,078 | <p>Just replace it with <code>mysqli_fetch_array</code> or <code>mysqli_result::fetch_array</code> :)</p>
<pre class="lang-php prettyprint-override"><code>while( $row = $result->fetch_array() )
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
</code></pre>
<p>Almost all <code>mysql_*</code> functions have a corresponding <code>mysqli_*</code> function.</p> |
12,698,893 | Is there a way to add methods on the fly to a class using typescript? | <p>I am trying create some kind of mixin method that add methods to the prototype/class on the fly but I get errors such as </p>
<blockquote>
<p>The property 'greetName' does not exist on value of type 'Greeter'
any</p>
</blockquote>
<p>and </p>
<blockquote>
<p>The property 'greetName' does not exist on value of type 'Greeter'
any</p>
</blockquote>
<p>when I run the following code.</p>
<pre><code>class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
Greeter.prototype.greetName = function(name){
return this.greet() + ' ' + name;
}
var greeter = new Greeter('Mr');
window.alert(greeter.greetName('Name'));
</code></pre>
<p>It actually compiles to valid js and runs as expected. Is there a way to do this with out compiler warnings/errors? </p> | 16,966,860 | 6 | 2 | null | 2012-10-02 21:49:45.987 UTC | 6 | 2018-10-23 00:21:30.917 UTC | 2015-12-06 08:26:09.357 UTC | null | 4,129,551 | null | 531,940 | null | 1 | 31 | typescript | 31,646 | <p>This solution has the benefit of giving you type checking when you dynamically add a method:</p>
<pre><code>class MyClass {
start() {
}
}
var example = new MyClass();
// example.stop(); not allowed
interface MyClass {
stop(): void;
}
MyClass.prototype['stop'] = function () {
alert('Stop');
}
var stage2 = example;
stage2.stop();
</code></pre> |
13,132,214 | Free NCrunch alternative | <p>Since NCrunch has left the free market, I was looking for a similar tool for code coverage marking, and continous testing like NCrunch</p>
<p>edit: I'm using VS2012</p>
<p>update: </p>
<p>I've been using ContinuousTest for a while now, it's OK, but I think it lacks feedback when I write code. The feedback is good when I write tests, but when I break a test (while editing source code) it won't tell me that the test broke (in the margin, like it does for NCrunch). So if anyone knows other tools, I'm still listening.</p> | 13,147,929 | 7 | 1 | null | 2012-10-30 03:29:05.423 UTC | 26 | 2018-08-19 23:51:28.497 UTC | 2013-10-11 23:16:21.13 UTC | null | 505,810 | null | 505,810 | null | 1 | 97 | c#|visual-studio|code-coverage|ncrunch | 33,229 | <p>From what I've read, most people are in the same boat and are moving to <a href="https://github.com/continuoustests/ContinuousTests/" rel="noreferrer">ContinuousTests</a>. I do not think there is a perfect replacement... yet.</p>
<p>Here is a decent <a href="http://blog.diktator.org/index.php/2012/10/19/continuous-testing-mighty-moose-vs-ncrunch/" rel="noreferrer">comparison between NCrunch and ContinuousTests</a></p>
<p><strong>Update</strong></p>
<p>Upon recent usage of ContinuousTests with VS2012 I have decided to uninstall. There was too much friction to get it running. I believe it needs an update to support VS2012 properly.</p> |
61,033,599 | Initialize multiple constant class members using one function call C++ | <p>If I have two different constant members variables, which both need to be initialized based on the same function call, is there a way to do this without calling the function twice? </p>
<p>For example, a fraction class where numerator and denominator are constant.</p>
<pre><code>int gcd(int a, int b); // Greatest Common Divisor
class Fraction {
public:
// Lets say we want to initialize to a reduced fraction
Fraction(int a, int b) : numerator(a/gcd(a,b)), denominator(b/gcd(a,b))
{
}
private:
const int numerator, denominator;
};
</code></pre>
<p>This results in wasted time, as the GCD function is called twice. You could also define a new class member, <code>gcd_a_b</code>, and first assign the output of gcd to that in the initializer list, but then this would lead to wasted memory.</p>
<p>In general, is there a way to do this without wasted function calls or memory? Can you perhaps create temporary variables in an initializer list?</p> | 61,033,668 | 3 | 5 | null | 2020-04-04 19:24:47.143 UTC | 4 | 2020-11-09 21:50:48.923 UTC | 2020-07-03 16:48:52.49 UTC | null | 9,638,272 | null | 11,418,001 | null | 1 | 53 | c++|oop|constructor|constants|initializer-list | 2,767 | <blockquote>
<p>In general, is there a way to do this without wasted function calls or memory?</p>
</blockquote>
<p>Yes. This can be done with a <a href="https://en.cppreference.com/w/cpp/language/initializer_list#Delegating_constructor" rel="nofollow noreferrer"><strong>delegating constructor</strong></a>, introduced in C++11.</p>
<p>A delegating constructor is a very efficient way to acquire temporary values needed for construction before <em>any</em> member variables are initialized.</p>
<pre><code>int gcd(int a, int b); // Greatest Common Divisor
class Fraction {
public:
// Call gcd ONCE, and forward the result to another constructor.
Fraction(int a, int b) : Fraction(a,b,gcd(a,b))
{
}
private:
// This constructor is private, as it is an
// implementation detail and not part of the public interface.
Fraction(int a, int b, int g_c_d) : numerator(a/g_c_d), denominator(b/g_c_d)
{
}
const int numerator, denominator;
};
</code></pre> |
11,145,270 | How to replace an entire line in a text file by line number | <p>I have a situation where I want a bash script to replace an entire line in a file.
The line number is always the same, so that can be a hard-coded variable.</p>
<p>I'm not trying to replace some sub-string in that line, I just want to replace that line entirely with a new line.</p>
<p>Are there any bash methods for doing this (or something simple that can be thrown into a .sh script).</p> | 11,145,362 | 11 | 0 | null | 2012-06-21 19:20:43.993 UTC | 71 | 2022-01-06 09:20:14.653 UTC | 2018-04-19 21:54:27.997 UTC | null | 126,164 | null | 788,171 | null | 1 | 193 | bash|text|replace|sed | 350,707 | <p>Not the greatest, but this should work:</p>
<pre><code>sed -i 'Ns/.*/replacement-line/' file.txt
</code></pre>
<p>where <code>N</code> should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the <code>-i</code> option:</p>
<pre><code>sed 'Ns/.*/replacement-line/' file.txt > new_file.txt
</code></pre> |
16,612,365 | Migration details for DynamoDB v2 in AWS Java SDK? | <p>Has anyone made the change to the new namespaces (<code>com.amazonaws.services.dynamodbv2</code>) and interfaces for DynamoDB in the AWS Java SDK 1.4.2 (and later)? The release of Local Secondary Indices apparently necessitated breaking changes as per <a href="http://aws.amazon.com/releasenotes/Java/7912157505356585">the 1.4.2 release notes</a>.</p>
<p>Has anyone found a guide detailing what changed and what needs to happen to migrate existing code? I am trying to decide when is best to make this change for an existing code base.</p> | 16,618,235 | 2 | 0 | null | 2013-05-17 15:06:59.36 UTC | 8 | 2013-05-23 16:36:01.507 UTC | 2013-05-23 16:36:01.507 UTC | null | 43,217 | null | 43,217 | null | 1 | 14 | java|amazon-web-services|amazon-dynamodb | 5,443 | <p>The new <em>dynamodbv2</em> namespace of DynamoDB introduces the following incompatible changes (in that they are not simply additive, and require code changes to switch to the new namespace):</p>
<ul>
<li><em>HashKeyElement</em> and <em>RangeKeyElement</em> are replaced with a <em>Map<String, AttributeValue></em>. This includes the structures named <em>ExclusiveStartKey</em>, <em>LastEvaluatedKey</em>, and <em>Key</em>. The main impact on the code with this change is that now in order to call <em>GetItem</em>, for example, your code needs to know the attribute names of the primary keys, and not just the primary key values.</li>
<li>Query now uses a <em>KeyCondition</em> of type <em>Map<String, Condition></em> to specify the full query, instead of having separate <em>HashKeyValue</em> and <em>RangeKeyCondition</em> fields.</li>
<li>CreateTable input separates the attribute type definitions from the primary key definitions (and create/update/delete/describe responses match this)</li>
<li>Consumed Capacity in responses is now a structure instead of a single number, and must be asked for in the request. In Batch operations, this is returned in a separate <em>ConsumedCapacity</em> structure, instead of alongside the results. </li>
</ul>
<p>It is possible to migrate your code to the new Java API incrementally, if desired. If you plan to add functionality to your code that queries Local Secondary Indexes, or creates tables with local secondary indexes, you will need to use the new API for that part of your code. </p>
<p>If you create a table with Local Secondary Indexes with the new API, you can still use your existing code in the <em>dynamodb</em> namespace to perform all of the existing operations on that table. As an example, PutItem with the <em>dynamodb</em> namespace client will work against tables created using the <em>dynamodbv2</em> client, as well as the other way around.</p> |
16,729,023 | Maven build issue - Connection to repository refused | <p>I wish to import, change, rebuild, test and push/check-in my changes to the code available <a href="https://github.com/cloudera/seismichadoop" rel="noreferrer">in this Github repository</a></p>
<p>Currently, I do not wish to use any IDE or plug-ins for this purpose.</p>
<p>I installed Maven on my Windows machine and as proceeded as per the installation instructions as shown below :</p>
<pre><code>C:\Documents and Settings\298790\My Documents\Downloads\seismichadoop-master>mvn
-X package
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 19:21:
28+0530)
Maven home: D:\Omkar\Development\Softwares\Tools\apache-maven-3.0.5
Java version: 1.6.0_20, vendor: Sun Microsystems Inc.
Java home: C:\Program Files\Java\jdk1.6.0_20\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows xp", version: "5.1", arch: "x86", family: "windows"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from D:\Omkar\Development\Softwares\Tools\apache
-maven-3.0.5\conf\settings.xml
[DEBUG] Reading user settings from C:\Documents and Settings\298790\.m2\settings
.xml
[DEBUG] Using local repository at C:\Documents and Settings\298790\.m2\repositor
y
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10 for C:\Doc
uments and Settings\298790\.m2\repository
[INFO] Scanning for projects...
[DEBUG] Extension realms for project com.cloudera.seismic:seismic:jar:0.1.0: (no
ne)
[DEBUG] Looking up lifecyle mappings for packaging jar from ClassRealm[plexus.co
re, parent: null]
[DEBUG] === REACTOR BUILD PLAN ================================================
[DEBUG] Project: com.cloudera.seismic:seismic:jar:0.1.0
[DEBUG] Tasks: [package]
[DEBUG] Style: Regular
[DEBUG] =======================================================================
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building seismic 0.1.0
[INFO] ------------------------------------------------------------------------
[DEBUG] Lifecycle default -> [validate, initialize, generate-sources, process-so
urces, generate-resources, process-resources, compile, process-classes, generate
-test-sources, process-test-sources, generate-test-resources, process-test-resou
rces, test-compile, process-test-classes, test, prepare-package, package, pre-in
tegration-test, integration-test, post-integration-test, verify, install, deploy
]
[DEBUG] Lifecycle clean -> [pre-clean, clean, post-clean]
[DEBUG] Lifecycle site -> [pre-site, site, post-site, site-deploy]
[DEBUG] Using connector WagonRepositoryConnector with priority 0 for http://repo
.maven.apache.org/maven2
Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-
resources-plugin/2.5/maven-resources-plugin-2.5.pom
[DEBUG] Writing resolution tracking file C:\Documents and Settings\298790\.m2\re
pository\org\apache\maven\plugins\maven-resources-plugin\2.5\maven-resources-plu
gin-2.5.pom.lastUpdated
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 21.573s
[INFO] Finished at: Fri May 24 12:05:55 IST 2013
[INFO] Final Memory: 2M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its
dependencies could not be resolved: Failed to read artifact descriptor for org.
apache.maven.plugins:maven-resources-plugin:jar:2.5: Could not transfer artifact
org.apache.maven.plugins:maven-resources-plugin:pom:2.5 from/to central (http:/
/repo.maven.apache.org/maven2): Connection to http://repo.maven.apache.org refus
ed: Connection timed out: connect -> [Help 1]
org.apache.maven.plugin.PluginResolutionException: Plugin org.apache.maven.plugi
ns:maven-resources-plugin:2.5 or one of its dependencies could not be resolved:
Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-
plugin:jar:2.5
at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.re
solve(DefaultPluginDependenciesResolver.java:129)
at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getPluginD
escriptor(DefaultMavenPluginManager.java:142)
at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getMojoDes
criptor(DefaultMavenPluginManager.java:261)
at org.apache.maven.plugin.DefaultBuildPluginManager.getMojoDescriptor(D
efaultBuildPluginManager.java:185)
at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalc
ulator.setupMojoExecution(DefaultLifecycleExecutionPlanCalculator.java:152)
at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalc
ulator.setupMojoExecutions(DefaultLifecycleExecutionPlanCalculator.java:139)
at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalc
ulator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:116)
at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalc
ulator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:129)
at org.apache.maven.lifecycle.internal.BuilderCommon.resolveBuildPlan(Bu
ilderCommon.java:92)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProje
ct(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProje
ct(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBu
ild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(Lifecycl
eStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Laun
cher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.jav
a:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(La
uncher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:
352)
Caused by: org.sonatype.aether.resolution.ArtifactDescriptorException: Failed to
read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:ja
r:2.5
at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.
loadPom(DefaultArtifactDescriptorReader.java:296)
at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.
readArtifactDescriptor(DefaultArtifactDescriptorReader.java:186)
at org.sonatype.aether.impl.internal.DefaultRepositorySystem.readArtifac
tDescriptor(DefaultRepositorySystem.java:279)
at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.re
solve(DefaultPluginDependenciesResolver.java:115)
... 25 more
Caused by: org.sonatype.aether.resolution.ArtifactResolutionException: Could not
transfer artifact org.apache.maven.plugins:maven-resources-plugin:pom:2.5 from/
to central (http://repo.maven.apache.org/maven2): Connection to http://repo.mave
n.apache.org refused
at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolve(Def
aultArtifactResolver.java:538)
at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolveArti
facts(DefaultArtifactResolver.java:216)
at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolveArti
fact(DefaultArtifactResolver.java:193)
at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.
loadPom(DefaultArtifactDescriptorReader.java:281)
... 28 more
Caused by: org.sonatype.aether.transfer.ArtifactTransferException: Could not tra
nsfer artifact org.apache.maven.plugins:maven-resources-plugin:pom:2.5 from/to c
entral (http://repo.maven.apache.org/maven2): Connection to http://repo.maven.ap
ache.org refused
at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$4.wrap(W
agonRepositoryConnector.java:951)
at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$4.wrap(W
agonRepositoryConnector.java:941)
at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$GetTask.
run(WagonRepositoryConnector.java:669)
at org.sonatype.aether.util.concurrency.RunnableErrorForwarder$1.run(Run
nableErrorForwarder.java:60)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec
utor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.apache.maven.wagon.TransferFailedException: Connection to http://
repo.maven.apache.org refused
at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.fillInput
Data(AbstractHttpClientWagon.java:892)
at org.apache.maven.wagon.StreamWagon.getInputStream(StreamWagon.java:11
6)
at org.apache.maven.wagon.StreamWagon.getIfNewer(StreamWagon.java:88)
at org.apache.maven.wagon.StreamWagon.get(StreamWagon.java:61)
at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$GetTask.
run(WagonRepositoryConnector.java:601)
... 4 more
Caused by: org.apache.maven.wagon.providers.http.httpclient.conn.HttpHostConnect
Exception: Connection to http://repo.maven.apache.org refused
at org.apache.maven.wagon.providers.http.httpclient.impl.conn.DefaultCli
entConnectionOperator.openConnection(DefaultClientConnectionOperator.java:190)
at org.apache.maven.wagon.providers.http.httpclient.impl.conn.ManagedCli
entConnectionImpl.open(ManagedClientConnectionImpl.java:294)
at org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultR
equestDirector.tryConnect(DefaultRequestDirector.java:645)
at org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultR
equestDirector.execute(DefaultRequestDirector.java:480)
at org.apache.maven.wagon.providers.http.httpclient.impl.client.Abstract
HttpClient.execute(AbstractHttpClient.java:906)
at org.apache.maven.wagon.providers.http.httpclient.impl.client.Abstract
HttpClient.execute(AbstractHttpClient.java:805)
at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.execute(A
bstractHttpClientWagon.java:746)
at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.fillInput
Data(AbstractHttpClientWagon.java:886)
... 8 more
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at org.apache.maven.wagon.providers.http.httpclient.conn.scheme.PlainSoc
ketFactory.connectSocket(PlainSocketFactory.java:127)
at org.apache.maven.wagon.providers.http.httpclient.impl.conn.DefaultCli
entConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
... 15 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResoluti
onException
</code></pre>
<p>I tried to access the URL for which I'm getting the connection refused error :</p>
<pre><code>http://repo.maven.apache.org
Browsing for this directory has been disabled.
View this directory's contents on http://search.maven.org instead.
</code></pre>
<p>The pom.xml is as follows :</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cloudera.seismic</groupId>
<artifactId>seismic</artifactId>
<version>0.1.0</version>
<packaging>jar</packaging>
<name>seismic</name>
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>1.0.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.crunch</groupId>
<artifactId>crunch</artifactId>
<version>0.4.0-incubating</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven-hadoop</id>
<name>Hadoop Releases</name>
<url>https://repository.cloudera.com/content/repositories/releases/</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptors>
<descriptor>src/main/assembly/hadoop-job.xml</descriptor>
</descriptors>
<archive>
<manifest>
<mainClass>com.cloudera.seismic.segy.Main</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
</code></pre> | 16,729,906 | 1 | 1 | null | 2013-05-24 06:39:49.3 UTC | 8 | 2016-01-04 18:02:41.443 UTC | 2013-05-24 08:46:45.84 UTC | null | 395,202 | null | 1,106,134 | null | 1 | 19 | maven|github|maven-3 | 96,428 | <p>Most probably you are behind proxy.</p>
<p>Try to do a <code>telnet repo.maven.apache.org 80</code> and probably you will find it failed to connect.</p>
<p>In your settings.xml, add corresponding proxy settings to tell Maven to go through the proxy to download the artifacts</p>
<pre><code><settings>
.......
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>your_proxy_host</host>
<port>your_proxy_port</port>
<!--
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>*.yourdomain.com|*.yourOtherDomain.com</nonProxyHosts>
-->
</proxy>
</proxies>
</settings>
</code></pre> |
16,799,710 | imported maven project does not appear as java project. Shows folders | <p>I checked out the existing project source code from SVN to a folder in my system.
Then I opened eclipse. Import Project-> Existing Maven Project.</p>
<p>It imported without issues. However, Project Explorer shows it as just folders instead of packages. (Like when we create a package and then add classes to it, it shows a different icon for package root). I opened Navigator and Package Explorer as well. But they are showing them as folders as well.</p>
<p>I tried:</p>
<pre><code>mvn eclipse:clean
mvn eclipse:eclipse
</code></pre>
<p>on the root of the project. But it did not help.</p>
<p>Can anyone help on this one?</p>
<p>My folder structure:</p>
<pre><code>ecs->
ecs-ejb->
src/java/main/com/xxx
pom.xml
ecs->ear->
src/java/main/com/xxx
pom.xml
pom.xml
</code></pre> | 16,799,735 | 15 | 2 | null | 2013-05-28 19:16:44.207 UTC | 7 | 2021-11-14 00:21:41.76 UTC | 2013-05-28 21:44:25.34 UTC | null | 668,650 | null | 668,650 | null | 1 | 22 | java|eclipse|maven|package | 75,966 | <p>Try to:</p>
<ol>
<li>Right click the project->Configure->Convert to Maven Project</li>
</ol>
<p><strong>---- Edit ----</strong></p>
<p>If this doesnt work, it is likely that someone checked in their environment files into your SVN. If they checked in:</p>
<ul>
<li>.project</li>
<li>.classpath</li>
<li>.settings/</li>
</ul>
<p>They could be conflicting with your environment (different settings/plugins/versions of eclipse...). Try dropping your project, deleting the folder/files, then remove these files from SVN, and repeat your initial process. All of these files/folders will get generated during the import to eclipse.</p>
<p><strong>---- Edit 2 ----</strong></p>
<p>Per your recent edit to the question, you have a multi-module project. If you only did this on the parent project, then there is no source folder. So you wouldn't see it. You should:</p>
<ol>
<li>File->Import...</li>
<li>Choose Existing Maven Projects, Next</li>
<li>Set the Root Directory to ecs/ecs-ejb, Finish</li>
<li>Repeat for all other modules.</li>
</ol>
<p>In eclipse, each module of a multi-module maven project needs its own eclipse project.</p> |
16,856,554 | filtering an ArrayList using an object's field | <p>I have an ArrayList which is filled by Objects.</p>
<p>My object class called <code>Article</code> which has two fields ;</p>
<pre><code>public class Article {
private int codeArt;
private String desArt;
public Article(int aInt, String string) {
this.desArt = string;
this.codeArt = aInt;
}
public int getCodeArt() {return codeArt; }
public void setCodeArt(int codeArt) {this.codeArt = codeArt;}
public String getDesArt() {return desArt;}
public void setDesArt(String desArt) { this.desArt = desArt;}
}
</code></pre>
<p>I want to filter my List using the <code>desArt</code> field, and for test I used the String "test".</p>
<p>I used the Guava from google which allows me to filter an ArrayList.</p>
<p>this is the code I tried :</p>
<pre><code>private List<gestionstock.Article> listArticles = new ArrayList<>();
//Here the I've filled my ArrayList
private List<gestionstock.Article> filteredList filteredList = Lists.newArrayList(Collections2.filter(listArticles, Predicates.containsPattern("test")));
</code></pre>
<p>but this code isn't working.</p> | 16,856,736 | 6 | 4 | null | 2013-05-31 11:46:51.467 UTC | 2 | 2016-08-06 12:00:27.67 UTC | 2013-05-31 11:57:39.99 UTC | null | 1,350,869 | null | 2,417,302 | null | 1 | 22 | java|arraylist|filtering|guava | 89,852 | <p>This is normal: <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Predicates.html#containsPattern%28java.lang.String%29">Predicates.containsPattern()</a> operates on <code>CharSequence</code>s, which your <code>gestionStock.Article</code> object does not implement.</p>
<p>You need to write your own predicate:</p>
<pre><code>public final class ArticleFilter
implements Predicate<gestionstock.Article>
{
private final Pattern pattern;
public ArticleFilter(final String regex)
{
pattern = Pattern.compile(regex);
}
@Override
public boolean apply(final gestionstock.Article input)
{
return pattern.matcher(input.getDesArt()).find();
}
}
</code></pre>
<p>Then use:</p>
<pre><code> private List<gestionstock.Article> filteredList
= Lists.newArrayList(Collections2.filter(listArticles,
new ArticleFilter("test")));
</code></pre>
<p>However, this is quite some code for something which can be done in much less code using non functional programming, as demonstrated by @mgnyp...</p> |
17,095,839 | Is it possible in Java to Invoke another class' main method and return to the invoking code? | <pre><code>public class A{
public static void main(String[] args)
{
//Main code
}
}
public class B{
void someMethod()
{
String[] args={};
A.main();
System.out.println("Back to someMethod()");
}
}
</code></pre>
<p><br>
Is there any way to do this? I found a method of doing the same using reflection but that doesn't return to the invoking code either. I tried using <code>ProcessBuilder</code> to execute it in a separate process but I guess I was missing out something.</p> | 17,095,862 | 5 | 3 | null | 2013-06-13 19:55:18.09 UTC | 8 | 2016-11-08 18:00:47.987 UTC | 2013-06-13 20:05:40.8 UTC | null | 1,618,135 | null | 918,765 | null | 1 | 27 | java | 60,503 | <p>Your code already nearly does it - it's just not passing in the arguments:</p>
<pre><code>String[] args = {};
A.main(args);
</code></pre>
<p>The <code>main</code> method is only "special" in terms of it being treated as an entry point. It's otherwise a perfectly normal method which can be called from other code with no problems. Of course you may run into problems if it's written in a way which <em>expects</em> it only to be called as an entry point (e.g. if it uses <code>System.exit</code>) but from a language perspective it's fine.</p> |
16,908,186 | Python check if list items are integers? | <p>I have a list which contains numbers and letters in string format.</p>
<pre><code>mylist=['1','orange','2','3','4','apple']
</code></pre>
<p>I need to come up with a new list which only contains numbers:</p>
<pre><code>mynewlist=['1','2','3','4']
</code></pre>
<p>If I have a way to check if each item in list can be converted to Integer, I should be able to come up with what I want by doing something like this:</p>
<pre><code>for item in mylist:
if (check item can be converted to integer):
mynewlist.append(item)
</code></pre>
<p>How do I check that a string can be converted to an integer? Or is there any better way to do it?</p> | 16,908,200 | 4 | 0 | null | 2013-06-04 00:56:57.65 UTC | 11 | 2020-04-04 02:19:29.587 UTC | 2020-04-04 02:19:29.587 UTC | null | 5,225,453 | null | 2,180,836 | null | 1 | 29 | python|string|list|integer | 163,994 | <p>Try this:</p>
<pre><code>mynewlist = [s for s in mylist if s.isdigit()]
</code></pre>
<hr />
<p>From the <a href="http://docs.python.org/2/library/stdtypes.html#str.isdigit" rel="noreferrer">docs</a>:</p>
<blockquote>
<p><strong><code>str.isdigit()</code></strong></p>
<p>Return true if all characters in the string are digits and there is at least one character, false otherwise.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</blockquote>
<hr />
<p>As noted in the comments, <code>isdigit()</code> returning <code>True</code> does not necessarily indicate that the string can be parsed as an int via the <code>int()</code> function, and it returning <code>False</code> does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.</p> |
16,746,765 | Custom Info Window for Google Maps | <p>I'd like to make a custom Info Window for Google Maps for iOS like the photo below. Is it possible to extend GMSOverlay like GMSMarker, GMSPolyline, and GMSPolygon do to create custom graphics? </p>
<p><img src="https://i.stack.imgur.com/lsJKE.png" alt="enter image description here"></p> | 39,358,538 | 4 | 3 | null | 2013-05-25 05:32:04.36 UTC | 36 | 2016-09-06 22:05:24.623 UTC | null | null | null | null | 68,751 | null | 1 | 54 | google-maps-sdk-ios | 44,902 | <p>For those who's trying to add buttons to a custom view representing info window - it seems to be impossible to do, because Google Maps SDK draws it as an image or something like this. But there is a quite simple solution: </p>
<ol>
<li>You have to create a custom view with buttons and whatever you need to be displayed in your info window.</li>
<li>Add it as a subview in your <strong>mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker)</strong> method. You can set a position of a custom view by getting a coordinates of a marker tapped with a help of <strong>mapView.projection.pointForCoordinate(marker.position)</strong></li>
<li><p>Your custom view possibly has to change it position by following camera position, so you have to handle <strong>mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition)</strong> where you could easily update your custom view position.</p>
<pre><code>var infoWindow = CustomInfoView()
var activePoint : POIItem?
func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
if let poiItem = marker as? POIItem {
// Remove previously opened window if any
if activePoint != nil {
infoWindow.removeFromSuperview()
activePoint = nil
}
// Load custom view from nib or create it manually
// loadFromNib here is a custom extension of CustomInfoView
infoWindow = CustomInfoView.loadFromNib()
// Button is here
infoWindow.testButton.addTarget(self, action: #selector(self.testButtonPressed), forControlEvents: .AllTouchEvents)
infoWindow.center = mapView.projection.pointForCoordinate(poiItem.position)
activePoint = poiItem
self.view.addSubview(infoWindow)
}
return false
}
func mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition) {
if let tempPoint = activePoint {
infoWindow.center = mapView.projection.pointForCoordinate(tempPoint.position)
}
}
</code></pre></li>
</ol> |
16,627,227 | Problem HTTP error 403 in Python 3 Web Scraping | <p>I was trying to <strong>scrape</strong> a website for practice, but I kept on getting the HTTP Error 403 (does it think I'm a bot)?</p>
<p>Here is my code:</p>
<pre><code>#import requests
import urllib.request
from bs4 import BeautifulSoup
#from urllib import urlopen
import re
webpage = urllib.request.urlopen('http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1').read
findrows = re.compile('<tr class="- banding(?:On|Off)>(.*?)</tr>')
findlink = re.compile('<a href =">(.*)</a>')
row_array = re.findall(findrows, webpage)
links = re.finall(findlink, webpate)
print(len(row_array))
iterator = []
</code></pre>
<p>The error I get is:</p>
<pre><code> File "C:\Python33\lib\urllib\request.py", line 160, in urlopen
return opener.open(url, data, timeout)
File "C:\Python33\lib\urllib\request.py", line 479, in open
response = meth(req, response)
File "C:\Python33\lib\urllib\request.py", line 591, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python33\lib\urllib\request.py", line 517, in error
return self._call_chain(*args)
File "C:\Python33\lib\urllib\request.py", line 451, in _call_chain
result = func(*args)
File "C:\Python33\lib\urllib\request.py", line 599, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
</code></pre> | 16,627,277 | 11 | 0 | null | 2013-05-18 17:47:06.23 UTC | 69 | 2022-08-23 17:07:14.04 UTC | 2021-10-17 21:30:15.497 UTC | null | 1,839,439 | null | 989,359 | null | 1 | 162 | python|http|web-scraping|http-status-code-403 | 261,335 | <p>This is probably because of <code>mod_security</code> or some similar server security feature which blocks known spider/bot user agents (<code>urllib</code> uses something like <code>python urllib/3.3.0</code>, it's easily detected). Try setting a known browser user agent with:</p>
<pre><code>from urllib.request import Request, urlopen
req = Request(
url='http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1',
headers={'User-Agent': 'Mozilla/5.0'}
)
webpage = urlopen(req).read()
</code></pre>
<p>This works for me.</p>
<p>By the way, in your code you are missing the <code>()</code> after <code>.read</code> in the <code>urlopen</code> line, but I think that it's a typo.</p>
<p>TIP: since this is exercise, choose a different, non restrictive site. Maybe they are blocking <code>urllib</code> for some reason...</p> |
63,221,443 | Forgot do in do... while loop | <p>I had an annoying bug, where I forgot to write <code>do</code> in a <code>do ... while</code> loop.</p>
<pre><code>int main() {
int status=1;
/*do*/ {
status = foo();
} while (status);
}
</code></pre>
<p>Why does this still compile and run? It seems to me that the compiler should reject this as nonsensical or at least raise a warning (I have <code>-Wall</code> in my compiler options). I'm using C++11.</p>
<p>From what I could tell, the braced code runs <code>{ ... }</code> and then the programme checks the condition in the while clause ad infinitum.</p> | 63,221,475 | 3 | 6 | null | 2020-08-02 22:00:41.147 UTC | 7 | 2020-08-12 11:56:14.16 UTC | 2020-08-04 14:54:38.38 UTC | null | 9,253,414 | null | 1,014,240 | null | 1 | 61 | c++ | 6,045 | <p>I'm assuming you <em>actually</em> had <code>int status</code> <em>outside</em> of the loop body, otherwise the code <em>wouldn't</em> compile. (Not even <em>with</em> the <code>do</code> in place.)</p>
<p>With that fixed, the code you wrote is still valid without <code>do</code>, but does something differrent, as you already correctly noted. Let me rewrite it slightly to show how it is interpreted:</p>
<pre class="lang-cpp prettyprint-override"><code>int main () {
int status;
{ // anonymous braced block that just creates a new scope
status = foo();
}
while (status) {
// empty loop body
}
}
</code></pre>
<p>A stand-alone block like that <a href="https://stackoverflow.com/questions/500006/what-is-the-purpose-of-anonymous-blocks-in-c-style-languages">does have its uses</a>, for example to utilize <a href="https://en.cppreference.com/w/cpp/language/raii" rel="noreferrer">RAII</a> - it could contain a local variable with an object whose destructor frees some resource when it goes out of scope (for example a file handle), among other things.</p>
<p>The reason that the <code>while (status);</code> is the same as <code>while (status) {}</code> is because you are allowed to put either a single statement or a block, and <code>;</code> is a valid statement that does nothing.</p>
<p><sub>And writing something like <code>while (someVariable);</code> isn't even nonsensical in general (although of course in this case it is) because it is essentially a spinlock, a form of busy waiting - it would leave the loop if another processor core, some I/O component or an interrupt would modify the value of <code>someVariable</code> so that the condition is no longer fulfilled, and it would do so without any delay. You would probably not write such code on a desktop platform where "hogging CPU" is a bad thing (except in specific scenarios in kernel-mode code), but on an embedded device like a microcontroller (where your code is the only code that runs) it can be a perfectly valid way of implementing code that waits for some external change. As pointed out by Acorn in the comments, this would of course only make sense if <code>someVariable</code> were <code>volatile</code> (or otherwise non-predictable), but I'm talking about busy loops on a variable in general.</sub></p> |
4,092,325 | How to remove part of a string before a ":" in javascript? | <p>If I have a string <code>Abc: Lorem ipsum sit amet</code>, how can I use JavaScript/jQuery to remove the string before the <code>:</code> including the <code>:</code>. For example the above string will become: <code>Lorem ipsum sit amet</code>.</p> | 4,092,337 | 2 | 1 | null | 2010-11-03 22:44:43.077 UTC | 37 | 2021-08-20 17:08:49.407 UTC | 2019-10-23 20:21:46.3 UTC | user166390 | 7,552,292 | null | 182,172 | null | 1 | 165 | javascript | 220,388 | <p>There is no need for jQuery here, regular JavaScript will do:</p>
<pre><code>var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);
</code></pre>
<p>Or, the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split" rel="noreferrer"><code>.split()</code></a> and <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop" rel="noreferrer"><code>.pop()</code></a> version:</p>
<pre><code>var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();
</code></pre>
<p>Or, the regex version (several variants of this):</p>
<pre><code>var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
</code></pre> |
9,670,898 | Joining tables using foreign key | <p>I have 2 tables , employees and departments.</p>
<p>departments(id, department)</p>
<p>employees(id, department_id, name, and a bunch more here)</p>
<p>so employees.department_id is a foreign key to departments.id.</p>
<p>I need to show the table employees, but instead of department_id (showing the IDs of the departments) I need to show the actual departments name, so in place of department_id, i need to place departments.department.</p>
<p>How should I do this?</p> | 9,670,981 | 5 | 1 | null | 2012-03-12 16:24:57.44 UTC | 4 | 2018-11-29 15:36:56.55 UTC | 2018-11-29 15:36:56.55 UTC | null | 792,066 | null | 1,103,660 | null | 1 | 13 | mysql|join | 45,803 | <p>Your friend told you the truth :p</p>
<p>You just have to use a inner join between your two tables like this:</p>
<pre><code>SELECT d.name, e.name, e.email, ... FROM deparments d INNER JOIN employees e ON d.id = e.department_id.
</code></pre>
<p>You have to adapt your field to have the desired output :)</p> |
10,164,263 | How to pass two dimensional array of an unknown size to a function | <p>I want to make class library, a function which its parameter is a matrix of unknown size, and the user will create his own matrix with his own size and pass it to this function to do some operations on his matrix like this, will be the function </p>
<pre><code>calculateDeterminantOfTheMatrix( int matrix[][])
{
some Operations to do on matrix
}
</code></pre> | 10,164,304 | 6 | 4 | null | 2012-04-15 17:16:55.56 UTC | 9 | 2019-05-26 10:06:09.23 UTC | 2017-06-20 06:44:15.45 UTC | null | 898,348 | user1308378 | null | null | 1 | 18 | c++|function|pointers|matrix | 39,911 | <p>Multi-dimensional arrays are not very well supported by the built-in components of C and C++. You can pass an <code>N</code>-dimension array only when you know <code>N-1</code> dimensions at compile time:</p>
<pre><code>calculateDeterminantOfTheMatrix( int matrix[][123])
</code></pre>
<p>However, the standard library supplies <code>std::vector</code> container, that works very well for multi-dimension arrays: in your case, passing <code>vector<vector<int> > &matrix</code> would be the proper way of dealing with the task in C++.</p>
<pre><code>int calculateDeterminantOfTheMatrix(vector<vector<int> > &matrix) {
int res = 0;
for (int i = 0 ; i != matrix.size() ; i++)
for(int j = 0 ; j != matrix[i].size() ; j++)
res += matrix[i][j];
return res;
}
</code></pre>
<p>As an added bonus, you wouldn't need to pass dimensions of the matrix to the function: <code>matrix.size()</code> represents the first dimension, and <code>matrix[0].size()</code> represents the second dimension.</p> |
9,719,693 | exposing operations on resources RESTfully - overloaded POST vs. PUT vs. controller resources | <p>Say you've got a Person resource, and part of its representation includes a Location value which can have values like "at home", "at school" and "at work". How would you RESTfully expose activities like "go home", "go to work", "go to school", etc? For the sake of discussion, let's stipulate that these activities take time, so they are executed asynchronously, and there are various ways in which they could fail (no means of transportation available, transportation breakdown during travel, other act of God, etc.). In addition, the Person resource has other attributes and associated operations that affect those attributes (e.g. attribute=energy-level, operations=eat/sleep/excercise).</p>
<p><strong>Option 1</strong>: Overload POST on the Person resource, providing an input parameter indicating what you want the person to do (e.g. action=go-to-school). Return a 202 from the POST and expose activity-in-progress status attributes within the Person's representation that the client can GET to observe progress and success/failure.</p>
<p><em>Benefits:</em> keeps it simple.</p>
<p><em>Drawbacks:</em> amounts to tunneling. The action taking place is buried in the payload instead of being visible in the URI, verb, headers, etc. The POST verb on this resource doesn't have a single semantic meaning.</p>
<p><strong>Option 2</strong>: Use PUT to set the Person's location to the state you'd like them to have. Return a 202 from the PUT and expose activity-in-progress attributes for status polling via GET.</p>
<p><em>Benefits</em>: Not sure I see any.</p>
<p><em>Drawbacks</em>: really, this is just tunneling with another verb. Also, it doesn't work in some cases (both sleeping and eating increase energy-level, so PUTting the energy-level to a higher value is ambiguous in terms of what action you want the resource to perform).</p>
<p><strong>Option 3</strong>: expose a generic controller resource that operates on Person objects. For example, create a PersonActivityManager resource that accepts POST requests with arguments that identify the target Person and requested action. The POST could return a PersonActivity resource to represent the activity in progress, which the client could GET to monitor progress and success/failure.</p>
<p><em>Benefits</em>: Seems a bit cleaner by separating the activity and its status from the Person resource.</p>
<p><em>Drawbacks</em>: Now we've moved the tunneling to the PersonActivityManager resource.</p>
<p><strong>Option 4</strong>:
Establish separate controller resources for each supported action, e.g. a ToWorkTransporter resource that accepts POST requests with an argument (or URI element) that identifies the Person, plus a ToHomeTransporter, a ToSchoolTransporter, a MealServer, a Sleeper, and an Exerciser. Each of these returns an appropriate task-monitoring resource (Commute, Meal, Slumber, Workout) from their POST method, which the client can monitor via GET.</p>
<p><em>Benefits</em>: OK, we've finally eliminated tunneling. Each POST means only one thing.</p>
<p><em>Drawbacks</em>: Now were talking about a lot of resources (maybe we could combine the transporters into one Transporter that accepts a destination argument). And some of them are pretty semantically contrived (a Sleeper?). It may be more RESTful, but is it practical?</p> | 9,804,930 | 1 | 2 | null | 2012-03-15 12:28:51.063 UTC | 8 | 2012-03-21 12:47:46.567 UTC | 2012-03-15 13:38:14.093 UTC | null | 781,332 | null | 781,332 | null | 1 | 19 | rest | 4,537 | <p>OK, I've been researching and pondering this for about a week now. Since nobody else has answered, I'll post the results of what I've learned.</p>
<p>Tim Bray, in <a href="http://www.tbray.org/ongoing/When/200x/2009/03/20/Rest-Casuistry">RESTful Casuistry</a>, talks about PUT-ing a state field vs POST-ing to a controller which will perform an operation affecting that state. He uses the example of a VM and how to RESTfully expose the function of a "reboot button". He says </p>
<blockquote>
<p>"If I want to update some fields in an existing resource, I’m inclined
to think about PUT. But that doesn’t work because it’s supposed to be
idempotent, and rebooting a server sure isn’t. Well, OK, do it with
POST I guess; no biggie.</p>
<p>But you’re not really changing a state, you’re requesting a specific
set of actions to happen, as a result of which the state may or may
not attain the desired value. In fact, when you hit the deploy switch,
the state changes to deploying and then after some unpredictable
amount of time to deployed. And the reboot operation is the classic
case of a box with a big red switch on the side; the problem is how to
push the switch.</p>
<p>So, the more I think of it, the more I think that these resources are
like buttons, with only one defined operation: push. People have been
whining about “write-only resources” but I don’t have a problem with
that because it seems accurate. The reboot and halt buttons don’t
really have any state, so you shouldn’t expect anything useful from a
GET."</p>
</blockquote>
<p>Tim seems to settle somewhere between my #3 and #4 option, exposing multiple controller resources, but pulling back from "going overboard" and having separate controller resources for everything. </p>
<p>Tim's post led to another by Roy Fielding (<a href="http://roy.gbiv.com/untangled/2009/it-is-okay-to-use-post">It is OK to use POST</a>) in which he says that for situations where there is a monitorable entity state, and an action to potentially change that state, he's inclined to use POST rather than PUT. In response to a commenter's suggestion to expose the monitored state as a separate PUT-able resource, he says </p>
<blockquote>
<p>"we only use PUT when the update action is idempotent and the
representation is complete. I think we should define an additional
resource whenever we think that resource might be useful to others in
isolation, and make use of the GET/PUT methods for that resource, but
I don’t think we should define new resources just for the sake of
avoiding POST."</p>
</blockquote>
<p>Finally, Bill de hOra, in <a href="http://www.dehora.net/journal/2009/02/03/just-use-post/">Just use POST</a> discusses the specific case of using PUT vs. POST to update the state of a collection resource, and the tradeoffs therein.</p> |
10,243,374 | textview cutting off a letter in android | <p><img src="https://i.stack.imgur.com/OGzWG.png" alt="http://dl.dropbox.com/u/24856/Screenshots/android/cutoff.png"></p>
<p>this is a screen shot from my android. the text is "asd". however the "d" is slightly cut off. here is the relevant view:</p>
<pre><code> <TextView
android:id="@+id/stuff"
android:padding="2dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/other_stuff"
android:layout_marginTop="33dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="italic" />
</code></pre>
<p>any idea as to what is causing this ?</p> | 10,407,290 | 13 | 3 | null | 2012-04-20 09:15:51.517 UTC | 2 | 2022-08-05 08:05:04.097 UTC | null | null | null | null | 211,983 | null | 1 | 28 | android | 15,278 | <p>ended up with a hacky solution which is adding a white space after the last italicized character</p> |
10,062,317 | Iterating through an object hashtable | <p>I am trying to use a hashtable so I can select a specific object stored in an array/object. However, I am having a problem looping through an object.</p>
<pre><code>var pins= {};
pins[6] = '6';
pins[7] = '7';
pins[8] = '8';
$('#result3').append('<div>Size: ' + Object.size(pins) + '</div>');
for(var i = 0; i < Object.size(pins); i++) {
$('#result3').append('<div>' + pins[i] + '</div>');
}
</code></pre>
<p><strong>JSFiddle</strong>: <a href="http://jsfiddle.net/7TrSU/" rel="noreferrer">http://jsfiddle.net/7TrSU/</a></p>
<p>As you can see in <code>TEST 3</code> which uses object <code>pin</code> to store the data, I am getting <code>undefined</code> when looping through the object <code>pin</code>. </p>
<p>What is the correct way for looping through <code>pin</code>?</p>
<p><strong>EDIT</strong></p>
<p>What happens if instead of just <code>pin[6] = '6'</code>, I make pin[6] = an object and I want to loop through the all their <code>id</code> properties? Actual code snippet of what I'm doing...</p>
<pre><code>for(var i = 0; i < json.length; i++) {
markerId = json[i].listing_id
// Place markers on map
var latLng = new google.maps.LatLng(json[i].lat, json[i].lng);
var marker = new google.maps.Marker({
listing_id: markerId,
position: latLng,
icon: base_url + 'images/template/markers/listing.png',
});
markers[markerId] = marker;
}
for(var marker in markers) {
console.log('marker ID: ' + marker.listing_id);
mc.addMarker(marker);
}
</code></pre>
<p>The <code>console.log</code> above returns undefined, and if I do <code>console.log(marker)</code> instead, I get the value of <code>marker.listing_id</code>. Sorry I'm getting confused! </p>
<p>I managed to get it to work with <code>$.each(markers, function(i, marker){});</code> but why does the <code>for..in</code> above not work?</p> | 10,062,336 | 6 | 5 | null | 2012-04-08 11:06:15.65 UTC | 7 | 2012-04-08 11:56:44.2 UTC | 2012-04-08 11:44:06.69 UTC | null | 741,099 | null | 741,099 | null | 1 | 52 | javascript|hashtable | 82,826 | <p>Don't use a <code>for(i=0; i<size; i++)</code> loop. Instead, use:</p>
<ol>
<li><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer"><code>Object.keys(pins)</code></a> to get a list of properties, and loop through it, or</li>
<li>Use a <code>for ( key_name in pins)</code> in conjunction with <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/HasOwnProperty" rel="noreferrer"><code>Object.hasOwnProperty</code></a> (to exclude inherit properties) to loop through the properties.</li>
</ol>
<p>The problem of your third test case is that it reads the values of keys 0, 1 and 2 (instead of 6, 7, 8).</p> |
10,081,728 | add request header on backbone | <p>My server has a manual authorization. I need to put the username/password of my server to my backbone request inorder for it to go through. How may i do this? Any ideas? Thank you</p> | 10,082,699 | 10 | 0 | null | 2012-04-10 00:54:02.713 UTC | 25 | 2019-03-21 13:58:58.853 UTC | null | null | null | null | 1,212,802 | null | 1 | 53 | jquery|backbone.js | 44,541 | <p>Models in Backbone retrieve, update, and destroy data using the methods <code>fetch</code>, <code>save</code>, and <code>destroy</code>. These methods delegate the actual request portion to Backbone.sync. Under the hood, all <code>Backbone.sync</code> is doing is creating an ajax request using jQuery. In order to incorporate your Basic HTTP authentication you have a couple of options.</p>
<p><code>fetch</code>, <code>save</code>, and <code>destroy</code> all accept an additional parameter <code>[options]</code>. These <code>[options]</code> are simply a dictionary of jQuery request options that get included into jQuery ajax call that is made. This means you can easily define a simple method which appends the authentication:</p>
<pre><code>sendAuthentication = function (xhr) {
var user = "myusername";// your actual username
var pass = "mypassword";// your actual password
var token = user.concat(":", pass);
xhr.setRequestHeader('Authorization', ("Basic ".concat(btoa(token))));
}
</code></pre>
<p>And include it in each <code>fetch</code>, <code>save</code>, and <code>destroy</code> call you make. Like so:</p>
<pre><code> fetch({
beforeSend: sendAuthentication
});
</code></pre>
<p>This can create quite a bit of repetition. Another option could be to override the <code>Backbone.sync</code> method, copy the original code and just include the <code>beforeSend</code> option into each jQuery ajax request that is made.</p>
<p>Hope this helps!</p> |
57,789,565 | Google Cloud Run - Domain Mapping stuck at Certificate Provisioning | <p>Is anyone getting this issue with Google Cloud Run Domain Mapping? When I add a custom domain to my domain mappings, I get this:</p>
<blockquote>
<p>Waiting for certificate provisioning. You must configure your DNS records for certificate issuance to begin.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/Z2i9q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Z2i9q.png" alt="enter image description here"></a></p>
<p>I know it says it's only added 1 day ago and I should give it time, but I actually let it go for 5 days, deleted it, and this is my second try.</p>
<p>You can see in the below screenshot that it is added via Cloudflare. I even tried toggling the Proxy service on and off with no luck.</p>
<p><a href="https://i.stack.imgur.com/J3Yup.png" rel="noreferrer"><img src="https://i.stack.imgur.com/J3Yup.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/pCuW1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pCuW1.png" alt="enter image description here"></a></p> | 58,526,972 | 8 | 10 | null | 2019-09-04 13:33:26.183 UTC | 2 | 2022-08-17 00:04:40.487 UTC | 2020-03-25 23:09:44.637 UTC | null | 472,495 | null | 2,761,425 | null | 1 | 47 | google-cloud-platform|google-cloud-run | 9,403 | <p>I just tried Toggling the proxy off again it seemed to work. They must have fixed something internally.</p> |
10,234,201 | AppEngine Error [ java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal ] | <p>i was looking to find a solution for this problem but seems difficult. I have appengine project working with a servlet that handle registration. When i try to call this servlet i have this log report:</p>
<pre><code>012-04-19 10:31:06.816 /register 500 90ms 0kb Apache-HttpClient/UNAVAILABLE (java 1.4)
ip - gecodroidtest [19/Apr/2012:10:31:06 -0700] "POST /register HTTP/1.1" 500 0 - "Apache-HttpClient/UNAVAILABLE (java 1.4)" "cloudnotifyit.appspot.com" ms=90 cpu_ms=58 api_cpu_ms=0 cpm_usd=0.001738 instance=00c61b117c772731eb45290bfcb07750c0505f
W 2012-04-19 10:31:06.794
com.cloudnotify.server.servlet.RequestInfo processRequest: xxxxxxxxxxxx@xxxx //just for me
W 2012-04-19 10:31:06.810
Error for /register
java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal
at com.google.appengine.runtime.Request.process-240c2ffe1bf8ddba(Request.java)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at org.apache.xerces.parsers.AbstractDOMParser.startDocument(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.startDocument(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl.startEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.startDocumentParsing(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)
at javax.jdo.JDOHelper.readNamedPMFProperties(JDOHelper.java:1407)
at javax.jdo.JDOHelper.getNamedPMFProperties(JDOHelper.java:1286)
at javax.jdo.JDOHelper.getPropertiesFromJdoconfig(JDOHelper.java:1232)
at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:1079)
at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:914)
at com.cloudnotify.server.c2dm.C2DMessaging.getPMF(C2DMessaging.java:103)
at com.cloudnotify.server.servlet.RequestInfo.initDevices(RequestInfo.java:225)
at com.cloudnotify.server.servlet.RequestInfo.processRequest(RequestInfo.java:183)
at com.cloudnotify.server.servlet.RegisterServlet.doPost(RegisterServlet.java:100)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:449)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:455)
at com.google.tracing.TraceContext.runInContext(TraceContext.java:695)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:333)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:325)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:453)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ElementTraversal
at com.google.appengine.runtime.Request.process-240c2ffe1bf8ddba(Request.java)
... 44 more
C 2012-04-19 10:31:06.812
Uncaught exception from servlet
java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal
at com.google.appengine.runtime.Request.process-240c2ffe1bf8ddba(Request.java)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at org.apache.xerces.parsers.AbstractDOMParser.startDocument(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.startDocument(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl.startEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.startDocumentParsing(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)
at javax.jdo.JDOHelper.readNamedPMFProperties(JDOHelper.java:1407)
at javax.jdo.JDOHelper.getNamedPMFProperties(JDOHelper.java:1286)
at javax.jdo.JDOHelper.getPropertiesFromJdoconfig(JDOHelper.java:1232)
at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:1079)
at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:914)
at com.cloudnotify.server.c2dm.C2DMessaging.getPMF(C2DMessaging.java:103)
at com.cloudnotify.server.servlet.RequestInfo.initDevices(RequestInfo.java:225)
at com.cloudnotify.server.servlet.RequestInfo.processRequest(RequestInfo.java:183)
at com.cloudnotify.server.servlet.RegisterServlet.doPost(RegisterServlet.java:100)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:449)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:455)
at com.google.tracing.TraceContext.runInContext(TraceContext.java:695)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:333)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:325)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:453)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ElementTraversal
at com.google.appengine.runtime.Request.process-240c2ffe1bf8ddba(Request.java)
... 44 more
Thanks all
</code></pre> | 10,235,196 | 3 | 1 | null | 2012-04-19 18:13:01.773 UTC | 7 | 2018-05-08 09:38:13.477 UTC | null | null | null | null | 1,344,683 | null | 1 | 61 | google-app-engine | 85,199 | <p>There may be some existing issue with the Xerces parser on GAE. See <a href="http://code.google.com/p/googleappengine/issues/detail?id=1367" rel="noreferrer">http://code.google.com/p/googleappengine/issues/detail?id=1367</a> </p>
<p>Maybe the workaround is to ensure that all of Xerces jars (including xml-apis.jar) are in your WEB-INF/lib.</p> |
9,890,049 | Query to list all users of a certain group | <p>How can I use a a search filter to display users of a specific group?</p>
<p>I've tried the following:</p>
<pre><code>(&
(objectCategory=user)
(memberOf=MyCustomGroup)
)
</code></pre>
<p>and this:</p>
<pre><code>(&
(objectCategory=user)
(memberOf=cn=SingleSignOn,ou=Groups,dc=tis,dc=eg,dc=ddd,DC=com)
)
</code></pre>
<p>but neither display users of a specific group.</p> | 9,890,107 | 4 | 0 | null | 2012-03-27 13:01:18.243 UTC | 22 | 2021-05-05 19:20:39.737 UTC | 2019-05-30 20:29:36.613 UTC | null | 270,348 | null | 484,703 | null | 1 | 83 | active-directory|ldap|ldap-query | 366,407 | <p>memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:</p>
<pre><code>(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))
</code></pre>
<p>If you don't yet have the distinguished name, you can search for it with:</p>
<pre><code>(&(objectCategory=group)(cn=myCustomGroup))
</code></pre>
<p>and return the attribute <code>distinguishedName</code>. Case may matter.</p> |
10,209,427 | Subtract 7 days from current date | <p>It seems that I can't subtract 7 days from the current date. This is how i am doing it:</p>
<pre><code>NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-7];
NSDate *sevenDaysAgo = [gregorian dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
</code></pre>
<p>SevenDaysAgo gets the same value as the current date.</p>
<p>Please help.</p>
<p>EDIT: In my code I forgot to replace the variable which gets the current date with the right one. So above code is functional.</p> | 10,209,490 | 12 | 2 | null | 2012-04-18 12:32:08.79 UTC | 27 | 2021-11-25 05:46:52.623 UTC | 2012-04-18 19:47:07.557 UTC | null | 282,045 | null | 282,045 | null | 1 | 132 | objective-c|ios|nsdate | 79,981 | <p>use dateByAddingTimeInterval method:</p>
<pre><code>NSDate *now = [NSDate date];
NSDate *sevenDaysAgo = [now dateByAddingTimeInterval:-7*24*60*60];
NSLog(@"7 days ago: %@", sevenDaysAgo);
</code></pre>
<p>output:</p>
<pre><code>7 days ago: 2012-04-11 11:35:38 +0000
</code></pre>
<p>Hope it helps</p> |
10,183,370 | What's the difference between Ruby's dup and clone methods? | <p>The <a href="http://www.ruby-doc.org/core-2.0/Object.html#method-i-dup" rel="noreferrer">Ruby docs for <code>dup</code></a> say:</p>
<blockquote>
<p>In general, <code>clone</code> and <code>dup</code> may have different semantics in descendent classes. While <code>clone</code> is used to duplicate an object, including its internal state, <code>dup</code> typically uses the class of the descendent object to create the new instance.</p>
</blockquote>
<p>But when I do some test I found they are actually the same:</p>
<pre><code>class Test
attr_accessor :x
end
x = Test.new
x.x = 7
y = x.dup
z = x.clone
y.x => 7
z.x => 7
</code></pre>
<p>So what are the differences between the two methods?</p> | 10,183,477 | 6 | 2 | null | 2012-04-17 00:08:28.927 UTC | 65 | 2019-02-06 17:26:50.373 UTC | 2013-07-14 16:24:02.65 UTC | null | 211,563 | null | 1,337,500 | null | 1 | 234 | ruby|clone|dup | 94,974 | <p>Subclasses may override these methods to provide different semantics. In <code>Object</code> itself, there are two key differences.</p>
<p>First, <code>clone</code> copies the singleton class, while <code>dup</code> does not.</p>
<pre><code>o = Object.new
def o.foo
42
end
o.dup.foo # raises NoMethodError
o.clone.foo # returns 42
</code></pre>
<p>Second, <code>clone</code> preserves the frozen state, while <code>dup</code> does not.</p>
<pre><code>class Foo
attr_accessor :bar
end
o = Foo.new
o.freeze
o.dup.bar = 10 # succeeds
o.clone.bar = 10 # raises RuntimeError
</code></pre>
<p>The <a href="https://github.com/rubinius/rubinius/blob/master/kernel/alpha.rb#L189" rel="noreferrer">Rubinius implementation for these methods</a>
is often my source for answers to these questions, since it is quite clear, and a fairly compliant Ruby implementation.</p> |
8,193,672 | Difference between using @OneToMany and @ManyToMany | <p>I am having some trouble understanding the difference between <code>@OneToMany</code> and <code>@ManyToMany</code>. When I use <code>@OneToMany</code> it defaults to create a JoinTable and if you add the mappedBy attribute you will have bidirectional relationship between two entities. </p>
<p>I have a <code>Question</code> that may belong to many <code>Categories</code>, and one <code>Category</code> may belong to many <code>Questions</code>. I don't understand if I should use <code>@ManyToMany</code> or <code>@OneToMany</code> because for me it seems exactly the same thing, but it is probably not. </p>
<p>Could somebody explain it?</p> | 8,193,879 | 3 | 0 | null | 2011-11-19 11:18:43.88 UTC | 8 | 2011-11-19 12:06:51.963 UTC | 2011-11-19 11:46:24.89 UTC | null | 920,607 | null | 454,049 | null | 1 | 15 | java|jakarta-ee|jpa | 10,457 | <p>Well, the difference is in the design you're trying to reflect using objects.</p>
<p>In your case, every <code>Question</code> can be assigned to multiple <code>Categories</code> - so that's a sign of <code>@*ToMany</code> relationship. Now you have to decide if: </p>
<ul>
<li>each <code>Category</code> can have only one <code>Question</code> assigned to it (it will result in a <strong>unique</strong> constraint which means that <strong>no other Category can refer the same Question</strong>) - this will be <code>@OneToMany</code> relationship,</li>
<li>each <code>Category</code> can have multiple <code>Questions</code> assigned to it (there will be no unique constraint in the <code>Category</code> table) - this will be <code>@ManyToMany</code> relationship.</li>
</ul>
<p><strong>@OneToMany (Question -> Category)</strong></p>
<p>This relationship can be represented by join table only if you explicitly define so using <code>@JoinTable</code> or when it is a <strong>unidirectional</strong> relationship in which the owning side is the 'One' side (it means that in the <code>Question</code> entity you have a collection of <code>Categories</code>, but in the <code>Categories</code> you don't have any reference to the <code>Question</code>).</p>
<p>If you think about it, it seems quite reasonable that the join table is used. There is no other way the DBMS could save a connection between one row in <code>Question</code> table with multiple rows in <code>Categories</code> table.</p>
<p>However, if you would like to model a bidirectional relationship you need to specify that the <code>Category</code> ('Many' side) is the owning side of the relationship. In this case the DBMS can create a join column with foreign key in the <code>Category</code> table because each <code>Category</code> row can be connected with only one <code>Question</code>.</p>
<p>In this way you don't have any join table but simple foreign keys (still, as pointed at the beginning, you can force to create the join table using <code>@JoinTable</code>).</p>
<p><strong>@ManyToMany</strong></p>
<p>This relationship must be represented as a join table. It basically works very similar to the unidirectional <code>@OneToMany</code> relationship, but in this case you may have multiple rows from <code>Question</code> joined with multiple rows from <code>Categories</code>.</p> |
11,979,788 | ARM assembly loop | <pre><code>for (int i = 0; i < 10000; i++)
a[i] = b[i] + c[i]
</code></pre>
<p>What does the ARM assembly for this high level language look like? </p>
<p>Edit:
I'm also assuming the base address of A is in R8, the base
address of B is in R9, and the base address of C is in R10
and A,B,C are all int arrays</p>
<p>Much appreciated</p>
<p>I tried:</p>
<pre><code>MOV R0, #0 ; Init r0 (i = 0)
Loop:
a[i] = b[i] + c[i] //How to fix this?
ADD R0, R0, #1 ;Increment it
CMP R0, #1000 ;Check the limit
BLE Loop ;Loop if not finished
</code></pre> | 11,982,051 | 4 | 3 | null | 2012-08-16 02:09:31.153 UTC | 2 | 2012-08-16 09:15:57.583 UTC | 2012-08-16 02:32:47.063 UTC | null | 1,042,688 | null | 1,042,688 | null | 1 | 5 | assembly|for-loop|arm | 58,018 | <p>Assuming this high level language doesn't have anything conflicting with C, you can use an arm C compiler to create assembly code from your snippet. For example if you have the following in test.c,</p>
<pre><code>void test() {
register int i asm("r0");
register int *a asm("r8");
register int *b asm("r9");
register int *c asm("r10");
for (i = 0; i < 10000; i++) {
a[i] = b[i] + c[i];
}
}
</code></pre>
<p>you can run</p>
<pre><code>arm-linux-androideabi-gcc -O0 -S test.c
</code></pre>
<p>to create a test.s file, which will contain assembly code for your test function as well as some extra stuff. You can see how your loop got compiled into to assembly below.</p>
<pre><code><snipped>
.L3:
mov r2, r8
mov r3, r0
mov r3, r3, asl #2
add r3, r2, r3
mov r1, r9
mov r2, r0
mov r2, r2, asl #2
add r2, r1, r2
ldr r1, [r2, #0]
mov ip, sl
mov r2, r0
mov r2, r2, asl #2
add r2, ip, r2
ldr r2, [r2, #0]
add r2, r1, r2
str r2, [r3, #0]
mov r3, r0
add r3, r3, #1
mov r0, r3
.L2:
mov r2, r0
ldr r3, .L5
cmp r2, r3
ble .L3
sub sp, fp, #12
ldmfd sp!, {r8, r9, sl, fp}
bx lr
<snipped>
</code></pre>
<p>Now the problem with this approach is trusting the compiler generates the optimal code for your study, which might not be always the case but what you'll get is fast answers to your questions like above instead of waiting for people :)</p>
<p>-- extra --</p>
<p>GCC allows you to put variables into certain registers, see <a href="http://gcc.gnu.org/onlinedocs/gcc/Explicit-Reg-Vars.html" rel="noreferrer">related documentation</a>.</p>
<p>You can get arm instruction cheat sheet <a href="http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf" rel="noreferrer">here</a>.</p>
<p>Newer versions of GCC creates better arm code as one would expected. Above snipped is generated by version 4.4.3, and I can confirm <a href="https://launchpad.net/gcc-linaro" rel="noreferrer">Linaro</a>'s 4.7.1 proves my claim. So if you take my approach use the most recent tool chain you can get.</p> |
11,983,412 | Get all input types with name, id, value in JQuery | <p>In JQuery, how can i get list of input type with name, id and value present in any div?</p> | 11,983,452 | 5 | 2 | null | 2012-08-16 08:36:53.533 UTC | 1 | 2018-03-13 19:14:49.99 UTC | null | null | null | null | 456,222 | null | 1 | 6 | jquery | 49,757 | <p>Selects inputs that descend from a div that have both name, id, and value attributes present. Then pushes the "type" attribute of each matching item into an array.</p>
<pre><code>var inputTypes = [];
$('div input[name][id][value]').each(function(){
inputTypes.push($(this).attr('type'));
});
</code></pre>
<p><a href="http://api.jquery.com/multiple-attribute-selector/">http://api.jquery.com/multiple-attribute-selector/</a></p> |
11,491,405 | JS jQuery - check if value is in array | <p>I am more of a PHP person, not JS - and I think my problem is more a syntax problem ..</p>
<p>I have a small jQuery to "validate" and check input value .</p>
<p>It works ok for single words, but I need array.</p>
<p>I am using the <code>inArray()</code> of jQuery .</p>
<pre><code>var ar = ["value1", "value2", "value3", "value4"]; // ETC...
jQuery(document).ready(function() {
jQuery("form#searchreport").submit(function() {
if (jQuery.inArray(jQuery("input:first"), ar)){
//if (jQuery("input:first").val() == "value11") { // works for single words
jQuery("#divResult").html("<span>VALUE FOUND</span>").show();
jQuery("#contentresults").delay(800).show("slow");
return false;
}
// SINGLE VALUE SPECIAL CASE / Value not allowed
if (jQuery("input:first").val() == "word10") {
jQuery("#divResult").html("YOU CHEAT !").show();
jQuery("#contentresults").delay(800).show("slow");
return false;
}
// Value not Valid
jQuery("#divResult").text("Not valid!").show().fadeOut(1000);
return false;
});
});
</code></pre>
<p>now - this <code>if (jQuery.inArray(jQuery("input:first"), ar))</code> is not working right .. every value that I put will be validated as OK . (even empty)</p>
<p>I need to validate only values from the array (ar) .</p>
<p>I tried also <code>if (jQuery.inArray(jQuery("input:first"), ar) == 1) // 1,0,-1 tried all</code></p>
<p>what am i doing wrong ?</p>
<p>Bonus question : how to do NOT in array in jQuery ??
(the equivalent of PHP <code>if (!in_array('1', $a))</code> - I sw somehre that it will not work , and need to use something like this : <code>!!~</code></p> | 11,491,429 | 4 | 1 | null | 2012-07-15 11:15:44.93 UTC | 5 | 2018-01-09 23:46:12.09 UTC | null | null | null | null | 1,244,126 | null | 1 | 21 | jquery|arrays|validation | 129,696 | <p>You are comparing a jQuery object (<code>jQuery('input:first')</code>) to strings (the elements of the array).<br>
Change the code in order to compare the input's value (wich is a string) to the array elements: </p>
<pre><code>if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)
</code></pre>
<p>The <code>inArray</code> method returns <code>-1</code> if the element wasn't found in the array, so as your <em>bonus</em> answer to how to determine if an element is <strong>not</strong> in an array, use this : </p>
<pre><code>if(jQuery.inArray(el,arr) == -1){
// the element is not in the array
};
</code></pre> |
11,904,805 | Django startswith on fields | <p>let's say that I have an Address model with a postcode field. I can lookup addresses with postcode starting with "123" with this line:</p>
<pre><code>Address.objects.filter(postcode__startswith="123")
</code></pre>
<p>Now, I need to do this search the "other way around". I have an Address model with a postcode_prefix field, and I need to retrieve all the addresses for which postcode_prefix is a prefix of a given code, like "12345". So if in my db I had 2 addresses with postcode_prefix = "123" and "234", only the first one would be returned.</p>
<p>Something like:</p>
<pre><code>Address.objects.filter("12345".startswith(postcode_prefix))
</code></pre>
<p>The problem is that this doesn't work.
The only solution I can come up with is to perform a filter on the first char, like:</p>
<pre><code>Address.objects.filter(postcode_prefix__startswith="12345"[0])
</code></pre>
<p>and then, when I get the results, make a list comprehension that filters them properly, like this:</p>
<pre><code>results = [r for r in results if "12345".startswith(r.postcode_prefix)]
</code></pre>
<p>Is there a better way to do it in django?</p> | 11,906,048 | 6 | 1 | null | 2012-08-10 15:28:51.65 UTC | 4 | 2021-12-05 02:49:44.587 UTC | 2021-12-01 12:55:55.437 UTC | null | 15,993,687 | null | 1,590,645 | null | 1 | 34 | django | 58,409 | <p>In SQL terms, what you want to achieve reads like ('12345' is the postcode you are searching for):</p>
<pre><code>SELECT *
FROM address
WHERE '12345' LIKE postcode_prefix||'%'
</code></pre>
<p>This is not really a standard query and I do not see any possibility to achieve this in Django using only get()/filter().</p>
<p>However, Django offers a way to provide additional SQL clauses with <code>extra()</code>:</p>
<pre><code>postcode = '12345'
Address.objects.extra(where=["%s LIKE postcode_prefix||'%%'"], params=[postcode])
</code></pre>
<p>Please see the <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra" rel="noreferrer">Django documentation on extra()</a> for further reference. Also note that the extra contains pure SQL, so you need to make sure that the clause is valid for your database.</p>
<p>Hope this works for you. </p> |
11,781,658 | What is the opposite method of Array.empty? or [].empty? in ruby | <p>I do realize that I can do </p>
<pre><code>unless [1].empty?
</code></pre>
<p>But I'm wondering if there is a method?</p> | 11,781,780 | 5 | 1 | null | 2012-08-02 16:14:52.39 UTC | 2 | 2021-10-23 21:38:38.223 UTC | null | null | null | null | 688,266 | null | 1 | 69 | ruby | 44,143 | <p>As well as <code>#any?</code> as davidrac mentioned, with <a href="http://rubygems.org/gems/activesupport" rel="noreferrer">ActiveSupport</a> there's <a href="https://apidock.com/rails/Object/present%3F" rel="noreferrer">#present?</a> which acts more like a truth test in other languages. For <code>nil</code>, <code>false</code>, <code>''</code>, <code>{}</code>, <code>[]</code> and so on it returns false; for everything else true (including 0, interestingly).</p> |
11,715,485 | What is the difference between declaration and definition in Java? | <p>I'm very confused between the two terms. I checked on stackoverflow and there's a similar question for C++ but not for java. </p>
<p>Can someone explain the difference between the two terms for java?</p> | 11,715,494 | 8 | 2 | null | 2012-07-30 04:41:59.18 UTC | 30 | 2022-08-27 02:46:54.16 UTC | null | null | null | null | 1,422,604 | null | 1 | 86 | java | 82,296 | <p>The conceptual difference is simple:</p>
<ul>
<li><p><em>Declaration</em>: You are <em>declaring</em> that something exists, such as a class, function or variable. You don't say anything about <em>what</em> that class or function looks like, you just say that it exists.</p>
</li>
<li><p><em>Definition</em>: You <em>define</em> how something is implemented, such as a class, function or variable, i.e. you say <em>what</em> it actually is.</p>
</li>
</ul>
<p><strong>In Java</strong>, there is little difference between the two, and formally speaking, a declaration includes not only the identifier, but also it's definition. Here is how I personally interpret the terms in detail:</p>
<ul>
<li><p><strong>Classes</strong>: Java doesn't really separate declarations and definitions as C++ does (in header and cpp files). You define them at the point where you declare them.</p>
</li>
<li><p><strong>Functions</strong>: When you're writing an interface (or an abstract class), you could say that you're declaring a function, without defining it. Ordinary functions however, are always defined right where they are declared. See the body of the function as its definition if you like.</p>
</li>
<li><p><strong>Variables</strong>: A variable <em>declaration</em> could look like this:</p>
<pre><code> int x;
</code></pre>
</li>
</ul>
<p>(you're declaring that a variable <code>x</code> exists and has type <code>int</code>) either if it's a local variable or member field. In Java, there's no information left about <code>x</code> to <em>define</em>, except possible what values it shall hold, which is determined by the assignments to it.</p>
<p>Here's a rough summary of how I use the terms:</p>
<pre><code>abstract class SomeClass { // class decl.
// \
int x; // variable decl. |
// |
public abstract void someMethod(); // function decl. |
// |
public int someOtherMethod() { // function decl. |
// | class
if (Math.random() > .5) // \ | def.
return x; // | function definition |
else // | |
return -x; // / |
// |
} // |
} // /
</code></pre> |
3,264,064 | Unpack inner zips in zip with Maven | <p>I can unpack zip file via the maven-dependency plugin, but currently I have the problem that inside that zip file other zip files are include and I need to unpack them as well. How can I do this?</p> | 3,264,160 | 4 | 0 | null | 2010-07-16 10:51:00.333 UTC | 9 | 2018-08-09 11:29:37.367 UTC | 2016-06-07 14:47:02.433 UTC | null | 2,011,421 | null | 296,328 | null | 1 | 38 | maven|zip|maven-2|archive|unzip | 35,701 | <p>You can unzip any files using ant task runner plugin:</p>
<pre><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>prepare</id>
<phase>validate</phase>
<configuration>
<tasks>
<echo message="prepare phase" />
<unzip src="zips/archive.zip" dest="output/" />
<unzip src="output/inner.zip" dest="output/" />
<unzip dest="output">
<fileset dir="archives">
<include name="prefix*.zip" />
</fileset>
</unzip>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</code></pre> |
3,603,581 | What does it mean for an object to be picklable (or pickle-able)? | <p>Python docs mention this word a lot and I want to know what it means! Googling doesn't help much..</p> | 3,603,621 | 4 | 2 | null | 2010-08-30 19:32:50.907 UTC | 11 | 2021-08-20 20:31:00.323 UTC | null | null | null | null | 413,065 | null | 1 | 102 | python|pickle | 44,075 | <p>It simply means it can be serialized by the <a href="https://docs.python.org/library/pickle.html" rel="noreferrer"><code>pickle</code></a> module. For a basic explanation of this, see <a href="https://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled" rel="noreferrer">What can be pickled and unpickled?</a>. <a href="https://docs.python.org/3/library/pickle.html#pickling-class-instances" rel="noreferrer">Pickling Class Instances</a> provides more details, and shows how classes can customize the process.</p> |
3,716,492 | What does Expression.Quote() do that Expression.Constant() can’t already do? | <p><strong>Note: I am aware of the earlier question “<a href="https://stackoverflow.com/questions/3138133/">What is the purpose of LINQ's Expression.Quote method?</a>”</strong>, but if you read on you will see that it doesn’t answer my question.</p>
<p>I understand what the stated purpose of <code>Expression.Quote()</code> is. However, <code>Expression.Constant()</code> can be used for the same purpose (in addition to all the purposes that <code>Expression.Constant()</code> is already used for). Therefore, I don’t understand why <code>Expression.Quote()</code> is at all required. </p>
<p>To demonstrate this, I have written a quick example where one would customarily use <code>Quote</code> (see the line marked with exclamation points), but I used <code>Constant</code> instead and it worked equally well:</p>
<pre><code>string[] array = { "one", "two", "three" };
// This example constructs an expression tree equivalent to the lambda:
// str => str.AsQueryable().Any(ch => ch == 'e')
Expression<Func<char, bool>> innerLambda = ch => ch == 'e';
var str = Expression.Parameter(typeof(string), "str");
var expr =
Expression.Lambda<Func<string, bool>>(
Expression.Call(typeof(Queryable), "Any", new Type[] { typeof(char) },
Expression.Call(typeof(Queryable), "AsQueryable",
new Type[] { typeof(char) }, str),
// !!!
Expression.Constant(innerLambda) // <--- !!!
),
str
);
// Works like a charm (prints one and three)
foreach (var str in array.AsQueryable().Where(expr))
Console.WriteLine(str);
</code></pre>
<p>The output of <code>expr.ToString()</code> is the same for both, too (whether I use <code>Constant</code> or <code>Quote</code>).</p>
<p>Given the above observations, it appears that <code>Expression.Quote()</code> is redundant. The C# compiler could have been made to compile nested lambda expressions into an expression tree involving <code>Expression.Constant()</code> instead of <code>Expression.Quote()</code>, and any LINQ query provider that wants to process expression trees into some other query language (such as SQL) could look out for a <code>ConstantExpression</code> with type <code>Expression<TDelegate></code> instead of a <code>UnaryExpression</code> with the special <code>Quote</code> node type, and everything else would be the same.</p>
<p>What am I missing? Why was <code>Expression.Quote()</code> and the special <code>Quote</code> node type for <code>UnaryExpression</code> invented?</p> | 3,753,382 | 5 | 0 | null | 2010-09-15 09:49:29.417 UTC | 44 | 2020-09-01 22:15:39.837 UTC | 2017-05-23 12:02:34.21 UTC | null | -1 | null | 33,225 | null | 1 | 100 | c#|expression-trees | 12,059 | <h2>Short answer:</h2>
<p>The quote operator is an <em>operator</em> which <em>induces closure semantics on its operand</em>. Constants are just values.</p>
<p>Quotes and constants have different <em>meanings</em> and therefore have <em>different representations in an expression tree</em>. Having the same representation for two very different things is <em>extremely</em> confusing and bug prone.</p>
<h2>Long answer:</h2>
<p>Consider the following:</p>
<pre><code>(int s)=>(int t)=>s+t
</code></pre>
<p>The outer lambda is a factory for adders that are bound to the outer lambda's parameter. </p>
<p>Now, suppose we wish to represent this as an expression tree that will later be compiled and executed. What should the body of the expression tree be? <em>It depends on whether you want the compiled state to return a delegate or an expression tree.</em></p>
<p>Let's begin by dismissing the uninteresting case. If we wish it to return a delegate then the question of whether to use Quote or Constant is a moot point:</p>
<pre><code> var ps = Expression.Parameter(typeof(int), "s");
var pt = Expression.Parameter(typeof(int), "t");
var ex1 = Expression.Lambda(
Expression.Lambda(
Expression.Add(ps, pt),
pt),
ps);
var f1a = (Func<int, Func<int, int>>) ex1.Compile();
var f1b = f1a(100);
Console.WriteLine(f1b(123));
</code></pre>
<p>The lambda has a nested lambda; the compiler generates the interior lambda as a delegate to a function closed over the state of the function generated for the outer lambda. We need consider this case no more.</p>
<p>Suppose we wish the compiled state to return an <em>expression tree</em> of the interior. There are two ways to do that: the easy way and the hard way. </p>
<p>The hard way is to say that instead of</p>
<pre><code>(int s)=>(int t)=>s+t
</code></pre>
<p>what we really mean is</p>
<pre><code>(int s)=>Expression.Lambda(Expression.Add(...
</code></pre>
<p>And then generate the expression tree for <em>that</em>, producing <em>this mess</em>:</p>
<pre><code> Expression.Lambda(
Expression.Call(typeof(Expression).GetMethod("Lambda", ...
</code></pre>
<p>blah blah blah, dozens of lines of reflection code to make the lambda. <em>The purpose of the quote operator is to tell the expression tree compiler that we want the given lambda to be treated as an expression tree, not as a function, without having to explicitly generate the expression tree generation code</em>.</p>
<p>The easy way is:</p>
<pre><code> var ex2 = Expression.Lambda(
Expression.Quote(
Expression.Lambda(
Expression.Add(ps, pt),
pt)),
ps);
var f2a = (Func<int, Expression<Func<int, int>>>)ex2.Compile();
var f2b = f2a(200).Compile();
Console.WriteLine(f2b(123));
</code></pre>
<p>And indeed, if you compile and run this code you get the right answer.</p>
<p>Notice that the quote operator is the operator which induces closure semantics on the interior lambda which uses an outer variable, a formal parameter of the outer lambda.</p>
<p>The question is: why not eliminate Quote and make this do the same thing?</p>
<pre><code> var ex3 = Expression.Lambda(
Expression.Constant(
Expression.Lambda(
Expression.Add(ps, pt),
pt)),
ps);
var f3a = (Func<int, Expression<Func<int, int>>>)ex3.Compile();
var f3b = f3a(300).Compile();
Console.WriteLine(f3b(123));
</code></pre>
<p>The constant does not induce closure semantics. Why should it? You said that this was a <em>constant</em>. It's just a value. It should be perfect as handed to the compiler; the compiler should be able to just generate a dump of that value to the stack where it is needed. </p>
<p>Since there is no closure induced, if you do this you'll get a "variable 's' of type 'System.Int32' is not defined" exception on the invocation. </p>
<p>(Aside: I've just reviewed the code generator for delegate creation from quoted expression trees, and unfortunately a comment that I put into the code back in 2006 is still there. FYI, the hoisted outer parameter is <em>snapshotted</em> into a constant when the quoted expression tree is reified as a delegate by the runtime compiler. There was a good reason why I wrote the code that way which I do not recall at this exact moment, but it does have the nasty side effect of introducing closure over <em>values</em> of outer parameters rather than closure over <em>variables</em>. Apparently the team which inherited that code decided to not fix that flaw, so if you are relying upon mutation of a closed-over outer parameter being observed in a compiled quoted interior lambda, you're going to be disappointed. However, since it is a pretty bad programming practice to both (1) mutate a formal parameter and (2) rely upon mutation of an outer variable, I would recommend that you change your program to not use these two bad programming practices, rather than waiting for a fix which does not appear to be forthcoming. Apologies for the error.)</p>
<p>So, to repeat the question:</p>
<blockquote>
<p>The C# compiler could have been made to compile nested lambda expressions into an expression tree involving Expression.Constant() instead of Expression.Quote(), and any LINQ query provider that wants to process expression trees into some other query language (such as SQL) could look out for a ConstantExpression with type Expression instead of a UnaryExpression with the special Quote node type, and everything else would be the same.</p>
</blockquote>
<p>You are correct. We <em>could</em> encode semantic information that means "induce closure semantics on this value" by <em>using the type of the constant expression as a flag</em>. </p>
<p>"Constant" would then have the meaning "use this constant value, <em>unless</em> the type happens to be an expression tree type <em>and</em> the value is a valid expression tree, in which case, instead use the value that is the expression tree resulting from rewriting the interior of the given expression tree to induce closure semantics in the context of any outer lambdas that we might be in right now.</p>
<p>But why <em>would</em> we do that crazy thing? <em>The quote operator is an insanely complicated operator</em>, and it should be used <em>explicitly</em> if you're going to use it. You're suggesting that in order to be parsimonious about not adding one extra factory method and node type amongst the several dozen already there, that we add a bizarre corner case to constants, so that constants are sometimes logically constants, and sometimes they are rewritten lambdas with closure semantics.</p>
<p>It would also have the somewhat odd effect that constant doesn't mean "use this value". Suppose for some bizarre reason you <em>wanted</em> the third case above to compile an expression tree into a delegate that hands out an expression tree that has a not-rewritten reference to an outer variable? Why? Perhaps because <em>you are testing your compiler</em> and want to just pass the constant on through so that you can perform some other analysis on it later. Your proposal would make that impossible; any constant that happens to be of expression tree type would be rewritten regardless. One has a reasonable expectation that "constant" means "use this value". "Constant" is a "do what I say" node. The constant processor's job is not to guess at what you <em>meant</em> to say based on the type.</p>
<p>And note of course that you are now putting the burden of understanding (that is, understanding that constant has complicated semantics that mean "constant" in one case and "induce closure semantics" based on a flag that is <em>in the type system</em>) upon <em>every</em> provider that does semantic analysis of an expression tree, not just upon Microsoft providers. <strong>How many of those third-party providers would get it wrong?</strong> </p>
<p>"Quote" is waving a big red flag that says "hey buddy, look over here, I'm a nested lambda expression and I have wacky semantics if I'm closed over an outer variable!" whereas "Constant" is saying "I'm nothing more than a value; use me as you see fit." When something is complicated and dangerous we want to be making it wave red flags, not hiding that fact by making the user dig through the <em>type system</em> in order to find out whether this value is a special one or not.</p>
<p>Furthermore, the idea that avoiding redundancy is even a goal is incorrect. Sure, avoiding unnecessary, confusing redundancy is a goal, but most redundancy is a good thing; redundancy creates clarity. New factory methods and node kinds are <em>cheap</em>. We can make as many as we need so that each one represents one operation cleanly. We have no need to resort to nasty tricks like "this means one thing unless this field is set to this thing, in which case it means something else." </p> |
3,612,567 | How to create my own java library(API)? | <p>I created a program in Java and I designed it so that methods that I want them to appear (getter methods) in the main, I can call them easily after initiate the class that holds these methods.</p>
<p>The question is that, I need to make this application (that holds the getter methods) to be like an API so that I can give my application for developers to use my functions (the getter methods) if they need them, and only what they need is to add this file (I think the API after is done shown as .jar file).</p>
<p>How can I make it so that I can make my code reusable with other application? It's similar to the .dll, I think.</p>
<p>Thanks a lot ;)</p> | 3,612,587 | 8 | 2 | null | 2010-08-31 19:39:32.753 UTC | 26 | 2022-03-02 07:14:49.927 UTC | 2018-09-30 21:14:57.523 UTC | null | 1,429,387 | null | 408,389 | null | 1 | 56 | java|jar | 108,442 | <p>Create a JAR. Then include the JAR. Any classes in that JAR will be available. Just make sure you protect your code if you are giving out an API. Don't expose any methods / properties to the end user that shouldn't be used. </p>
<p>Edit: In response to your comment, make sure you don't include the source when you package the JAR. Only include the class files. That's the best you can really do.</p> |
3,740,280 | How do ACID and database transactions work? | <p>What is the relationship between ACID and database transaction?</p>
<p>Does ACID give database transaction or is it the same thing?</p>
<p>Could someone enlighten this topic.</p> | 3,740,307 | 9 | 0 | null | 2010-09-18 03:35:46.763 UTC | 98 | 2022-07-19 10:36:20.22 UTC | 2019-05-20 03:50:47.867 UTC | null | 1,025,118 | null | 224,922 | null | 1 | 179 | database|transactions|acid | 131,967 | <p><a href="http://en.wikipedia.org/wiki/ACID" rel="noreferrer">ACID</a> is a set of properties that you would like to apply when modifying a database.</p>
<ul>
<li>Atomicity</li>
<li>Consistency</li>
<li>Isolation</li>
<li>Durability</li>
</ul>
<p>A transaction is a set of related changes which is used to achieve some of the ACID properties. Transactions are tools to achieve the ACID properties.</p>
<p>Atomicity means that you can guarantee that all of a transaction happens, or none of it does; you can do complex operations as one single unit, all or nothing, and a crash, power failure, error, or anything else won't allow you to be in a state in which only some of the related changes have happened.</p>
<p>Consistency means that you guarantee that your data will be consistent; none of the constraints you have on related data will ever be violated.</p>
<p>Isolation means that one transaction cannot read data from another transaction that is not yet completed. If two transactions are executing concurrently, each one will see the world as if they were executing sequentially, and if one needs to read data that is written by another, it will have to wait until the other is finished.</p>
<p>Durability means that once a transaction is complete, it is guaranteed that all of the changes have been recorded to a durable medium (such as a hard disk), and the fact that the transaction has been completed is likewise recorded.</p>
<p>So, transactions are a mechanism for guaranteeing these properties; they are a way of grouping related actions together such that as a whole, a group of operations can be atomic, produce consistent results, be isolated from other operations, and be durably recorded.</p> |
3,542,333 | How to prevent custom views from losing state across screen orientation changes | <p>I've successfully implemented <a href="http://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance%28%29" rel="noreferrer"><code>onRetainNonConfigurationInstance()</code></a> for my main <code>Activity</code> to save and restore certain critical components across screen orientation changes. </p>
<p>But it seems, my custom views are being re-created from scratch when the orientation changes. This makes sense, although in my case it's inconvenient because the custom view in question is an X/Y plot and the plotted points are stored in the custom view. </p>
<p>Is there a crafty way to implement something similar to <code>onRetainNonConfigurationInstance()</code> for a custom view, or do I need to just implement methods in the custom view which allow me to get and set its "state"?</p> | 3,542,895 | 10 | 0 | null | 2010-08-22 16:45:07.973 UTC | 166 | 2021-02-19 11:16:06.237 UTC | 2014-10-24 14:27:51.217 UTC | null | 356,895 | null | 268,803 | null | 1 | 269 | android|android-activity|state|screen-orientation | 110,721 | <p>You do this by implementing <a href="http://developer.android.com/reference/android/view/View.html#onSaveInstanceState%28%29" rel="noreferrer"><code>View#onSaveInstanceState</code></a> and <a href="http://developer.android.com/reference/android/view/View.html#onRestoreInstanceState%28android.os.Parcelable%29" rel="noreferrer"><code>View#onRestoreInstanceState</code></a> and extending the <a href="http://developer.android.com/reference/android/view/View.BaseSavedState.html" rel="noreferrer"><code>View.BaseSavedState</code></a> class.</p>
<pre><code>public class CustomView extends View {
private int stateToSave;
...
@Override
public Parcelable onSaveInstanceState() {
//begin boilerplate code that allows parent classes to save state
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
//end
ss.stateToSave = this.stateToSave;
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
//begin boilerplate code so parent classes can restore state
if(!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
//end
this.stateToSave = ss.stateToSave;
}
static class SavedState extends BaseSavedState {
int stateToSave;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
this.stateToSave = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(this.stateToSave);
}
//required field that makes Parcelables from a Parcel
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
</code></pre>
<p>The work is split between the View and the View's SavedState class. You should do all the work of reading and writing to and from the <code>Parcel</code> in the <code>SavedState</code> class. Then your View class can do the work of extracting the state members and doing the work necessary to get the class back to a valid state.</p>
<p>Notes: <code>View#onSavedInstanceState</code> and <code>View#onRestoreInstanceState</code> are called automatically for you if <code>View#getId</code> returns a value >= 0. This happens when you give it an id in xml or call <code>setId</code> manually. Otherwise you have to call <code>View#onSaveInstanceState</code> and write the Parcelable returned to the parcel you get in <code>Activity#onSaveInstanceState</code> to save the state and subsequently read it and pass it to <code>View#onRestoreInstanceState</code> from <code>Activity#onRestoreInstanceState</code>.</p>
<p>Another simple example of this is the <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/widget/CompoundButton.java#CompoundButton.onSaveInstanceState%28%29" rel="noreferrer"><code>CompoundButton</code></a></p> |
3,656,592 | How to programmatically disable page scrolling with jQuery | <p>Using jQuery, I would like to disable scrolling of the body:</p>
<p>My idea is to:</p>
<ol>
<li>Set <code>body{ overflow: hidden;}</code> </li>
<li>Capture the current <code>scrollTop();/scrollLeft()</code> </li>
<li>Bind to the body scroll event, set scrollTop/scrollLeft to the captured value.</li>
</ol>
<p>Is there a better way?</p>
<hr>
<p>Update:</p>
<p>Please see my example, and a reason why, at <a href="http://jsbin.com/ikuma4/2/edit" rel="noreferrer">http://jsbin.com/ikuma4/2/edit</a></p>
<p>I am aware someone will be thinking "why does he not just use <code>position: fixed</code> on the panel?".</p>
<p>Please do not suggest this as I have other reasons.</p> | 3,656,618 | 24 | 17 | null | 2010-09-07 07:30:18.74 UTC | 70 | 2021-04-20 15:43:29.84 UTC | 2013-03-11 16:26:46.013 UTC | null | 1,339,429 | null | 383,759 | null | 1 | 170 | jquery|css|scroll | 484,498 | <p>The only way I've found to do this is similar to what you described:</p>
<ol>
<li>Grab current scroll position (don't forget horizontal axis!).</li>
<li>Set overflow to hidden (probably want to retain previous overflow value).</li>
<li>Scroll document to stored scroll position with scrollTo().</li>
</ol>
<p>Then when you're ready to allow scrolling again, undo all that.</p>
<p>Edit: no reason I can't give you the code since I went to the trouble to dig it up...</p>
<pre><code>// lock scroll position, but retain settings for later
var scrollPosition = [
self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
];
var html = jQuery('html'); // it would make more sense to apply this to body, but IE7 won't have that
html.data('scroll-position', scrollPosition);
html.data('previous-overflow', html.css('overflow'));
html.css('overflow', 'hidden');
window.scrollTo(scrollPosition[0], scrollPosition[1]);
// un-lock scroll position
var html = jQuery('html');
var scrollPosition = html.data('scroll-position');
html.css('overflow', html.data('previous-overflow'));
window.scrollTo(scrollPosition[0], scrollPosition[1])
</code></pre> |
8,219,040 | Windows copy command return codes? | <p>I would like to test for the success/failure of a copy in a batch file, but I can't find any documentation on what if any errorlevel codes are returned. For example</p>
<pre><code>copy x y
if %errorlevel%. equ 1. (
echo Copy x y failed due to ...
exit /B
) else (
if %errorlevel% equ 2. (
echo Copy x y failed due to ...
exit /B
)
... etc ...
)
</code></pre> | 8,219,166 | 5 | 1 | null | 2011-11-21 21:55:31.06 UTC | 4 | 2020-04-07 17:28:35.577 UTC | 2017-02-22 22:38:13.95 UTC | null | 597,305 | null | 597,305 | null | 1 | 31 | windows|batch-file | 101,483 | <p>I'd opt for <code>xcopy</code> in this case since the error levels are documented (see <a href="http://technet.microsoft.com/en-us/library/bb491035.aspx" rel="nofollow noreferrer">xcopy documentation</a>, paraphrased below):</p>
<pre><code>Exit code Description
========= ===========
0 Files were copied without error.
1 No files were found to copy.
2 The user pressed CTRL+C to terminate xcopy.
4 Initialization error occurred. There is not
enough memory or disk space, or you entered
an invalid drive name or invalid syntax on
the command line.
5 Disk write error occurred.
</code></pre>
<p>In any case, <code>xcopy</code> is a far more powerful solution. The <a href="http://technet.microsoft.com/en-us/library/bb490886.aspx" rel="nofollow noreferrer">equivalent documentation</a> for <code>copy</code> does not document the error levels.</p>
<hr>
<p>As an aside, you may want to rethink your use of the <code>%errorlevel%</code> <em>variable.</em> It has unexpected results, at least in some versions of Windows, if someone has explicitly done something silly like:</p>
<pre><code>set errorlevel=22
</code></pre>
<p>In those cases, the actual <em>variable</em> will be used rather than grabbing the actual error level. The "normal" way of doing this is (in decreasing order since <code>errorlevel</code> is a "greater than or equal to" check):</p>
<pre><code>if errorlevel 2 (
echo Copy x y failed due to reason 2
exit /B
)
if errorlevel 1 (
echo Copy x y failed due to reason 1
exit /B
)
</code></pre>
<hr>
<p>In addition, if you are running Win7 or Win Server 2008 or later, you should look into <a href="http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx" rel="nofollow noreferrer">Robocopy</a>, which is now the preferred mass-copy solution.</p> |
7,779,443 | How to use UIStepper | <p>I am trying to work with <code>UIStepper</code> to increment or decrement an integer,
but both "-" and "+" increase the integer! How can I recognize the "+" and "-" button?</p>
<p>In the <code>UIStepper</code> header file there are two <code>UIButton</code>s:</p>
<pre><code>UIButton *_plusButton;
UIButton *_minusButton;
</code></pre>
<p>for example :</p>
<pre><code>- (IBAction)changeValue:(id)sender
{
UIStepper *stepper = (UIStepper *) sender;
stepper.maximumValue = 10;
stepper.minimumValue = 0;
if (stepper)
{
integer++;
[label setText:[NSString stringWithFormat:@"%d",integer]];
}
else
{
integer--;
[label setText:[NSString stringWithFormat:@"%d",integer]];
}
}
</code></pre> | 7,779,498 | 5 | 0 | null | 2011-10-15 17:33:01.593 UTC | 12 | 2019-12-06 23:37:09.877 UTC | 2016-03-09 11:41:35.45 UTC | null | 5,722,289 | null | 319,097 | null | 1 | 39 | ios|objective-c|uistepper | 69,455 | <p>You should ignore the ivars. They will not help you.</p>
<p>The <code>UIStepper</code> has a <code>value</code> property that you can query to figure out what the current value is. So your method could simply be:</p>
<pre><code>- (IBAction)valueChanged:(UIStepper *)sender {
double value = [sender value];
[label setText:[NSString stringWithFormat:@"%d", (int)value]];
}
</code></pre> |
7,956,038 | pugjs(jade) template engine loading css file | <p>I've been searching in the examples on the GitHub but I couldn't find how to load a simple css file into my layout. My first thought was doing something like this <code>link(href="my.css")</code> but it seems it's not working at all. The href points to a correct location online (checked and working) thus maybe I'm forgetting something?</p> | 7,956,323 | 5 | 1 | null | 2011-10-31 15:45:12.88 UTC | 8 | 2019-11-28 19:19:56.107 UTC | 2015-12-31 07:43:57.157 UTC | null | 553,523 | null | 617,461 | null | 1 | 39 | css|node.js|pug|pugjs | 66,750 | <p>try: <code>link(rel='stylesheet', href='/stylesheets/style.css')
</code></p> |
7,992,134 | Breakpoints are crossed out, how can I make them valid? | <p>i got a tricky one:</p>
<p><img src="https://i.stack.imgur.com/BxPke.jpg" alt="look At Breakpoints, they are crossed out!"></p>
<p>I can't set valid breakpoints. Not in Tests, neither in my Java Classes. I searched Stackoverflow and google, but I couldn't find anybody with the same problem.</p>
<p>I'm using STS(x86) and Maven.</p>
<p><strong>Edit:</strong> It may seem confusing but I solved it by myself.
I have to go Run-> Skip all Breakpoints (it was set, and I wonder how it was set, because I didn't do it)</p> | 7,992,183 | 6 | 2 | null | 2011-11-03 08:46:22.733 UTC | 15 | 2018-02-02 13:17:27.103 UTC | 2018-02-02 13:17:27.103 UTC | null | 17,801 | null | 1,022,119 | null | 1 | 192 | java|eclipse|breakpoints|sts-springsourcetoolsuite | 48,708 | <p>There is a menu entry you have discovered for yourself that toggles the skipping of all breakpoints. There is also an icon for this in the "Breakpoints" View, and there may be a hot-key defined as well, all of which you may have triggered by accident.</p>
<p>Take a look at the <strong>Run -> Skip All Breakpoints</strong>.</p> |
8,355,264 | Tournament bracket placement algorithm | <p>Given a list of opponent seeds (for example seeds 1 to 16), I'm trying to write an algorithm that will result in the top seed playing the lowest seed in that round, the 2nd seed playing the 2nd-lowest seed, etc.</p>
<p>Grouping 1 and 16, 2 and 15, etc. into "matches" is fairly easy, but I also need to make sure that the higher seed will play the lower seed in subsequent rounds.</p>
<p>An example bracket with the correct placement:</p>
<pre>1 vs 16
1 vs 8
8 vs 9
1 vs 4
4 vs 13
4 vs 5
5 vs 12
1 vs 2
2 vs 15
2 vs 7
7 vs 10
2 vs 3
3 vs 14
3 vs 6
6 vs 11</pre>
<p>As you can see, seed 1 and 2 only meet up in the final.</p> | 8,361,231 | 10 | 5 | null | 2011-12-02 10:57:59.15 UTC | 21 | 2019-08-21 11:16:49.557 UTC | 2011-12-02 19:02:06.293 UTC | null | 221,528 | null | 221,528 | null | 1 | 26 | algorithm|language-agnostic|brackets|tournament | 23,730 | <p>I've come up with the following algorithm. It may not be super-efficient, but I don't think that it really needs to be. It's written in PHP.</p>
<pre class="lang-php prettyprint-override"><code><?php
$players = range(1, 32);
$count = count($players);
$numberOfRounds = log($count / 2, 2);
// Order players.
for ($i = 0; $i < $numberOfRounds; $i++) {
$out = array();
$splice = pow(2, $i);
while (count($players) > 0) {
$out = array_merge($out, array_splice($players, 0, $splice));
$out = array_merge($out, array_splice($players, -$splice));
}
$players = $out;
}
// Print match list.
for ($i = 0; $i < $count; $i++) {
printf('%s vs %s<br />%s', $players[$i], $players[++$i], PHP_EOL);
}
?>
</code></pre> |
4,344,523 | Popup window in any app | <p>i want to Popup dialog at a specific time in any app my code :</p>
<pre><code> public class testPOPDialog extends Activity {
/** Called when the activity is first created. */
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler.postDelayed(mUpdateTimeTask, 1000);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
AlertDialog d = new AlertDialog.Builder(testPOPDialog.this)
.setTitle("tanchulai")
.setMessage("bucuo de tanchulai")
.create();
d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
d.show();
}
};
}
</code></pre>
<p>it give me </p>
<pre><code>12-03 10:12:18.162: ERROR/AndroidRuntime(571): android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRoot$W@43dd71c0 -- permission denied for this window type
</code></pre>
<p>what is this permission
if i delete <code>d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);</code> my app is correct.....</p> | 4,344,760 | 3 | 0 | null | 2010-12-03 10:18:20.333 UTC | 9 | 2014-04-15 11:37:44.837 UTC | 2014-04-15 11:37:44.837 UTC | null | 1,007,369 | null | 233,618 | null | 1 | 7 | android|android-widget | 12,115 | <p>Add this permission to your manifest:</p>
<pre><code>android.permission.SYSTEM_ALERT_WINDOW
</code></pre> |
4,488,481 | How to show Dependency Injection on a UML class diagram? | <p>How do I show Dependency Injection of an object or class in a UML class diagram?</p> | 4,503,518 | 3 | 0 | null | 2010-12-20 09:48:18.343 UTC | 11 | 2020-09-15 15:02:50.527 UTC | 2019-06-06 23:05:28.07 UTC | null | 2,483,484 | null | 100,516 | null | 1 | 40 | dependency-injection|uml|class-diagram | 28,084 | <p><a href="http://www.martinfowler.com/articles/injection.html" rel="noreferrer">Martin Fowler</a> shows it like this:</p>
<p><img src="https://i.stack.imgur.com/HTSTO.gif" alt="DI UML"></p> |
4,411,049 | How can I find the union of two Django querysets? | <p>I’ve got a Django model with two custom manager methods. Each returns a different subset of the model’s objects, based on a different property of the object.</p>
<p>Is there any way to get a queryset, or just a list of objects, that’s the union of the querysets returned by each manager method?</p> | 4,412,293 | 3 | 2 | null | 2010-12-10 16:32:44.71 UTC | 15 | 2021-02-02 13:38:28.48 UTC | 2010-12-10 16:46:09.3 UTC | null | 20,578 | null | 20,578 | null | 1 | 119 | python|django|django-models | 67,675 | <p>This works and looks a bit cleaner:</p>
<pre><code>records = query1 | query2
</code></pre>
<p>If you don't want duplicates, then you will need to append <code>.distinct()</code>:</p>
<pre><code>records = (query1 | query2).distinct()
</code></pre> |
4,329,893 | Erlang/OTP - Timing Applications | <p>I am interested in bench-marking different parts of my program for speed. I having tried using <code>info(statistics)</code> and <code>erlang:now()</code></p>
<p>I need to know down to the microsecond what the average speed is. I don't know why I am having trouble with a script I wrote.</p>
<p>It should be able to start anywhere and end anywhere. I ran into a problem when I tried starting it on a process that may be running up to four times in parallel.</p>
<p>Is there anyone who already has a solution to this issue?</p>
<p>EDIT:</p>
<p>Willing to give a bounty if someone can provide a script to do it. It <em>needs</em> to spawn though multiple process'. I cannot accept a function like timer.. at least in the implementations I have seen. IT only traverses one process and even then some major editing is necessary for a full test of a full program. Hope I made it clear enough.</p> | 4,354,188 | 4 | 2 | null | 2010-12-01 22:41:47.337 UTC | 12 | 2020-10-14 11:41:19.737 UTC | 2020-10-14 11:41:19.737 UTC | null | 11,880,324 | null | 417,896 | null | 1 | 14 | erlang|performance|timing | 4,261 | <p>Here's how to use eprof, likely the easiest solution for you:</p>
<p>First you need to start it, like most applications out there:</p>
<pre><code>23> eprof:start().
{ok,<0.95.0>}
</code></pre>
<p>Eprof supports two profiling mode. You can call it and ask to profile a certain function, but we can't use that because other processes will mess everything up. We need to manually start it profiling and tell it when to stop (this is why you won't have an easy script, by the way).</p>
<pre><code>24> eprof:start_profiling([self()]).
profiling
</code></pre>
<p>This tells eprof to profile everything that will be run and spawned from the shell. New processes will be included here. I will run some arbitrary multiprocessing function I have, which spawns about 4 processes communicating with each other for a few seconds:</p>
<pre><code>25> trade_calls:main_ab().
Spawned Carl: <0.99.0>
Spawned Jim: <0.101.0>
<0.100.0>
Jim: asking user <0.99.0> for a trade
Carl: <0.101.0> asked for a trade negotiation
Carl: accepting negotiation
Jim: starting negotiation
... <snip> ...
</code></pre>
<p>We can now tell eprof to stop profiling once the function is done running.</p>
<pre><code>26> eprof:stop_profiling().
profiling_stopped
</code></pre>
<p>And we want the logs. Eprof will print them to screen by default. You can ask it to also log to a file with <code>eprof:log(File)</code>. Then you can tell it to analyze the results. We tell it to collapse the run time from all processes into a single table with the option <code>total</code> (see the <a href="http://erldocs.com/R14B/tools/eprof.html?i=5&search=eprof#analyze/1" rel="noreferrer">manual</a> for more options):</p>
<pre><code>27> eprof:analyze(total).
FUNCTION CALLS % TIME [uS / CALLS]
-------- ----- --- ---- [----------]
io:o_request/3 46 0.00 0 [ 0.00]
io:columns/0 2 0.00 0 [ 0.00]
io:columns/1 2 0.00 0 [ 0.00]
io:format/1 4 0.00 0 [ 0.00]
io:format/2 46 0.00 0 [ 0.00]
io:request/2 48 0.00 0 [ 0.00]
...
erlang:atom_to_list/1 5 0.00 0 [ 0.00]
io:format/3 46 16.67 1000 [ 21.74]
erl_eval:bindings/1 4 16.67 1000 [ 250.00]
dict:store_bkt_val/3 400 16.67 1000 [ 2.50]
dict:store/3 114 50.00 3000 [ 26.32]
</code></pre>
<p>And you can see that most of the time (50%) is spent in dict:store/3. 16.67% is taken in outputting the result, another 16.67% is taken by erl_eval (this is why you get by running short functions in the shell -- parsing them becomes longer than running them).</p>
<p>You can then start going from there. That's the basics of profiling run times with Erlang. Handle with care, eprof can be quite a load on a production system or for functions that run for too long. Especially on a production system.</p> |
4,318,881 | In C, what does a variable declaration with two asterisks (**) mean? | <p>I am working with C and I'm a bit rusty. I am aware that <code>*</code> has three uses:</p>
<ol>
<li>Declaring a pointer.</li>
<li>Dereferencing a pointer.</li>
<li>Multiplication</li>
</ol>
<p>However, what does it mean when there are two asterisks (<code>**</code>) before a variable declaration:</p>
<pre><code>char **aPointer = ...
</code></pre>
<p>Thanks,</p>
<p>Scott</p> | 4,318,886 | 5 | 0 | null | 2010-11-30 21:30:14.04 UTC | 25 | 2010-12-26 18:17:05.567 UTC | 2010-12-26 18:17:05.567 UTC | null | 220,819 | null | 229,807 | null | 1 | 65 | c|pointers | 50,676 | <p>It declares a <strong>pointer to a <code>char</code> pointer</strong>.</p>
<p>The usage of such a pointer would be to do such things like:</p>
<pre><code>void setCharPointerToX(char ** character) {
*character = "x"; //using the dereference operator (*) to get the value that character points to (in this case a char pointer
}
char *y;
setCharPointerToX(&y); //using the address-of (&) operator here
printf("%s", y); //x
</code></pre>
<p>Here's another example:</p>
<pre><code>char *original = "awesomeness";
char **pointer_to_original = &original;
(*pointer_to_original) = "is awesome";
printf("%s", original); //is awesome
</code></pre>
<p>Use of <code>**</code> with arrays:</p>
<pre><code>char** array = malloc(sizeof(*array) * 2); //2 elements
(*array) = "Hey"; //equivalent to array[0]
*(array + 1) = "There"; //array[1]
printf("%s", array[1]); //outputs There
</code></pre>
<p>The <code>[]</code> operator on arrays does essentially pointer arithmetic on the front pointer, so, the way <code>array[1]</code> would be evaluated is as follows:</p>
<pre><code>array[1] == *(array + 1);
</code></pre>
<p>This is one of the reasons why array indices start from <code>0</code>, because:</p>
<pre><code>array[0] == *(array + 0) == *(array);
</code></pre> |
4,457,274 | How to specify table's height such that a vertical scroll bar appears? | <p>I have a table with many rows on my page. I would like to set table's height, say for 500px, such that if the height of the table is bigger than that, a vertical scroll bar will appear. I tried to use CSS <code>height</code> attribute on the <code>table</code>, but it doesn't work.</p> | 4,457,290 | 5 | 3 | null | 2010-12-16 03:52:00.847 UTC | 19 | 2022-09-09 11:34:42.88 UTC | 2017-01-02 22:50:14.58 UTC | null | 4,370,109 | null | 247,243 | null | 1 | 117 | css|css-tables | 236,217 | <p>Try using the <code>overflow</code> CSS property. There are also separate properties to define the behaviour of just horizontal overflow (<code>overflow-x</code>) and vertical overflow (<code>overflow-y</code>).</p>
<p>Since you only want the vertical scroll, try this:</p>
<pre><code>table {
height: 500px;
overflow-y: scroll;
}
</code></pre>
<hr />
<p><strong>EDIT:</strong></p>
<p>Apparently <code><table></code> elements don't respect the <code>overflow</code> property. This appears to be because <code><table></code> elements are not rendered as <code>display: block</code> by default (they actually have their own display type). You can force the <code>overflow</code> property to work by setting the <code><table></code> element to be a block type:</p>
<pre><code>table {
display: block;
height: 500px;
overflow-y: scroll;
}
</code></pre>
<p>Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the containing element, you need to specify an explicit width for the element as well.</p> |
4,662,442 | C# Get/Set Syntax Usage | <p>These are declarations for a Person class. </p>
<pre><code>protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }
</code></pre>
<p>How do I go about using the get/set? In main, I instantiate a </p>
<pre><code>Person Tom = new Person();
</code></pre>
<p>How does Tom.set/get??</p>
<p>I am use to doing C++ style where you just write out the int getAge() and void setAge() functions. But in C# there are shortcuts handling get and set? </p> | 4,662,455 | 7 | 2 | null | 2011-01-11 20:46:24.337 UTC | 11 | 2017-10-05 00:23:29.167 UTC | 2015-05-19 19:56:51.903 UTC | null | 1,060,900 | null | 438,339 | null | 1 | 34 | c#|syntax|properties | 138,174 | <p>Assuming you have access to them (the properties you've declared are <code>protected</code>), you use them like this:</p>
<pre><code>Person tom = new Person();
tom.Title = "A title";
string hisTitle = tom.Title;
</code></pre>
<p>These are <a href="http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx" rel="noreferrer"><em>properties</em></a>. They're basically pairs of getter/setter methods (although you can have just a getter, or just a setter) with appropriate metadata. The example you've given is of <em>automatically implemented properties</em> where the compiler is adding a backing field. You can write the code yourself though. For example, the <code>Title</code> property you've declared is like this:</p>
<pre><code>private string title; // Backing field
protected string Title
{
get { return title; } // Getter
set { title = value; } // Setter
}
</code></pre>
<p>... except that the backing field is given an "unspeakable name" - one you can't refer to in your C# code. You're forced to go through the property itself.</p>
<p>You can make one part of a property more restricted than another. For example, this is quite common:</p>
<pre><code>private string foo;
public string Foo
{
get { return foo; }
private set { foo = value; }
}
</code></pre>
<p>or as an automatically implemented property:</p>
<pre><code>public string Foo { get; private set; }
</code></pre>
<p>Here the "getter" is public but the "setter" is private.</p> |
4,444,620 | How do I add a column to an rdlc's dataset and have it appear for use in the report? | <p>I have an rdlc that has a separately-defined dataset. The time has come that I have the need to add a column to one of the tables, which I can do without issue. However, when I open the rdlc to use the new column, it does not appear in the Report Data pane.</p>
<p>This issue was reported to Microsoft <a href="http://connect.microsoft.com/VisualStudio/feedback/details/106561/rdlc-files-reports-dont-update-when-dataset-changes" rel="noreferrer">here</a>, but it was closed as by design. The workaround offered with the issue does not seem to work for VS2010 (refresh the dataset or the table; neither does anything).</p>
<p>Has anyone seen this problem, and if so, how did you get around it?</p> | 4,452,116 | 8 | 1 | null | 2010-12-14 21:49:31.407 UTC | 5 | 2017-06-08 06:04:47.72 UTC | null | null | null | null | 467,210 | null | 1 | 38 | .net|visual-studio-2010|rdlc | 44,326 | <p>Well, I resolved my problem, but I don't like how I had to do it.</p>
<p>For reference, (as far as I can tell) the only way to add a column to a dataset that is already attached to an rdlc is to hand-edit the xml (i.e. open the rdlc with your favorite text editor and add a <code>Field</code> to the appropriate table). After doing this, the field appears in the <code>Report Data</code> pane, and I can use it as if it were there from the beginning.</p>
<p>I would still like to know how to perform this seemingly simple task from the UI, but nonetheless my current problem is solved.</p> |
4,728,933 | function switching between singular and plural? | <p>I'm looking for a function that given a string it switches the string to singular/plural. I need it to work for european languages other than English.</p>
<p>Are there any functions that can do the trick? (Given a string to convert and the language?)</p>
<p>Thanks</p> | 4,729,288 | 10 | 8 | null | 2011-01-18 20:58:06.473 UTC | 10 | 2021-07-30 09:24:19.07 UTC | 2019-04-30 10:47:10.487 UTC | null | 10,010,493 | null | 496,223 | null | 1 | 25 | php|singular|plural | 39,602 | <p>There is no function built into PHP for this type of operation. There are, however, some tools that you may be able to use to help accomplish your goal.</p>
<p>There is an unofficial Google Dictionary API which contains information on plurals. You can read more about <a href="http://googlesystem.blogspot.com/2009/12/on-googles-unofficial-dictionary-api.html" rel="noreferrer">that method here</a>. You'll need to parse a JSON object to find the appropriate items and this method tends to be a little bit slow.</p>
<p>The other method that comes to mind is to use aspell, or one of its relatives. I'm not sure how accurate the dictionaries are for languages other than English but I've used aspell to expand words into their various forms.</p>
<p>I know this is not the most helpful answer, but hopefully it gives you a general direction to search in.</p> |
4,222,176 | Why is iterating through a large Django QuerySet consuming massive amounts of memory? | <p>The table in question contains roughly ten million rows.</p>
<pre><code>for event in Event.objects.all():
print event
</code></pre>
<p>This causes memory usage to increase steadily to 4 GB or so, at which point the rows print rapidly. The lengthy delay before the first row printed surprised me – I expected it to print almost instantly.</p>
<p>I also tried <code>Event.objects.iterator()</code> which behaved the same way.</p>
<p>I don't understand what Django is loading into memory or why it is doing this. I expected Django to iterate through the results at the database level, which'd mean the results would be printed at roughly a constant rate (rather than all at once after a lengthy wait).</p>
<p>What have I misunderstood?</p>
<p>(I don't know whether it's relevant, but I'm using PostgreSQL.)</p> | 4,222,432 | 10 | 1 | null | 2010-11-19 04:49:41 UTC | 34 | 2022-04-25 13:12:38.827 UTC | null | null | null | null | 312,785 | null | 1 | 132 | sql|django|postgresql|django-orm | 59,042 | <p>Nate C was close, but not quite.</p>
<p>From <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated" rel="noreferrer">the docs</a>:</p>
<blockquote>
<p>You can evaluate a QuerySet in the following ways:</p>
<ul>
<li><p>Iteration. A QuerySet is iterable, and it executes its database query the first time you iterate over it. For example, this will print the headline of all entries in the database:</p>
<pre><code>for e in Entry.objects.all():
print e.headline
</code></pre></li>
</ul>
</blockquote>
<p>So your ten million rows are retrieved, all at once, when you first enter that loop and get the iterating form of the queryset. The wait you experience is Django loading the database rows and creating objects for each one, before returning something you can actually iterate over. Then you have everything in memory, and the results come spilling out.</p>
<p>From my reading of the docs, <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#iterator" rel="noreferrer"><code>iterator()</code></a> does nothing more than bypass QuerySet's internal caching mechanisms. I think it might make sense for it to a do a one-by-one thing, but that would conversely require ten-million individual hits on your database. Maybe not all that desirable.</p>
<p>Iterating over large datasets efficiently is something we still haven't gotten quite right, but there are some snippets out there you might find useful for your purposes:</p>
<ul>
<li><a href="http://djangosnippets.org/snippets/1949/" rel="noreferrer">Memory Efficient Django QuerySet iterator</a></li>
<li><a href="http://djangosnippets.org/snippets/1170/" rel="noreferrer">batch querysets</a></li>
<li><a href="http://djangosnippets.org/snippets/1400/" rel="noreferrer">QuerySet Foreach</a></li>
</ul> |
4,346,580 | How to add a method to Enumeration in Scala? | <p>In Java you could:</p>
<pre><code>public enum Enum {
ONE {
public String method() {
return "1";
}
},
TWO {
public String method() {
return "2";
}
},
THREE {
public String method() {
return "3";
}
};
public abstract String method();
}
</code></pre>
<p>How do you do this in Scala?</p>
<p>EDIT / Useful links:</p>
<ul>
<li><a href="https://github.com/rbricks/itemized" rel="noreferrer">https://github.com/rbricks/itemized</a></li>
<li><a href="http://pedrorijo.com/blog/scala-enums/" rel="noreferrer">http://pedrorijo.com/blog/scala-enums/</a></li>
</ul> | 19,080,686 | 11 | 3 | null | 2010-12-03 14:38:03.233 UTC | 11 | 2017-01-04 13:38:42.507 UTC | 2017-01-04 13:38:42.507 UTC | null | 61,628 | null | 61,628 | null | 1 | 39 | java|scala|enums|enumeration | 16,686 | <pre><code>object Unit extends Enumeration {
abstract class UnitValue(var name: String) extends Val(name) {
def m: Unit
}
val G = new UnitValue("g") {
def m {
println("M from G")
}
}
val KG = new UnitValue("kg") {
def m {
println("M from KG")
}
}
}
</code></pre> |
4,831,748 | Is ++i really faster than i++ in for-loops in java? | <p>In java I usually make a for-loop like following:</p>
<pre><code>for (int i = 0; i < max; i++) {
something
}
</code></pre>
<p>But recently a colleague typed it so:</p>
<pre><code>for (int i = 0; i < max; ++i) {
something
}
</code></pre>
<p>He said the latter would be faster. Is that true?</p> | 4,831,768 | 11 | 5 | null | 2011-01-28 18:29:44.097 UTC | 7 | 2015-08-10 09:11:46.64 UTC | 2011-01-28 18:46:33.907 UTC | null | 30,453 | null | 594,241 | null | 1 | 41 | java|loops|performance|premature-optimization | 10,565 | <p>No, it's not true. You could measure the performance by timing each loop for a large number of iterations, but I'm fairly certain they will be the same.</p>
<p>The myth came from C where <code>++i</code> was regarded as faster than <code>i++</code> because the former can be implemented by incremeting i then returning it. The latter might be implemented by copying the value of i to a temporary variable, incrementing i, then returning the temporary. The first version doesn't need to make the temporary copy and so many people assume that it is faster. However if the expression is used as a statement modern C compilers can optimize the temporary copy away so that there will be no difference in practice.</p> |
14,530,717 | Avoid expunging timer on glassfish | <p>I have a method annotated with @Schedule that is called by the container once in a while.</p>
<pre><code>@Schedule(second = "*/5", minute = "*", hour = "*", persistent = false)
public void myTimerMethod() throws Exception {
...
}
</code></pre>
<p>Problem is on certain conditions i want to this method to throw an exception to cause the ongoing transaction to rollback. But if I do this more than two times the timer will be expunged and not called any more! </p>
<pre><code>INFO: EJB5119:Expunging timer ['68@@1359143163781@@server@@domain1' 'TimedObject = MyBean' 'Application = My-War' 'BEING_DELIVERED' 'PERIODIC' 'Container ID = 89072805830524936' 'Fri Jan 25 21:49:30 CET 2013' '0' '*/5 # * # * # * # * # * # * # null # null # null # true # myTimerMethod # 0' ] after [2] failed deliveries
</code></pre>
<p>I know i can configure timer rescheduling in domain.xml using</p>
<pre><code><domains>
...
<configs>
<config>
...
<ejb-container session-store="${com.sun.aas.instanceRoot}/session-store">
<ejb-timer-service>
<property name="reschedule-failed-timer" value="true"></property>
</ejb-timer-service>
</ejb-container>
...
</config>
</configs>
...
</domains>
</code></pre>
<p>But my question is, can I have this setting configured when i deploy my application? </p>
<p>Can't find it in:</p>
<pre><code>glassfish-resources.xml
glassfish-ejb-jar.xml
glassfish-web.xml
</code></pre>
<p>Is there some way to do it programmatically maybe?</p>
<p>(My rationale behind behind putting server-configuration like this in config files rather than configuring the server is so my app should be possible to install directly on a fresh installation of glassfish)</p> | 14,558,386 | 2 | 1 | null | 2013-01-25 21:30:46.17 UTC | 13 | 2018-12-14 16:43:52.58 UTC | 2013-11-29 10:42:02.183 UTC | null | 1,305,740 | null | 1,418,643 | null | 1 | 23 | java|glassfish|java-ee-6|ejb-3.1 | 8,945 | <p>I'd use a different approach.</p>
<p>Instead of throwing an exception directly from the scheduled method, try to introduce a level of indirection as in:</p>
<pre><code>...
@Inject RealWorkHere realImplementation;
@Schedule(second = "*/5", minute = "*", hour = "*", persistent = false)
public void myTimerMethod(){
try{
realImplementation.myTimerMethodImpl()
}catch (Exception x){
// hopefully log it somewhere
}
}
...
</code></pre>
<p>where <code>RealWorkHere</code> is the bean with the actual implementation as in:</p>
<pre><code>@Stateless
public class RealWorkHere{
@TransactionAttribute(REQUIRES_NEW)
public void myTimerMethod() throws Exception {
}
}
</code></pre>
<p>This comes with the benefit of:</p>
<ul>
<li>Not throwing an exception in a container-initated transaction (thus avoiding the expunging)</li>
<li>Better logging of the Exception</li>
<li>Clear demarcation of the 'real' business transaction</li>
</ul>
<h2>See also</h2>
<ul>
<li><a href="https://github.com/javaee/ejb-spec/issues/111" rel="noreferrer">ejb-spec #111: Please clearify the behaviour of an container if an application exception is thrown during the execution of a timer callback method</a></li>
</ul> |
2,338,661 | EF4 POCO: Snapshot vs Self-tracking over WCF | <p>Last year I developed a data access service for our project using Entity Framework (.NET3.5 of course) and using Julie Lerhman's book as a guide developed state tracking POCO objects. We use WCF and also have Silverlight 3 clients. We are moving to .NET 4.0 and I want to switch to using code generation to eliminate wasted developer time writing the POCO classes and the translation classes.</p>
<p>With the research I have done there seems to be 3 ways of state tracking POCOs:</p>
<p>1) Changed tracked proxies: Doesn't seem to be useful for us as it seems this doesn't work over WCF serialisation.</p>
<p>2) Snapshot based: Snapshot is taken when POCO entity graph is retrieved, returned graph from client is compared with that snapshot and differences are compared...seems good to me.</p>
<p>3) Self-Tracking Entities: Code generator generates logic for doing self tracking within the POCO objects. This seems close to what we do now except it is all generated for us.</p>
<p>I am trying to work out what the advantages and disadvantages are between all of these methods. I am guessing that 1 and 2 are "connected" and that they need the ObjectContext that the POCOs were originally queried from to remain instanciated, but haven't been able to confirm this. I also don't see a reason why anyone would really bother with option 1 given that option 3 seems to do the same and more...</p>
<p>Snapshot seems the simplest to me, but if this requires an ObjectContext to remain open for a long time I am not so sure...</p>
<p>I am only a junior programmer so any advice here, especially with regards to Silverlight 3 (I believe options 2 and 3 work with Silverlight 3 but 2 may have issues) is much appreciated.</p> | 2,345,222 | 2 | 2 | null | 2010-02-26 00:25:06.903 UTC | 9 | 2010-07-10 06:01:42.743 UTC | 2010-02-26 00:38:20.427 UTC | null | 150,759 | null | 150,759 | null | 1 | 12 | wcf|entity-framework|poco|snapshot|self-tracking-entities | 8,090 | <p>Go with Option 3. Self-Tracking Entities as this is what they were designed for. </p>
<p>"Self-tracking entities are optimized for serialization scenarios"</p>
<p><a href="http://blogs.msdn.com/adonet/pages/feature-ctp-walkthrough-self-tracking-entities-for-the-entity-framework.aspx" rel="noreferrer">This post</a> gives a good demonstration.</p> |
3,025,921 | Is there a performance gain from defining routes in app.yaml versus one large mapping in a WSGIApplication in AppEngine? | <h1>Scenario 1</h1>
<p>This involves using one "gateway" route in <code>app.yaml</code> and then choosing the <code>RequestHandler</code> in the <code>WSGIApplication</code>.</p>
<h2>app.yaml</h2>
<pre><code>- url: /.*
script: main.py
</code></pre>
<h2>main.py</h2>
<pre><code>from google.appengine.ext import webapp
class Page1(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 1")
class Page2(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 2")
application = webapp.WSGIApplication([
('/page1/', Page1),
('/page2/', Page2),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
</code></pre>
<hr>
<h1>Scenario 2:</h1>
<p>This involves defining two routes in <code>app.yaml</code> and then two separate scripts for each (<code>page1.py</code> and <code>page2.py</code>). </p>
<h2>app.yaml</h2>
<pre><code>- url: /page1/
script: page1.py
- url: /page2/
script: page2.py
</code></pre>
<h2>page1.py</h2>
<pre><code>from google.appengine.ext import webapp
class Page1(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 1")
application = webapp.WSGIApplication([
('/page1/', Page1),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
</code></pre>
<h2>page2.py</h2>
<pre><code>from google.appengine.ext import webapp
class Page2(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 2")
application = webapp.WSGIApplication([
('/page2/', Page2),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
</code></pre>
<hr>
<h1>Question</h1>
<p>What are the benefits and drawbacks of each pattern? Is one much faster than the other?</p> | 3,026,641 | 2 | 0 | null | 2010-06-11 20:15:42.457 UTC | 11 | 2010-06-11 22:24:02.543 UTC | 2010-06-11 20:26:20.477 UTC | null | 81,019 | null | 81,019 | null | 1 | 17 | python|performance|google-app-engine|yaml | 1,413 | <p>The only performance implication relates to the loading of modules: Modules are loaded on an instance when they're first used, and splitting things up requires fewer module loads to serve a page on a new instance.</p>
<p>This is pretty minimal, though, as you can just as easily have the handler script dynamically load the needed module on-demand - and that's what many common frameworks already do.</p>
<p>In general, app.yaml routing is designed for routing between distinct components or applications. For example, remote_api and deferred both have their own handlers. It's perfectly reasonable, therefore, to have a single handler defined for your app that handles everything else.</p> |
1,987,162 | pass arguments between shell scripts but retain quotes | <p>How do I pass all the arguments of one shell script into another? I have tried $*, but as I expected, that does not work if you have quoted arguments.</p>
<p>Example:</p>
<pre><code>$ cat script1.sh
#! /bin/sh
./script2.sh $*
$ cat script2.sh
#! /bin/sh
echo $1
echo $2
echo $3
$ script1.sh apple "pear orange" banana
apple
pear
orange
</code></pre>
<p>I want it to print out:</p>
<pre><code>apple
pear orange
banana
</code></pre> | 1,987,164 | 1 | 2 | null | 2009-12-31 21:25:21.71 UTC | 8 | 2014-08-29 16:54:04.797 UTC | null | null | null | null | 7,412 | null | 1 | 29 | shell|argument-passing | 13,098 | <p>Use <code>"$@"</code> instead of <code>$*</code> to preserve the quotes:</p>
<pre><code>./script2.sh "$@"
</code></pre>
<p>More info:</p>
<p><a href="http://tldp.org/LDP/abs/html/internalvariables.html" rel="noreferrer">http://tldp.org/LDP/abs/html/internalvariables.html</a></p>
<blockquote>
<p>$*<br>
All of the positional parameters, seen as a single word</p>
<p>Note: "$*" must be quoted.</p>
<p>$@<br>
Same as $*, but each parameter is a quoted string, that is, the
parameters are passed on intact, without interpretation or expansion.
This means, among other things, that each parameter in the argument
list is seen as a separate word.</p>
<p>Note: Of course, "$@" should be quoted.</p>
</blockquote> |
27,016,554 | Hide label for input field | <p>I am trying to hide the label for a specific field in _form.php without success.</p>
<p>I have tried couple of variation like, but none is working:</p>
<pre><code><?= $form->field($model, 'sample_text')->textArea('label'=>false) ?>
</code></pre>
<p>and alternate code:</p>
<pre><code><?= $form->field($model, 'sample_text')->textArea('label'=>'') ?>
</code></pre>
<p>What is the right approach to hide a label? </p> | 27,016,851 | 7 | 0 | null | 2014-11-19 12:12:36.707 UTC | 4 | 2019-02-27 15:21:48.957 UTC | 2015-04-25 10:13:42.597 UTC | null | 1,203,805 | null | 1,124,993 | null | 1 | 35 | forms|yii|yii2|yii-widgets | 59,041 | <p>Ok, I found the solution.</p>
<pre><code><?= $form->field($model, 'sample_text')->textArea()->label(false) ?>
</code></pre> |
24,056,985 | How to know if a number is odd or even in Swift? | <p>I have an array of numbers typed <code>Int</code>.</p>
<p>I want to loop through this array and determine if each number is odd or even.</p>
<p>How can I determine if a number is odd or even in Swift?</p> | 24,057,238 | 5 | 0 | null | 2014-06-05 09:52:19.663 UTC | 8 | 2020-08-02 10:33:18.803 UTC | 2020-05-23 04:05:13.417 UTC | null | 1,265,393 | null | 3,218,559 | null | 1 | 63 | ios|swift|parity | 79,470 | <pre><code>var myArray = [23, 54, 51, 98, 54, 23, 32];
for myInt: Int in myArray{
if myInt % 2 == 0 {
println("\(myInt) is even number")
} else {
println("\(myInt) is odd number")
}
}
</code></pre> |
27,592,601 | Ruby: Variables defined in If/else statement are accessible outside of if/else? | <pre><code>def foo
#bar = nil
if true
bar = 1
else
bar = 2
end
bar #<-- shouldn't this refer to nil since the bar from the if statement is removed from the stack?
end
puts foo # prints "1"
</code></pre>
<p>I always thought you had to make a temporary variable and define it as nil or an initial value so that variables defined inside an if/else statement would persist outside the scope of the if/else statement and not disappear off the stack?? Why does it print 1 and not nil?</p> | 27,592,715 | 1 | 0 | null | 2014-12-21 18:50:16.357 UTC | 6 | 2014-12-21 19:30:01.847 UTC | null | null | null | null | 1,555,312 | null | 1 | 34 | ruby | 11,742 | <p>Variables are local to a function, class or module defintion, a <code>proc</code>, a block.</p>
<p>In ruby <code>if</code> is an expression and the branches don't have their own scope.</p>
<p>Also note that whenever the parser sees a variable assignment, it will create a variable in the scope, <a href="https://stackoverflow.com/questions/12928050/why-does-ruby-seem-to-hoist-variable-declarations-from-inside-a-case-statement-e">even if that code path isn't executed</a>:</p>
<pre><code>def test
if false
a = 1
end
puts a
end
test
# ok, it's nil.
</code></pre>
<p>It's bit similar to JavaScript, though it doesn't hoist the variable to the top of the scope:</p>
<pre><code>def test
puts a
a = 1
end
test
# NameError: undefined local variable or method `a' for ...
</code></pre>
<p>So even if what you were saying were true, it still wouldn't be <code>nil</code>.</p> |
3,036,638 | how to extract web page textual content in java? | <p>i am looking for a method to extract text from web page (initially html) using jdk or another library . please help</p>
<p>thanks</p> | 3,036,668 | 3 | 1 | null | 2010-06-14 10:59:35.373 UTC | 9 | 2015-07-16 09:14:47.377 UTC | null | null | null | null | 161,222 | null | 1 | 6 | java | 26,070 | <p>Use a <a href="http://www.google.co.id/search?q=Java+HTML+parser" rel="nofollow noreferrer">HTML parser</a> if at all possible; there are many available for Java.</p>
<p>Or you can use regex like many people do. This is generally not advisable, however, unless you're doing very simplistic processing.</p>
<h3>Related questions</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/238036/java-html-parsing"> Java HTML Parsing </a></li>
<li><a href="https://stackoverflow.com/questions/2168610/which-html-parser-is-best"> Which Html Parser is best? </a></li>
<li><a href="https://stackoverflow.com/questions/1806131/any-good-java-html-parsers">Any good Java HTML parsers?</a></li>
<li><a href="https://stackoverflow.com/questions/709233/recommendations-for-a-java-html-parser-editor"> recommendations for a java HTML parser/editor </a></li>
<li><a href="https://stackoverflow.com/questions/26638/what-html-parsing-libraries-do-you-recommend-in-java"> What HTML parsing libraries do you recommend in Java </a></li>
</ul>
<p>Text extraction:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/1386107/text-extraction-from-html-java"> Text Extraction from HTML Java </a></li>
<li><a href="https://stackoverflow.com/questions/2609948/text-extraction-with-java-html-parsers">Text extraction with java html parsers</a></li>
</ul>
<p>Tag stripping:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/832620/stripping-html-tags-in-java"> Stripping HTML tags in Java </a></li>
<li><a href="https://stackoverflow.com/questions/560605/how-to-strip-html-attributes-except-src-and-alt-in-java"> How to strip HTML attributes except “src” and “alt” in JAVA </a></li>
<li><a href="https://stackoverflow.com/questions/240546/removing-html-from-a-java-string"> Removing HTML from a Java String </a></li>
</ul> |
38,524,150 | MongoDB replica set with simple password authentication | <p>I have a MongoDB replica set of 3 servers (1 primary, 1 secondary, 1 arbiter; this is the default replica set created by Google Cloud 1-click install). The 2 config files (mongod.conf) of primary server and secondary server have been changed with <code>security.authorization: enabled</code> added.</p>
<p>Root user is added with the following MongoDB shell command:</p>
<pre><code>use admin
db.createUser({user:"root",pwd:"root",roles:["root"]})
</code></pre>
<p>After restarting MongoDB services on the primary and secondary servers with "sudo service mongod restart", connection to the replica set turns unstable.</p>
<p>rs.status() sometimes give the result as</p>
<ul>
<li>1 primary, 1 unreachable, 1 arbiter</li>
<li>1 secondary, 1 secondary, 1 arbiter</li>
<li>1 secondary, 1 unreachable, 1 arbiter</li>
</ul>
<p><strong>How to setup basic password authentication (not using keyfile) for MongoDB replica set the correct way?</strong></p> | 38,559,911 | 1 | 4 | null | 2016-07-22 10:28:55.377 UTC | 10 | 2021-08-13 21:11:02.883 UTC | 2021-08-13 21:11:02.883 UTC | null | 177,920 | null | 5,581,893 | null | 1 | 19 | mongodb|authentication|replicaset|database|nosql | 28,800 | <p>I finally found the answer. MongoDB replica set needs both user account and keyfile. Keyfile seems for authentication between servers in the replica set, not for logging in.</p>
<p>Create mongodb key file on linux, copy to all db servers with mode <code>600</code> intact:</p>
<pre><code>cd
openssl rand -base64 741 > mongodb.key
chmod 600 mongodb.key
</code></pre>
<p>mongod.conf file:</p>
<pre><code>replication:
replSetName: rs0
security:
authorization: enabled
keyFile: /home/USERNAME/mongodb.key
</code></pre>
<p>Admin user:</p>
<pre><code>(just like in question content)
</code></pre> |
43,573,297 | Put request with simple string as request body | <p>When I execute the following code from my browser the server gives me 400 and complains that the request body is missing. Anybody got a clue about how I can pass a simple string and have it send as the request body?</p>
<pre><code> let content = 'Hello world'
axios.put(url, content).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
</code></pre>
<p>If I wrap content in [] it comes thru. But then the server receives it as a string beginning with [ and ending with ]. Which seems odd.</p>
<p>After fiddling around I discovered that the following works</p>
<pre><code> let req = {
url,
method: 'PUT',
data: content
}
axios(req).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
</code></pre>
<p>But shouldn't the first one work as well?</p> | 50,364,961 | 9 | 0 | null | 2017-04-23 15:53:30.973 UTC | 12 | 2021-12-18 22:28:11.343 UTC | 2018-03-02 11:21:51.693 UTC | null | 1,175,081 | null | 672,009 | null | 1 | 48 | javascript|axios | 171,900 | <p>I solved this by overriding the default Content-Type:</p>
<pre><code>const config = { headers: {'Content-Type': 'application/json'} };
axios.put(url, content, config).then(response => {
...
});
</code></pre>
<p>Based on my experience, the default <code>Conent-Type</code> is <code>application/x-www-form-urlencoded</code> for strings, and <code>application/json</code> for objects (including arrays). Your server probably expects JSON.</p> |
26,014,368 | C++11 move when returning a lock | <p>In the book "C++ Concurrency in Action" reading the following method</p>
<pre><code>std::unique_lock<std::mutex> wait_for_data()
{
std::unique_lock<std::mutex> head_lock(head_mutex);
data_cond.wait(head_lock,[&]{return head.get()!=get_tail();});
return std::move(head_lock);
}
</code></pre>
<p>I cannot understand why the head_lock is std::move-ed when returned. My notion and gut feeling of the move usage and RVO matches the opinion shared in <a href="https://stackoverflow.com/questions/4986673/c11-rvalues-and-move-semantics-confusion-return-statement">C++11 rvalues and move semantics confusion (return statement)</a> </p>
<p>But I kind of tend to trust the author to know better. Can someone clarify when std::move the return value is better and is there something specifically about the locks? Thanks.</p> | 26,014,561 | 1 | 0 | null | 2014-09-24 10:17:47.467 UTC | 5 | 2014-12-21 19:32:48.13 UTC | 2017-05-23 11:59:23.063 UTC | null | -1 | user2026095 | null | null | 1 | 33 | c++|c++11|move-semantics|rvo | 3,795 | <p>It's fine with or without the <code>std::move</code>. The name of a local variable<sup>*</sup> is treated as an rvalue in the <code>return</code> statement, causing the move constructor to be invoked in both cases. The authors presumably used <code>std::move</code> for stylistic reasons, to make it clear that the lock is being moved. It does interfere with NRVO, but the cost of moving a <code>unique_lock</code> here is probably minimal compared to the cost of the lock and the wait. </p>
<p>In @Deduplicator's words, it's "a pessimization in order to emphasize the actual semantics".</p>
<p>You can test this yourself - <code>unique_lock</code> can't be copied, so <code>return head_lock;</code> wouldn't have compiled if it were a copy.</p>
<hr>
<p><sub><sup>*</sup> This is the C++14 rule. The C++11 rule is <a href="https://stackoverflow.com/questions/25875596/can-returning-a-local-variable-by-value-in-c11-14-result-in-the-return-value-b/25876175#25876175">restricted to cases where copy elision is allowed or would be allowed except for the fact that the variable is a function parameter</a>. This difference is immaterial as far as this question is concerned, since <code>head_lock</code> obviously qualifies for copy elision. </sub></p> |
24,593,967 | How to pass an anonymous function to the pipe in Elixir | <p>I'd like to write the code like this:</p>
<pre><code>def boundary do
:crypto.rand_bytes(8)
|> Base.encode16
|> &("--------FormDataBoundary" <> &1)
end
</code></pre>
<p>But it doesn't work.</p> | 24,603,914 | 6 | 0 | null | 2014-07-06 08:16:14.763 UTC | 6 | 2022-04-29 09:54:49.597 UTC | 2014-07-08 06:44:28.577 UTC | null | 854,408 | null | 854,408 | null | 1 | 46 | elixir | 11,216 | <p>It will look bit weird but must work:</p>
<pre><code>def boundary do
:crypto.rand_bytes(8)
|> Base.encode16
|> (&("--------FormDataBoundary" <> &1)).()
end
</code></pre> |
39,251,005 | Strange generic function appear in view controller after converting to swift 3 | <p>In my project, after converting to swift 3, a new function appeared before my <code>ViewController</code> class: </p>
<pre><code>fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
</code></pre>
<p>What does this function do? Why do I need it? </p> | 39,251,234 | 1 | 0 | null | 2016-08-31 13:29:09.19 UTC | 7 | 2016-08-31 13:42:10.203 UTC | null | null | null | null | 4,883,974 | null | 1 | 40 | ios|swift|swift3 | 3,294 | <p>That is interesting. Before the latest Swift 3, you could
compare <em>optional</em> values, for example</p>
<pre><code>let a: Int? = nil
let b: Int? = 4
print(a < b) // true
</code></pre>
<p>and <code>nil</code> was considered less than all non-optional values.</p>
<p>This feature has been removed (<a href="https://github.com/apple/swift-evolution/blob/master/proposals/0121-remove-optional-comparison-operators.md">SE-0121 – Remove Optional Comparison Operators</a>) and the above code would fail to compile
in Xcode 8 beta 6 with</p>
<pre>
error: value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
</pre>
<p>Apparently, the Swift migrator solves that problem for you by
providing a custom <code><</code> operator which takes two optional operands
and therefore "restores" the old behavior.</p>
<p>If you remove that definition then you should see where the
comparison is done in your code. Then try to update your code
and remove the optional comparisons. </p> |
50,521,494 | Angular 2 Routing navigate run in new tab(Use Angular Router naviagte ) | <p>How to open a new browser Tab , if using router.navigate .</p>
<pre><code>this.router.navigate([]).then(result => { window.location.href = link; });
</code></pre> | 50,521,527 | 6 | 1 | null | 2018-05-25 04:19:30.377 UTC | 4 | 2021-09-01 09:53:28.96 UTC | 2018-05-25 04:29:08.427 UTC | null | 4,510,146 | null | 4,510,146 | null | 1 | 22 | angular|angular-routing|angular-router | 43,032 | <p>Try this one.</p>
<pre><code>this.router.navigate([]).then(result => { window.open(link, '_blank'); });
</code></pre> |
2,469,466 | Refreshing a LinearLayout after adding a view | <p>I'm trying to add views dynamically to a linearlayout.
I see through getChildCount() that the views are added to the layout, but even calling invalidate() on the layout doesn't give me the childs showed up.</p>
<p>Am I missing something?</p> | 2,469,920 | 3 | 2 | null | 2010-03-18 11:39:11.903 UTC | 6 | 2015-03-21 08:20:18.213 UTC | 2010-06-09 16:39:15.653 UTC | null | 82,118 | null | 295,525 | null | 1 | 14 | android|drawable|android-linearlayout | 38,569 | <p>A couple of things you can check in your code:</p>
<ul>
<li>On the <a href="http://developer.android.com/reference/android/view/View.html" rel="noreferrer">View</a> that is being added, check that you call its <a href="http://developer.android.com/reference/android/view/View.html#setLayoutParams(android.view.ViewGroup.LayoutParams)" rel="noreferrer">setLayoutParameter</a> method with an appropriate <a href="http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html" rel="noreferrer">ViewGroup.LayoutParameter</a>.</li>
<li>When you adding the new <a href="http://developer.android.com/reference/android/view/View.html" rel="noreferrer">View</a>s, make sure you are doing it on the UI thread. To do this, you can use the parent <a href="http://developer.android.com/reference/android/view/View.html" rel="noreferrer">View</a>'s <a href="http://developer.android.com/reference/android/view/View.html#post(java.lang.Runnable)" rel="noreferrer">post</a> method.</li>
</ul>
<p>This self contained example adds a <a href="http://developer.android.com/reference/android/widget/TextView.html" rel="noreferrer">TextView</a> after a short delay when it starts:</p>
<pre><code>import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ProgrammticView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT));
setContentView(layout);
// This is just going to programatically add a view after a short delay.
Timer timing = new Timer();
timing.schedule(new TimerTask() {
@Override
public void run() {
final TextView child = new TextView(ProgrammticView.this);
child.setText("Hello World!");
child.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
// When adding another view, make sure you do it on the UI
// thread.
layout.post(new Runnable() {
public void run() {
layout.addView(child);
}
});
}
}, 5000);
}
}
</code></pre> |
2,582,551 | How to apply CSS to HTML body element? | <p>I am trying to get rid of this:</p>
<pre><code>document.body.className = "someclass";
</code></pre>
<p>I want to do this in CSS. </p>
<pre><code>body.someclass {
.
.
.
}
</code></pre>
<p>unfortunately I am not able to get this working in Firefox, chrome. </p>
<p>Am I doing anything wrong here? Is there any way we could apply a CSS class to body?</p> | 2,582,564 | 3 | 0 | null | 2010-04-06 03:52:36.687 UTC | 3 | 2016-12-15 16:57:29.767 UTC | null | null | null | null | 57,937 | null | 1 | 17 | javascript|html|xhtml|css | 65,516 | <p>You are doing two different things there. Your JavaScript is actually assigning the class "someclass" to your body element, while your CSS is <em>styling</em> a body element with the class "someclass", it won't assign the class to it, that is not the task of CSS. You would do it in plain (X)HTML like this:</p>
<pre><code><body class="someclass">
</code></pre> |
2,572,015 | NHibernate, and odd "Session is Closed!" errors | <p><em>Note: Now that I've typed this out, I have to apologize for the super long question, however, I think all the code and information presented here is in some way relevant.</em></p>
<hr>
<p>Okay, I'm getting odd "Session Is Closed" errors, at random points in my ASP.NET webforms application. Today, however, it's finally happening in the same place over and over again. I am near certain that nothing is disposing or closing the session in my code, as the bits of code that use are well contained away from all other code as you'll see below.</p>
<p>I'm also using ninject as my IOC, which may / may not be important.</p>
<p>Okay, so, First my <code>SessionFactoryProvider</code> and <code>SessionProvider</code> classes:</p>
<hr>
<p><strong>SessionFactoryProvider</strong></p>
<pre><code>public class SessionFactoryProvider : IDisposable
{
ISessionFactory sessionFactory;
public ISessionFactory GetSessionFactory()
{
if (sessionFactory == null)
sessionFactory =
Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2005.ConnectionString(p =>
p.FromConnectionStringWithKey("QoiSqlConnection")))
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<JobMapping>())
.BuildSessionFactory();
return sessionFactory;
}
public void Dispose()
{
if (sessionFactory != null)
sessionFactory.Dispose();
}
}
</code></pre>
<hr>
<p><strong><em>SessionProvider</em></strong></p>
<pre><code>public class SessionProvider : IDisposable
{
ISessionFactory sessionFactory;
ISession session;
public SessionProvider(SessionFactoryProvider sessionFactoryProvider)
{
this.sessionFactory = sessionFactoryProvider.GetSessionFactory();
}
public ISession GetCurrentSession()
{
if (session == null)
session = sessionFactory.OpenSession();
return session;
}
public void Dispose()
{
if (session != null)
{
session.Dispose();
}
}
}
</code></pre>
<hr>
<p>These two classes are wired up with Ninject as so:</p>
<p><strong><em>NHibernateModule</em></strong></p>
<pre><code>public class NHibernateModule : StandardModule
{
public override void Load()
{
Bind<SessionFactoryProvider>().ToSelf().Using<SingletonBehavior>();
Bind<SessionProvider>().ToSelf().Using<OnePerRequestBehavior>();
}
}
</code></pre>
<hr>
<p>and as far as I can tell work as expected.</p>
<p>Now my <code>BaseDao<T></code> class:</p>
<hr>
<p><strong><em>BaseDao</em></strong></p>
<pre><code>public class BaseDao<T> : IDao<T> where T : EntityBase
{
private SessionProvider sessionManager;
protected ISession session { get { return sessionManager.GetCurrentSession(); } }
public BaseDao(SessionProvider sessionManager)
{
this.sessionManager = sessionManager;
}
public T GetBy(int id)
{
return session.Get<T>(id);
}
public void Save(T item)
{
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(item);
transaction.Commit();
}
}
public void Delete(T item)
{
using (var transaction = session.BeginTransaction())
{
session.Delete(item);
transaction.Commit();
}
}
public IList<T> GetAll()
{
return session.CreateCriteria<T>().List<T>();
}
public IQueryable<T> Query()
{
return session.Linq<T>();
}
}
</code></pre>
<hr>
<p>Which is bound in Ninject like so:</p>
<hr>
<p><strong><em>DaoModule</em></strong></p>
<pre><code>public class DaoModule : StandardModule
{
public override void Load()
{
Bind(typeof(IDao<>)).To(typeof(BaseDao<>))
.Using<OnePerRequestBehavior>();
}
}
</code></pre>
<hr>
<p>Now the web request that is causing this is when I'm saving an object, it didn't occur till I made some model changes today, however the changes to my model has not changed the data access code in anyway. Though it changed a few NHibernate mappings (I can post these too if anyone is interested)</p>
<p>From as far as I can tell, <code>BaseDao<SomeClass>.Get</code> is called then <code>BaseDao<SomeOtherClass>.Get</code> is called then <code>BaseDao<TypeImTryingToSave>.Save</code> is called.</p>
<p>it's the third call at the line in <code>Save()</code></p>
<pre><code>using (var transaction = session.BeginTransaction())
</code></pre>
<p>that fails with "Session is Closed!" or rather the exception:</p>
<pre><code>Session is closed!
Object name: 'ISession'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ObjectDisposedException: Session is closed!
Object name: 'ISession'.
</code></pre>
<p>And indeed following through on the Debugger shows the third time the session is requested from the <code>SessionProvider</code> it is indeed closed and not connected.</p>
<p>I have verified that <code>Dispose</code> on my <code>SessionFactoryProvider</code> and on my <code>SessionProvider</code> are called at the end of the request and not before the <code>Save</code> call is made on my Dao.</p>
<p>So now I'm a little stuck. A few things pop to mind. </p>
<ul>
<li>Am I doing anything obviously wrong?</li>
<li>Does NHibernate ever close sessions without me asking to?</li>
<li>Any workarounds or ideas on what I might do?</li>
</ul>
<p>Thanks in advance</p> | 2,572,399 | 3 | 5 | null | 2010-04-03 17:21:24.737 UTC | 10 | 2014-12-11 20:21:27.043 UTC | null | null | null | null | 1,610 | null | 1 | 18 | c#|asp.net|nhibernate|ninject | 22,060 | <p>ASP.NET is multi-threaded so access to the ISession must be thread safe. Assuming you're using session-per-request, the easiest way to do that is to use NHibernate's built-in handling of <a href="http://knol.google.com/k/fabio-maulo/nhibernate-chapter-2/1nr4enxv3dpeq/6#" rel="noreferrer">contextual sessions</a>.</p>
<p>First configure NHibernate to use the web session context class:</p>
<pre><code>sessionFactory = Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2005.ConnectionString(p =>
p.FromConnectionStringWithKey("QoiSqlConnection")))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<JobMapping>())
.ExposeConfiguration(x => x.SetProperty("current_session_context_class", "web")
.BuildSessionFactory();
</code></pre>
<p>Then use the <code>ISessionFactory.GetCurrentSession()</code> to get an existing session, or bind a new session to the factory if none exists. Below I'm going to cut+paste my code for opening and closing a session.</p>
<pre><code> public ISession GetContextSession()
{
var factory = GetFactory(); // GetFactory returns an ISessionFactory in my helper class
ISession session;
if (CurrentSessionContext.HasBind(factory))
{
session = factory.GetCurrentSession();
}
else
{
session = factory.OpenSession();
CurrentSessionContext.Bind(session);
}
return session;
}
public void EndContextSession()
{
var factory = GetFactory();
var session = CurrentSessionContext.Unbind(factory);
if (session != null && session.IsOpen)
{
try
{
if (session.Transaction != null && session.Transaction.IsActive)
{
session.Transaction.Rollback();
throw new Exception("Rolling back uncommited NHibernate transaction.");
}
session.Flush();
}
catch (Exception ex)
{
log.Error("SessionKey.EndContextSession", ex);
throw;
}
finally
{
session.Close();
session.Dispose();
}
}
}
</code></pre> |
3,033,554 | Why is this field declared as private and also readonly? | <p>In the following code:</p>
<pre><code>public class MovieRepository : IMovieRepository
{
private readonly IHtmlDownloader _downloader;
public MovieRepository(IHtmlDownloader downloader)
{
_downloader = downloader;
}
public Movie FindMovieById(string id)
{
var idUri = ...build URI...;
var html = _downloader.DownloadHtml(idUri);
return ...parse ID HTML...;
}
public Movie FindMovieByTitle(string title)
{
var titleUri = ...build URI...;
var html = _downloader.DownloadHtml(titleUri);
return ...parse title HTML...;
}
}
</code></pre>
<p><a href="https://stackoverflow.com/questions/3029596/need-some-suggestions-on-my-softwares-architecture-code-review">I asked for something to review my code</a>, and someone suggested this approach. My question is why is the IHtmlDownloader variable readonly?</p> | 3,033,558 | 3 | 0 | null | 2010-06-13 19:20:11.213 UTC | 4 | 2022-01-24 19:51:39.77 UTC | 2017-05-23 12:10:29.303 UTC | null | -1 | null | 112,355 | null | 1 | 36 | c#|.net|interface|readonly | 29,940 | <p>If it's private and <code>readonly</code>, the benefit is that you can't inadvertently change it from another part of that class after it is initialized. The <code>readonly</code> modifier ensures the field can only be given a value during its initialization or in its class constructor.</p>
<p>If something functionally should not change after initialization, it's always good practice to use available language constructs to enforce that.</p>
<p>On a related note, C# 9 introduces the <code>init</code> <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/init" rel="nofollow noreferrer">accessor method</a> for properties, which indicates the property value can only be set during object construction, e.g.:</p>
<pre><code>class InitExample
{
private double _seconds;
public double Seconds
{
get { return _seconds; }
init { _seconds = value; }
}
}
</code></pre> |
2,693,180 | What is unchecked cast and how do I check it? | <p>I think I get what unchecked cast means (casting from one to another of a different type), but what does it mean to "Check" the cast? How can I check the cast so that I can avoid this warning in Eclipse?</p> | 2,693,188 | 3 | 1 | null | 2010-04-22 17:52:04.727 UTC | 15 | 2020-04-15 05:05:17.213 UTC | 2017-05-02 02:35:46.373 UTC | null | 1,267,663 | null | 300,414 | null | 1 | 40 | java|eclipse|casting|unchecked | 38,970 | <p>Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around. E.g. this line</p>
<pre><code>Set<String> set = new HashSet();
</code></pre>
<p>will produce such a warning.</p>
<p>Usually there is a good reason for such warnings, so you should try to improve your code instead of suppressing the warning. Quote from Effective Java, 2nd Edition:</p>
<blockquote>
<p><strong>Eliminate every unchecked warning that you can.</strong> If you
eliminate all warnings, you are assured that your code is typesafe, which is a very
good thing. It means that you won’t get a <code>ClassCastException</code> at runtime, and it
increases your confidence that your program is behaving as you intended.</p>
<p>If you can’t eliminate a warning, and you can prove that the code that
provoked the warning is typesafe, then (and only then) suppress the warning
with an <code>@SuppressWarnings("unchecked")</code> annotation. If you suppress warnings
without first proving that the code is typesafe, you are only giving yourself a
false sense of security. The code may compile without emitting any warnings, but
it can still throw a <code>ClassCastException</code> at runtime. If, however, you ignore
unchecked warnings that you know to be safe (instead of suppressing them), you
won’t notice when a new warning crops up that represents a real problem. The
new warning will get lost amidst all the false alarms that you didn’t silence.</p>
</blockquote>
<p>Of course, it is not always as easy to eliminate warnings as with the code above. Without seeing your code, there is no way to tell how to make it safe though.</p> |
2,705,076 | Difference between writing to file atomically and not | <p>What is the difference in writing to files atomically on the iPhone in objective-c and not, is there any performance difference between the two?</p> | 2,705,102 | 3 | 0 | null | 2010-04-24 15:48:02.023 UTC | 8 | 2020-04-09 18:15:50.167 UTC | 2020-04-09 18:15:50.167 UTC | null | 322,020 | null | 304,725 | null | 1 | 44 | iphone|objective-c|file-io | 14,756 | <p>Atomic in general means the operation <del>cannot be interrupted</del> will complete or have no effect. When writing files, that is accomplished by writing to a temporary file then replacing the original with the temporary when the write completes.</p>
<p>A crash while writing an atomic file means the original is not modified and there is a garbage file that can be deleted. A crash while writing normally would mean an expected good file is corrupt.</p>
<p>Performance wise the cost is minimal. During the write you will have two copies of a file. The file replace is a very simple operation at the file system level.</p>
<p>Edit: thanks zneak</p> |
40,422,790 | Relative Link to Repo's Root from Markdown file | <h3>I need to have a relative link to root of my repo from markdown file</h3>
<p>(I need it working for any forks)</p>
<p>So it looks like the only way it's to provide a link to <strong>some file</strong> in the root:</p>
<p><code>the [Root](/README.md)</code></p>
<p>or</p>
<p><code>the [Root](../README.md)</code></p>
<p>(if it's located at /doc/README.md for instance)</p>
<p>At the same time I can refer to any folder without referring to a file</p>
<p><code>the [Doc](/doc)</code></p>
<p>But if I try to put a link to the root folder:</p>
<p><code>the [real root](/)</code></p>
<p><code>the [real root](../)</code></p>
<p>I'll have a link such</p>
<p><a href="https://github.com/UserName/RepoName/" rel="noreferrer">https://github.com/UserName/RepoName/</a><strong>blob/master</strong></p>
<p>which unlike the </p>
<p><a href="https://github.com/UserName/RepoName/" rel="noreferrer">https://github.com/UserName/RepoName/</a><strong>blob/master</strong><em>/doc</em></p>
<p>refers to 404</p>
<p>So if I don't want to refer to README.md in the root (I could havn't it at all)</p>
<h3>Is there any way to have such a link?</h3> | 40,440,270 | 2 | 0 | null | 2016-11-04 12:33:27.927 UTC | 11 | 2020-04-09 12:53:55.8 UTC | 2018-06-21 15:05:49.9 UTC | null | 2,482,441 | null | 5,721,315 | null | 1 | 33 | github|markdown|readme | 21,682 | <p>After some research I've found this solution:</p>
<p><code>[the real relative root of any fork](/../../)</code></p>
<p>It always points to the default branch. For me it's Ok, so it's up to you</p>
<p>PS</p>
<p>With such a trick you can also access the following abilities:</p>
<p><code>[test](/../../tree/test)</code> - link to another branch</p>
<p><code>[doc/readme.md](/../../edit/master/doc/readme.md)</code> - open in editor</p>
<p><code>[doc/readme.md](/../../delete/master/doc/readme.md)</code> - ask to delete file</p>
<p><code>[doc/readme.md](/../../commits/master/doc/readme.md)</code> - history</p>
<p><code>[doc/readme.md](/../../blame/master/doc/readme.md)</code> - blame mode</p>
<p><code>[doc/readme.md](/../../raw/master/doc/readme.md)</code> - raw mode (will redirect)</p>
<p><code>[doc/](/../../new/master/doc/)</code> - ask to create new file</p>
<p><code>[doc/](/../../upload/master/doc/)</code> - ask to upload file</p>
<p><code>[find](/../../find/test)</code> - find file</p> |
38,764,714 | Globally configure NPM with a token registry to a specific scope (@organisation) | <p>
I want to globally setup an NPM registry for a specific <a href="https://docs.npmjs.com/misc/scope" rel="noreferrer">scope</a> to be used with a specific <a href="http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules" rel="noreferrer">token</a>.</p>
<p>I know that I can use :</p>
<pre class="lang-none prettyprint-override"><code>$ npm login --scope=@organisation
</code></pre>
<p>And I can also write a <code>~/.npmrc</code> with :</p>
<pre class="lang-none prettyprint-override"><code>//registry.npmjs.org/:_authToken=XXXX
</code></pre>
<p>But what I want is a combinaison of the two methods: Using the token at when assigning the registry URL to my scope.</p>
<p>I tried :</p>
<pre class="lang-none prettyprint-override"><code>npm config set @organisation:registry https://registry.npmjs.org/:_authToken=XXXX
</code></pre>
<p>But when running an NPM command (eg <code>npm install @organisation/my-package</code>). I get the following error :</p>
<pre class="lang-none prettyprint-override"><code>npm ERR! Darwin 15.6.0
npm ERR! argv "/Users/me/.nvm/versions/node/v6.2.2/bin/node" "/Users/me/.nvm/versions/node/v6.2.2/bin/npm" "install" "@organisation/my-package"
npm ERR! node v6.2.2
npm ERR! npm v3.10.3
npm ERR! code E403
npm ERR! you do not have permission to publish ":_authToken=XXXX". Are you logged in as the correct user? : :_authToken=XXXX
</code></pre>
<p>Is there a solution? (I need to use a token and no env variable).</p>
<p>PS: <a href="https://github.com/npm/npm/issues/7995#issuecomment-175915766" rel="noreferrer">https://github.com/npm/npm/issues/7995#issuecomment-175915766</a> but it's not working...</p> | 42,114,654 | 1 | 0 | null | 2016-08-04 10:22:03.54 UTC | 14 | 2020-05-14 18:41:24.003 UTC | 2016-08-04 10:41:24.277 UTC | null | 1,480,391 | null | 1,480,391 | null | 1 | 27 | node.js|npm|npm-private-modules | 30,856 | <p>According to the official documentation you should be able to <a href="https://docs.npmjs.com/misc/scope#associating-a-scope-with-a-registry" rel="noreferrer">associate a scope with a registry when logging in</a>. Is this what you want?</p>
<p>Did you try the following?</p>
<pre><code>npm login --registry=https://reg.example.com --scope=@myco
</code></pre>
<p>If you dont want to login, but rather want to <strong>specify the token explicitly</strong>, the following should work:</p>
<pre><code>npm config set @myco:registry https://reg.example.com
npm config set //reg.example.com/:_authToken xxxxxxxx
</code></pre>
<p>Note that the registry url must be normalized for this to work, ie it shouldn't include scheme and must end with a slash.</p> |
27,736,175 | how to send/receive Objects using sockets in java | <p>When I execute my code in the CMD window, it doesn't work in Client mode, exactly at the line:</p>
<pre><code>ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
</code></pre>
<p>the program block on this line but don't stop or signal error :</p>
<p>I have 3 classes: <code>Client</code>, <code>Server</code>, <code>Message</code></p>
<h2>ClientClass:</h2>
<pre><code>package client;
// Organize imports
public class Client {
public static void main(String[] args) throws UnknownHostException,
IOException, ClassNotFoundException {
System.out.println("welcome client");
Socket socket = new Socket("localhost", 4444);
System.out.println("Client connected");
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Ok");
Message message = new Message(new Integer(15), new Integer(32));
os.writeObject(message);
System.out.println("Envoi des informations au serveur ...");
ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
Message returnMessage = (Message) is.readObject();
System.out.println("return Message is=" + returnMessage);
socket.close();
}
}
</code></pre>
<h2>Server</h2>
<p>Here is the code of the <code>Server</code> class</p>
<pre><code>package Sockets;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static final int port = 4444;
private ServerSocket ss = null;
public void runServer() throws IOException, ClassNotFoundException{
ss = new ServerSocket(port);
System.out.println("le systeme est pret pour accepter les connexions");
Socket socket = ss.accept();
ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
Message m = (Message) is.readObject();
doSomething(m);
os.writeObject(m);
socket.close();
}
private void doSomething(Message m) {
m.setResult(new Integer(m.getA().intValue()*m.getB().intValue()));
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
new Server().runServer();
}
}
</code></pre>
<h2>Message</h2>
<p>And here is my object , I made it <code>Serializable</code> by implementing the interface <code>Serializable</code></p>
<pre><code>import java.io.Serializable;
public class Message implements Serializable {
private static final long serialVersionUID = -5399605122490343339L;
private Integer A;
private Integer B;
private Integer Result;
public Message(Integer firstNumber, Integer secondNumber ){
this.A = firstNumber;
this.B = secondNumber;
}
public Integer getA() {
return A;
}
public Integer getB() {
return B;
}
public void setResult(Integer X) {
Result = X;
}
}
</code></pre> | 27,736,470 | 1 | 0 | null | 2015-01-02 00:51:09.203 UTC | 3 | 2018-03-12 05:59:19.117 UTC | 2015-01-02 01:07:54.073 UTC | null | 1,762,224 | null | 4,411,135 | null | 1 | 13 | java|sockets|serializable | 44,649 | <p>You need to create the <code>ObjectOutputStream</code> before the <code>ObjectInputStream</code>, at both ends, for reasons described in the Javadoc concerning the object stream header.</p> |
54,239,669 | ASP.NET Core 2.2: Unable to resolve service for type 'AutoMapper.IMapper' | <p><strong><em>ASP.NET Core (Version: 2.2.102)</em></strong></p>
<p>I am building an API to return Portos and Especies, but anytime that I access /api/portos (as defined in the controller), I get this error:</p>
<blockquote>
<p>InvalidOperationException: Unable to resolve service for type
'AutoMapper.IMapper' while attempting to activate
'fish.Controllers.PortosController'.</p>
<p>Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider
sp, Type type, Type requiredBy, bool isDefaultParameterRequired)</p>
</blockquote>
<p>I am not sure what am I doing wrong, so any help is appreciated.</p>
<hr>
<p><strong>Models</strong></p>
<hr>
<p><em>Especie.cs</em></p>
<pre><code>using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace fish.Models
{
[Table("Especies")]
public class Especie
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Nome { get; set; }
public Porto Porto { get; set; }
public int PortoId { get; set; }
}
}
</code></pre>
<p><em>Porto.cs</em></p>
<pre><code>using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
namespace fish.Models
{
public class Porto
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Nome { get; set; }
public ICollection<Especie> Models { get; set; }
public Porto()
{
Models = new Collection<Especie>();
}
}
}
</code></pre>
<hr>
<p><strong>Controller</strong></p>
<hr>
<p><em>PortoController.cs</em></p>
<pre><code>using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using fish.Controllers.Resources;
using fish.Models;
using fish.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace fish.Controllers
{
public class PortosController : Controller
{
private readonly FishDbContext context;
private readonly IMapper mapper;
public PortosController(FishDbContext context, IMapper mapper)
{
this.mapper = mapper;
this.context = context;
}
[HttpGet("/api/portos")]
public async Task<IEnumerable<PortoResource>> GetPortos()
{
var portos = await context.Portos.Include(m => m.Models).ToListAsync();
return mapper.Map<List<Porto>, List<PortoResource>>(portos);
}
}
}
</code></pre>
<p><strong>Controller>Resources</strong></p>
<p><em>PortoResources.cs</em></p>
<pre><code>using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace fish.Controllers.Resources
{
public class PortoResource
{
public int Id { get; set; }
public string Nome { get; set; }
public ICollection<EspecieResource> Models { get; set; }
public PortoResource()
{
Models = new Collection<EspecieResource>();
}
}
}
</code></pre>
<p><em>EspecieResource.cs</em></p>
<pre><code>namespace fish.Controllers.Resources
{
public class EspecieResource
{
public int Id { get; set; }
public string Nome { get; set; }
}
}
</code></pre>
<hr>
<p><strong>More Relevant Code</strong></p>
<hr>
<p><em>Stratup.cs</em></p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper();
services.AddDbContext<FishDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
</code></pre>
<p><em>MappingProfile.cs</em></p>
<pre><code>using AutoMapper;
using fish.Controllers.Resources;
using fish.Models;
namespace fish.Mapping
{
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Porto, PortoResource>();
CreateMap<Especie, EspecieResource>();
}
}
}
</code></pre>
<p><em>FishDbContext.cs</em></p>
<pre><code>using fish.Models;
using Microsoft.EntityFrameworkCore;
namespace fish.Persistence
{
public class FishDbContext : DbContext
{
public FishDbContext(DbContextOptions<FishDbContext> options) : base(options)
{
}
public DbSet<Porto> Portos { get; set; }
}
}
</code></pre> | 54,239,761 | 2 | 0 | null | 2019-01-17 15:56:49.1 UTC | 4 | 2021-07-06 07:33:46.073 UTC | null | null | null | null | 7,109,869 | null | 1 | 14 | c#|api|asp.net-core|.net-core|asp.net-core-mvc | 39,302 | <p>You will have to use automapper package as shown below:</p>
<pre><code>Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
</code></pre>
<p>This will also in turn install the Automapper nuget package if you don’t have it already.</p>
<p>Then, inside your ConfigureServices method of your startup.cs, you will have to add a call to it as shown below.</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper();
}
</code></pre>
<p>Refer <a href="https://dotnetcoretutorials.com/2017/09/23/using-automapper-asp-net-core/" rel="noreferrer">this blog for more details.</a></p>
<p><strong>EDIT:</strong></p>
<p>There is very nice description <a href="https://stackoverflow.com/questions/40275195/how-to-setup-automapper-in-asp-net-core">from this thread.</a></p>
<p>You need to add code like below in startup.cs.</p>
<p>You have missed to add IMapper in DI. Please refer add Singleton call from below code.</p>
<pre><code>public void ConfigureServices(IServiceCollection services) {
// .... Ignore code before this
// Auto Mapper Configurations
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddMvc();
}
</code></pre>
<p><strong>EDIT: 06-07-21:</strong>
Refer this blogpost which explains how to use <a href="https://thecodeblogger.com/2021/06/17/configure-automapper-for-asp-net-core-api-app/" rel="noreferrer">AutoMapper with latest .NET</a></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.