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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,531,867 | Auto select file in Solution Explorer from its open tab | <p>Normally, many files in <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2010" rel="noreferrer">Visual Studio 2010</a> are opened in many tabs, while massively working on a project. Many times, I find myself right-clicking on a tab title and searching for <code>Show/Select/Scroll-to this file in Solution Explorer</code>, and I can't find it.</p>
<p>Is there a way to automatically select an opened file in Solution Explorer?</p> | 8,473,574 | 13 | 1 | null | 2010-08-20 14:35:07.193 UTC | 56 | 2021-05-25 13:07:25.96 UTC | 2019-07-18 20:25:06.737 UTC | null | 3,345,644 | null | 225,680 | null | 1 | 284 | visual-studio|visual-studio-2010 | 131,584 | <p>Another option is to bind 'View.TrackActivityInSolutionExplorer' to a keyboard short-cut, which is the same as 'Tools-->Options-->Projects and Solutions-->Track Active Item in Solution Explorer'</p>
<p>If you activate the short-cut twice the file is selected in the solution explorer, and the tracking is disabled again.</p>
<p><strong>Visual Studio 2013+</strong></p>
<p>There is now a feature built in to the VS2013 solution explorer called Sync with Active Document. The icon is two arrows in the solution explorer, and has the hotkey <kbd>Ctrl</kbd> + <kbd>[</kbd>, <kbd>S</kbd> to show the current document in the solution explorer. Does not enable the automatic setting mentioned above, and only happens once.</p> |
8,213,657 | Is Twitter's Bootstrap mobile friendly like Skeleton? | <p>Skeleton is made to scale to also fit mobile browsers, following the principles of <a href="http://www.abookapart.com/products/responsive-web-design" rel="noreferrer">responsive web design</a>. Does Bootstrap offer the same?</p> | 8,213,727 | 4 | 1 | null | 2011-11-21 14:46:36.933 UTC | 9 | 2013-09-30 14:21:42.723 UTC | 2012-09-09 21:24:43.153 UTC | null | 1,092,711 | null | 567,589 | null | 1 | 34 | css|twitter-bootstrap|responsive-design|skeleton-css-boilerplate | 20,876 | <p>Not yet - <a href="http://groups.google.com/group/twitter-bootstrap/browse_thread/thread/6db57d09f654a326?pli=1" rel="nofollow">http://groups.google.com/group/twitter-bootstrap/browse_thread/thread/6db57d09f654a326?pli=1</a></p>
<p>But it will be, at some point. <a href="https://github.com/twitter/bootstrap/wiki/Roadmap" rel="nofollow">The Roadmap</a> has this in for version 2.0. It's lightweight enough that in my experience you can add in your own <code>media queries</code> without much trouble.</p>
<p><strong>EDIT</strong> - As of 1 Feb 2012, <a href="http://twitter.github.com/bootstrap/index.html" rel="nofollow">version 2.0</a> is out, which is responsive down to mobile out of the box.</p>
<p><strong>EDIT</strong> - As of 19 Aug 2013, <a href="http://blog.getbootstrap.com/2013/08/19/bootstrap-3-released/" rel="nofollow">version 3.0</a> is out, which is not only responsive but takes a mobile-first approach:</p>
<blockquote>
<blockquote>
<p>With Bootstrap 2, we added optional mobile friendly styles for key aspects of the framework. With Bootstrap 3, we've rewritten the project to be mobile friendly from the start. Instead of adding on optional mobile styles, they're baked right into the core. In fact, Bootstrap is mobile first. Mobile first styles can be found throughout the entire library instead of in separate files.</p>
</blockquote>
</blockquote> |
7,971,315 | How to force exit application in C#? | <p>I have a multi threaded C# application and it has reader writer lock,but it gives a timeout exception on some computers(not being able to acquire a lock in time) and I need to forcefully close all threads.
how do I do it without getting any extra exceptions?</p> | 7,971,353 | 5 | 2 | null | 2011-11-01 18:45:58.033 UTC | 6 | 2021-12-28 13:49:16.073 UTC | 2016-12-06 13:33:53.09 UTC | null | 1,905,073 | null | 871,082 | null | 1 | 26 | c#|multithreading | 43,440 | <p><a href="http://msdn.microsoft.com/en-us/library/ms131100.aspx" rel="noreferrer">Environment.FailFast</a> might be what you're looking for, but take care about the side-effects: no finalizers, finally blocks or anything else is run. It really does terminate the process <strong>NOW</strong>.</p> |
4,404,539 | WPF: Alternating colors on a ItemsControl? | <p>How do I get alternating colors on a ItemsControl? I have AlternationCount set to 2, but the ItemsControl.AlternationIndex property always returns 0.</p>
<pre><code> <ItemsControl ItemsSource="{Binding}" AlternationCount="2">
<ItemsControl.Resources>
<Style x:Key="FooBar" TargetType="Grid">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Blue"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.Resources>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,10" Style="{StaticResource FooBar}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="25" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions >
<RowDefinition Height="Auto" />
<!--<RowDefinition Height="Auto" />-->
</Grid.RowDefinitions>
<CheckBox IsChecked="{Binding Checked, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" />
<Label Grid.Column="1" Content="{Binding CompanyName}" />
<Label Grid.Column="2" Content="{Binding TradeKey}" />
<Label Grid.Column="3" Content="{Binding TradeDate}" ContentStringFormat="d" />
<Label Grid.Column="4" Content="{Binding Cusip}" />
<Label Grid.Column="5" Content="{Binding IssueName}" />
<Label Grid.Column="6" Content="{Binding TotalUnits}" ContentStringFormat="N0" />
<!--<Expander Grid.Row="0" Grid.Column="7" Grid.ColumnSpan="7" IsExpanded="True">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<Label Content="Allocations"/>
<Button Content="Edit" Name="cmdEdit" Click="cmdEdit_Click" />
</StackPanel>
</Expander.Header>-->
<DataGrid Grid.Column="7" IsReadOnly="True" ItemsSource="{Binding Territories}" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Rep on Ticket" Binding="{Binding TradeCustomer.RepNameNotes}" />
<DataGridTextColumn Header="Rep # on Ticket" Binding="{Binding TradeCustomer.RepNumberNotes}" />
<DataGridTextColumn Header="State" Binding="{Binding TradeCustomer.AccountStateKey}" />
<DataGridTextColumn Header="Qty. on Ticket" Binding="{Binding TradeCustomer.Quantity, StringFormat=N0}" />
<DataGridTextColumn Header="Zip Code" Binding="{Binding ZipCode}" />
<DataGridTextColumn Header="State" Binding="{Binding State}" />
<DataGridTextColumn Header="Territory" Binding="{Binding Territory}" />
</DataGrid.Columns>
</DataGrid>
<!--</Expander>-->
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Template>
<ControlTemplate>
<Border BorderThickness="{TemplateBinding Border.BorderThickness}" Padding="{TemplateBinding Control.Padding}" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" SnapsToDevicePixels="True">
<ScrollViewer Padding="{TemplateBinding Control.Padding}" Focusable="False">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
</ScrollViewer>
</Border>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
</code></pre> | 4,405,657 | 3 | 1 | null | 2010-12-10 00:23:55.22 UTC | 3 | 2016-01-07 15:21:45.143 UTC | 2011-08-16 15:56:16.357 UTC | null | 305,637 | null | 5,274 | null | 1 | 41 | wpf|styles|itemscontrol | 23,956 | <p>Check here <a href="http://www.codeproject.com/Articles/35886/WPF-ItemsControl-with-alternating-items-and-hover-.aspx" rel="noreferrer">http://www.codeproject.com/Articles/35886/WPF-ItemsControl-with-alternating-items-and-hover-.aspx</a></p>
<p>You have to change your code like this to get it working</p>
<pre><code> <ItemsControl ItemsSource="{Binding DataList}" AlternationCount="2">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="FooBar" Margin="0,0,0,10">
----------------------------
----------------------------
</Grid>
<DataTemplate.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Blue" TargetName="FooBar"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Red" TargetName="FooBar"/>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</code></pre> |
4,335,570 | Accessing Hibernate Session from EJB using EntityManager | <p>Is it possible to obtain the Hibernate Session object from the EntityManager? I want to access some hibernate specific API...</p>
<p>I already tried something like:</p>
<pre><code>org.hibernate.Session hSession =
( (EntityManagerImpl) em.getDelegate() ).getSession();
</code></pre>
<p>but as soon as I invoke a method in the EJB I get "A system exception occurred during an invocation on EJB" with a NullPointerException </p>
<p>I use glassfish 3.0.1</p> | 4,335,718 | 4 | 0 | null | 2010-12-02 13:35:35.837 UTC | 9 | 2012-02-29 19:05:39.35 UTC | 2011-01-22 09:36:25.907 UTC | null | 203,907 | null | 350,722 | null | 1 | 18 | java|hibernate|jpa|jakarta-ee|glassfish-3 | 21,135 | <p><a href="https://stackoverflow.com/questions/4335570/accessing-hibernate-session-from-ejb-using-entitymanager/4335608#4335608">Bozho</a> and <a href="https://stackoverflow.com/questions/4335570/accessing-hibernate-session-from-ejb-using-entitymanager/4335600#4335600">partenon</a> are correct, but:</p>
<p>In JPA 2, the preferred mechanism is <a href="http://download.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#unwrap%28java.lang.Class%29" rel="nofollow noreferrer">entityManager.unwrap(class)</a></p>
<pre><code>HibernateEntityManager hem = em.unwrap(HibernateEntityManager.class);
Session session = hem.getSession();
</code></pre>
<p>I think your exception is caused because you are trying to cast to an implementation class (perhaps you were dealing with a JDK proxy). Cast to an interface, and everything should be fine (in the JPA 2 version, no casting is needed).</p> |
4,827,544 | java.lang.OutOfMemoryError: PermGen space | <p>i'm getting the following error
"http-9000-5" java.lang.OutOfMemoryError: PermGen space</p>
<p>org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.OutOfMemoryError: PermGen space.</p>
<p>My application using axis2.I increased the heap size 1024mb.But its not working.What would be the problem.Solution please</p> | 18,443,635 | 5 | 1 | null | 2011-01-28 11:10:16.937 UTC | 5 | 2014-05-08 09:57:18.817 UTC | 2011-01-28 11:15:53.713 UTC | null | 260,990 | null | 538,678 | null | 1 | 12 | java|tomcat6|permgen | 57,099 | <p>If you're using Tomcat as a Server of Eclipse, go to Server view, then double click on Tomcat, then "Open Launch Configuration", go to Arguments tab, and after setting -Dcatalina.base="" put this</p>
<pre><code>-Xms256m -Xmx512m -XX:MaxPermSize=512m -XX:PermSize=128m
</code></pre> |
4,687,235 | jQuery $.get or $.post to catch page load error (eg. 404) | <p>How do you catch Server Error or 404 page not found, when you use $.get or $.post ?</p>
<p>For example:</p>
<pre><code>$.post("/myhandler", { value: 1 }, function(data) {
alert(data);
});
</code></pre>
<p>That will do absolutely nothing if there is a Server Error loading "/myhandler", or if it is not found.</p>
<p>How do you make it notify you if there is an error?</p> | 4,687,279 | 5 | 0 | null | 2011-01-14 01:39:21.877 UTC | 6 | 2015-10-27 05:32:30.533 UTC | null | null | null | null | 36,036 | null | 1 | 19 | jquery|post|get | 40,114 | <p>use <code>error</code> handler on <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer"><code>$.ajax()</code></a> </p>
<pre><code>$.ajax({
url: "/myhandler",
data: {value: 1},
type: 'post',
error: function(XMLHttpRequest, textStatus, errorThrown){
alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText);
},
success: function(data){}
});
</code></pre>
<h1><a href="http://jsfiddle.net/reigel/RafuW/" rel="noreferrer">demo</a></h1> |
4,278,601 | What of Eclipse project .metadata can I safely ignore in Git/Mercurial? | <p>We have the code for an Eclipse RCP application in an Eclipse workspace containing multiple Java projects. We are using Mercurial with a simple .hgignore just *.class (but the same issue would pertain to Git).</p>
<p>Even a small change to the code can result in many of the files in .metadata getting changed. </p>
<p>I'd like to exclude some or all of the .metadata from version control. If we exclude it completely, the workspace is lost.</p>
<p>Does anyone know what we can safely exclude? Alternatively, how can we recreate it if we pull the code down to a fresh computer?</p> | 4,278,711 | 5 | 2 | null | 2010-11-25 15:27:55.953 UTC | 21 | 2013-04-10 09:27:23.143 UTC | 2013-04-10 09:27:23.143 UTC | null | 651,104 | null | 459,675 | null | 1 | 42 | java|eclipse|git|mercurial|rcp | 48,203 | <p>The files i'm personally aware of are:</p>
<ul>
<li>version.ini (not very exciting)</li>
<li>.plugins/org.eclipse.jdt.core/variablesAndContainers.dat (classpath variables)</li>
<li>.plugins/org.eclipse.core.resources/.projects/*/.location (projects in the workspace)</li>
</ul>
<p>Somewhere, i have an Eclipse workspace used for testing some Eclipse-related tools that is pretty severely cut down, but works. I'll see if i can dig it out.</p> |
4,201,239 | In HTML5, is the localStorage object isolated per page/domain? | <p>Is the HTML5 localStorage object isolated per page/domain? I am wondering because of how I would name localStorage keys. Do I need a separate prefix? Or can I name them whatever I want?</p> | 4,201,249 | 5 | 2 | null | 2010-11-17 03:33:57.003 UTC | 29 | 2019-10-23 11:07:37.42 UTC | null | null | null | null | 423,325 | null | 1 | 214 | javascript|html|local-storage | 91,045 | <p>It's per domain and port (the same segregation rules as the <a href="http://en.wikipedia.org/wiki/Same-origin_policy#Origin_determination_rules" rel="noreferrer">same origin policy</a>), to make it per-page you'd have to use a key based on the <code>location</code>, or some other approach. </p>
<p>You don't <em>need</em> a prefix, use one if you need it though. Also, yes, you can name them whatever you want.</p> |
4,471,041 | How to retrieve records for last 30 minutes in MS SQL? | <p>I want to retrieve records for last 30 minutes in a table. How to do that? Below is my query..</p>
<pre><code>select * from
[Janus999DB].[dbo].[tblCustomerPlay]
where DatePlayed < CURRENT_TIMESTAMP
and DatePlayed >
(CURRENT_TIMESTAMP-30)
</code></pre> | 4,471,066 | 6 | 0 | null | 2010-12-17 13:50:14.583 UTC | 6 | 2021-12-01 18:22:59.07 UTC | 2010-12-17 13:54:52.887 UTC | null | 397,952 | null | 144,250 | null | 1 | 57 | sql|sql-server|tsql | 150,064 | <p>Change this <code>(CURRENT_TIMESTAMP-30)</code></p>
<p>To This: <code>DateADD(mi, -30, Current_TimeStamp)</code></p>
<p>To get the current date use GetDate().</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms186819.aspx" rel="noreferrer">MSDN Link to DateAdd Function</a><br>
<a href="http://msdn.microsoft.com/en-us/library/ms188383.aspx" rel="noreferrer">MSDN Link to Get Date Function</a></p> |
4,840,102 | Why don't my south migrations work? | <p>First, I create my database.</p>
<pre><code>create database mydb;
</code></pre>
<p>I add "south" to installed Apps. Then, I go to this tutorial: <a href="http://south.aeracode.org/docs/tutorial/part1.html" rel="noreferrer">http://south.aeracode.org/docs/tutorial/part1.html</a></p>
<p>The tutorial tells me to do this:</p>
<pre><code>$ py manage.py schemamigration wall --initial
>>> Created 0001_initial.py. You can now apply this migration with: ./manage.py migrate wall
</code></pre>
<p>Great, now I migrate.</p>
<pre><code>$ py manage.py migrate wall
</code></pre>
<p>But it gives me this error...</p>
<pre><code>django.db.utils.DatabaseError: (1146, "Table 'fable.south_migrationhistory' doesn't exist")
</code></pre>
<p>So I use Google (which never works. hence my 870 questions asked on Stackoverflow), and I get this page: <a href="http://groups.google.com/group/south-users/browse_thread/thread/d4c83f821dd2ca1c" rel="noreferrer">http://groups.google.com/group/south-users/browse_thread/thread/d4c83f821dd2ca1c</a></p>
<p>Alright, so I follow that instructions</p>
<pre><code>>> Drop database mydb;
>> Create database mydb;
$ rm -rf ./wall/migrations
$ py manage.py syncdb
</code></pre>
<p>But when I run syncdb, Django creates a bunch of tables. Yes, it creates the south_migrationhistory table, but <strong>it also creates my app's tables.</strong></p>
<pre><code>Synced:
> django.contrib.admin
> django.contrib.auth
> django.contrib.contenttypes
> django.contrib.sessions
> django.contrib.sites
> django.contrib.messages
> south
> fable.notification
> pagination
> timezones
> fable.wall
> mediasync
> staticfiles
> debug_toolbar
Not synced (use migrations):
-
(use ./manage.py migrate to migrate these)
</code></pre>
<p>Cool....now it tells me to migrate these. So, I do this:</p>
<pre><code>$ py manage.py migrate wall
The app 'wall' does not appear to use migrations.
</code></pre>
<p>Alright, so fine. I'll add wall to initial migrations.</p>
<pre><code>$ py manage.py schemamigration wall --initial
</code></pre>
<p>Then I migrate:</p>
<pre><code>$ py manage.py migrate wall
</code></pre>
<p>You know what? It gives me this BS:</p>
<pre><code>_mysql_exceptions.OperationalError: (1050, "Table 'wall_content' already exists")
</code></pre>
<p>Sorry, this is really pissing me off. Can someone help ? thanks.</p>
<p>How do I get South to work and sync correctly with everything? The only thing I can think of is remove my app from INSTALLED_APPS, then run syncdb, then add it back on.</p>
<p><strong>That is SO SILLY.</strong></p> | 4,840,262 | 6 | 3 | null | 2011-01-29 23:23:13.147 UTC | 97 | 2013-10-25 13:50:23.087 UTC | 2013-07-28 23:00:05.643 UTC | null | 1,451,443 | null | 179,736 | null | 1 | 78 | python|django|migration|django-south | 48,648 | <p>South allows you to create migrations when you first start out with a new app and the tables haven't been added to the database yet, as well as creating migrations for legacy apps that already have tables in the database. The key is to know when to do what. </p>
<p>Your first mistake was when you deleted your migrations, as soon as you did that, and then ran syncdb, Django didn't know that you wanted south to manage that app anymore, so it created the tables for you. When you created your initial migrations and then ran migrate, south was trying to create tables that django already created, and thus your error.</p>
<p>At this point you have two options.</p>
<ol>
<li><p>Delete the tables for the wall app from your database and then run <code>$ py manage.py migrate wall</code> This will run the migration and create your tables.</p></li>
<li><p>Fake out the initial migration run
<code>$ py manage.py migrate wall 0001 --fake</code> This will tell south that you already have the tables on the database so just fake it, which will add a row to the south_migrationhistory table, so that the next time you run a migrate it will know that the first migration has already been run.</p></li>
</ol>
<h2>Setting up a brand new project and no database</h2>
<ol>
<li>create your database</li>
<li>add south to installed apps</li>
<li>run syncdb, this will add the django and south tables to the database</li>
<li>add your apps</li>
<li>for each app run <code>python manage.py schemamigration app_name --initial</code> this will create the initial migration files for your app</li>
<li>then run south migrate <code>python manage.py migrate app_name</code> this will add the tables to the database.</li>
</ol>
<h2>Setting up a legacy project and database</h2>
<ol>
<li>add south to installed apps</li>
<li>run syncdb, this will add the south tables to the database</li>
<li>for each of your apps run <code>python manage.py schemamigration app_name --initial</code> This will create your initial migrations</li>
<li>for each of your apps run <code>python manage.py migrate app_name 0001 --fake</code> , this will fake out south, it won't do anything to the database for those models, it will just add records to the south_migrationhistory table so that the next time you want to create a migration, you are all set. </li>
</ol>
<h2>Setting up a legacy project and no database</h2>
<ol>
<li>create database</li>
<li>add south to installed apps</li>
<li>for each of your apps run <code>python manage.py schemamigration app_name --initial</code> This will create your initial migrations</li>
<li>run syncdb, this will add any apps that don't have migrations to the database.</li>
<li>then run south migrate <code>python manage.py migrate</code> this will run all migrations for your apps.</li>
</ol>
<p>Now that you are setup with south, you can start using south to manage model changes to those apps. The most common command to run is <code>python manage.py schemamigration app_name migration_name --auto</code> that will look at the last migration you ran and it will find the changes and build out a migration file for you. Then you just need to run <code>python manage.py migrate</code> and it alter your database for you.</p>
<p>Hope that helps.</p> |
14,859,058 | Why does the Segment.io loader script push method names/args onto a queue which seemingly gets overwritten? | <p>I've been dissecting the following code snippet, which is used to asynchronously load the <a href="https://segment.io" rel="noreferrer">Segment.io</a> analytics wrapper script:</p>
<pre><code>// Create a queue, but don't obliterate an existing one!
var analytics = analytics || [];
// Define a method that will asynchronously load analytics.js from our CDN.
analytics.load = function(apiKey) {
// Create an async script element for analytics.js.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = ('https:' === document.location.protocol ? 'https://' : 'http://') +
'd2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/' + apiKey + '/analytics.min.js';
// Find the first script element on the page and insert our script next to it.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
// Define a factory that generates wrapper methods to push arrays of
// arguments onto our `analytics` queue, where the first element of the arrays
// is always the name of the analytics.js method itself (eg. `track`).
var methodFactory = function (type) {
return function () {
analytics.push([type].concat(Array.prototype.slice.call(arguments, 0)));
};
};
// Loop through analytics.js' methods and generate a wrapper method for each.
var methods = ['identify', 'track', 'trackLink', 'trackForm', 'trackClick',
'trackSubmit', 'pageview', 'ab', 'alias', 'ready'];
for (var i = 0; i < methods.length; i++) {
analytics[methods[i]] = methodFactory(methods[i]);
}
};
// Load analytics.js with your API key, which will automatically load all of the
// analytics integrations you've turned on for your account. Boosh!
analytics.load('MYAPIKEY');
</code></pre>
<p>It's well commented and I can see what it's doing, but I'm puzzled when it comes to the <code>methodFactory</code> function, which pushes details (method name and arguments) of any method calls made before the main <code>analytics.js</code> script has loaded onto the global <code>analytics</code> array.</p>
<p>This is all well and good, but then if/when the main script <em>does</em> load, it seemingly just overwrites the global <code>analytics</code> variable (see <a href="https://github.com/segmentio/analytics.js/blob/master/src/analytics.js" rel="noreferrer">last line here</a>), so all that data will be lost.</p>
<p>I see how this prevents script errors in a web page by stubbing out methods which don't exist yet, but I don't understand why the stubs can't just return an empty function:</p>
<pre><code>var methods = ['identify', 'track', 'trackLink', 'trackForm', 'trackClick',
'trackSubmit', 'pageview', 'ab', 'alias', 'ready'];
for (var i = 0; i < methods.length; i++) {
lib[methods[i]] = function () { };
}
</code></pre>
<p>What am I missing? Please, help me understand!</p> | 14,965,470 | 1 | 0 | null | 2013-02-13 17:11:52.767 UTC | 8 | 2015-05-26 14:44:46.847 UTC | 2015-05-26 14:44:46.847 UTC | null | 884,123 | null | 43,140 | null | 1 | 10 | javascript|asynchronous|segment-io | 4,356 | <p>Ian here, co-founder at Segment.io—I didn't actually write that code, Calvin did, but I can fill you in on what it's doing.</p>
<p>You're right, the <code>methodFactory</code> is stubbing out the methods so that they are available before the script loads, which means people can call <code>analytics.track</code> without wrapping those calls in an <code>if</code> or <code>ready()</code> call.</p>
<p>But the methods are actually better than "dumb" stubs, in that they save the method that was called, so we can replay the actions later. That's this part:</p>
<pre><code>analytics.push([type].concat(Array.prototype.slice.call(arguments, 0)));
</code></pre>
<p>To make that more readable:</p>
<pre><code>var methodFactory = function (method) {
return function () {
var args = Array.prototype.slice.call(arguments, 0);
var newArgs = [method].concat(args);
analytics.push(newArgs);
};
};
</code></pre>
<p>It tacks on the name of the method that was called, which means if I <code>analytics.identify('userId')</code>, our queue actually gets an array that looks like:</p>
<pre><code>['identify', 'userId']
</code></pre>
<p>Then, when our library loads in, it unloads all of the queued calls and replays them into the real methods (that are now available) so that all of the data recorded before load is still preserved. That's the key part, because we don't want to just throw away any calls that happen before our library has the chance to load. That looks like this:</p>
<pre><code>// Loop through the interim analytics queue and reapply the calls to their
// proper analytics.js method.
while (window.analytics.length > 0) {
var item = window.analytics.shift();
var method = item.shift();
if (analytics[method]) analytics[method].apply(analytics, item);
}
</code></pre>
<p><code>analytics</code> is a local variable at that point, and after we're done replaying, we replace the global with the local <code>analytics</code> (which is the real deal).</p>
<p>Hope that makes sense. We're actually going to have a series on our blog about all the little tricks for 3rd-party Javascript, so you might dig that soon!</p> |
14,920,806 | Is it possible to onclick="history.clear();" | <p>I'm going to implement <strong>logout</strong> button in my PhoneGap application, which will return the user into authentication page (with cleared fields). For the button I'm using anchor with onclick event:</p>
<pre><code><script type="text/javascript">
function doLogout() {
var backlen = history.length;
history.go(-backlen);
window.location.replace("index.html");
}
</script>
<a data-role="none" href="#" onclick="doLogout"></a>
</code></pre>
<p>but it's not works, i.e. it's just returns me to that authentication page with already filled fileds, seems like just a one step back. I'm not sure for <strong>history.clear()</strong>, because googling it gave me nothing:</p>
<pre><code><a data-role="none" href="index.html" onclick="javascript:history.clear();"></a>
</code></pre>
<p>Could anyone advise me where is my problem? If there is another solution to handle logout event in PhoneGap I would follow it. THanks</p> | 14,921,004 | 4 | 0 | null | 2013-02-17 11:55:36.453 UTC | 3 | 2018-10-22 15:49:19.783 UTC | 2013-02-17 12:41:08.553 UTC | null | 239,567 | null | 1,130,672 | null | 1 | 12 | javascript|cordova|logout | 67,360 | <p>The call to <code>history.go</code> will be ignored, because you are going back one more step than there are items in the history. The <code>length</code> property has the number of items including the current one, so if there are for example four items in the history, you can only go back three steps.</p>
<p>To go back to the first step, you would subtract one from the length:</p>
<pre><code>history.go(-(history.length - 1));
</code></pre>
<p>However, that would only take you back to your start page if you opened a new window specifically for that page. Otherwise it would take the user back to the first page that he visited using that window.</p>
<hr>
<p>There is no <code>clear</code> method for the <code>history</code> object.</p>
<p>Ref: <a href="https://developer.mozilla.org/en-US/docs/DOM/window.history" rel="noreferrer">https://developer.mozilla.org/en-US/docs/DOM/window.history</a></p>
<p>The browser history belongs to the user, you can't remove anything from it.</p> |
14,711,796 | Publish local Git repository to Team Foundation Service | <p>About a week ago Git support was added to Visual Studio 2012 and Team Foundation Service. I've been playing around with it a bit and wanted to publish a local repository to my team project. It's described in step 2 on the Team Foundation Service <a href="http://tfs.visualstudio.com/en-us/learn/code/publish-new-team-project-vs-git/" rel="noreferrer">website</a>:</p>
<ul>
<li>Publish your local Git repository into your new team project.</li>
</ul>
<p><img src="https://i.stack.imgur.com/YjyHl.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/DDfh5.png" alt="enter image description here"></p>
<p>Now I've been doing the exact same thing, but I don't get the "Publish to ..." context item. Could this be a bug or am I missing something?</p>
<p><img src="https://i.stack.imgur.com/9VGiB.png" alt="enter image description here"></p> | 14,740,846 | 12 | 3 | null | 2013-02-05 16:08:00.527 UTC | 10 | 2017-02-11 04:14:36.29 UTC | 2013-02-05 21:27:01.733 UTC | null | 522,735 | null | 95,503 | null | 1 | 20 | visual-studio|git|tfs|azure-devops | 18,093 | <p>I was having the same problem. I don't know why.</p>
<p>However, after a bit of playing around, I managed to get the following
working. Disclaimer: can't guarantee this is actually the correct way
to do it. It may bork things further. And whether it does the same as what the missing 'Publish' menu item is supposed to do, I have no idea. Use at your discretion...</p>
<ul>
<li>Get the url of your git repo in the project you set up in TFS.
<ul>
<li>Go to your project in the TFS web interface, then Code tab.</li>
<li>You should get a message that gives you the URL.</li>
<li>e.g. <a href="https://user.visualstudio.com/DefaultCollection/_git/YourProject"><a href="https://user.visualstudio.com/DefaultCollection/_git/YourProject">https://user.visualstudio.com/DefaultCollection/_git/YourProject</a></a></li>
</ul></li>
<li>Edit the .git/config file on your local repo.
<ul>
<li>Configure the origin remote to point to your TFS repo.</li>
<li>(note: if you already had an origin remote, you might want to rename that first to keep it)</li>
</ul></li>
</ul>
<p>e.g.</p>
<pre><code>[remote "origin"]
url = https://user.visualstudio.com/DefaultCollection/_git/YourRepo
fetch = +refs/heads/*:refs/remotes/origin/*
</code></pre>
<ul>
<li>Open your solution in Visual Studio.</li>
<li>Edit a file.</li>
<li>Do a commit.</li>
<li>Do a push.</li>
</ul>
<p>This should hopefully push your local repo to your TFS remote as origin.</p>
<p>From here things seem to be working for me -- the code is up in my TFS
web interface at least, and I can push commits to it. I can add backlog items etc. I'm new to TFS though so not sure if it's actually all working as it should be.</p> |
14,848,924 | How to define typedef of function pointer which has template arguments | <p>I would like to make typedef for function pointer which has stl container as argument and this container has unknown type. Something like this:</p>
<pre><code>typedef void (* TouchCallBack)(GLRenderer*, const MotionEvent&, std::vector<T >);
</code></pre>
<p>it's possible? (especially in c++ 03) </p> | 14,848,966 | 1 | 3 | null | 2013-02-13 08:01:33.847 UTC | 12 | 2013-02-13 08:03:58.16 UTC | null | null | null | null | 284,720 | null | 1 | 22 | c++|templates|function-pointers|typedef | 16,624 | <p>I don't know of any C++03 solution exactly like that, and it's not built into the language, but in C++11, this is possible with <code>using</code> aliases:</p>
<pre><code>template<typename T>
using TouchCallBack = void (*)(GLRenderer*, const MotionEvent&, std::vector<T >);
</code></pre>
<p>One workaround for C++03 is using a struct:</p>
<pre><code>template<typename T>
struct TouchCallBack {
typedef void (*type)(GLRenderer*, const MotionEvent&, std::vector<T >);
};
//use like TouchCallBack<int>::type
</code></pre> |
14,483,473 | Is there any JavaScript libraries for graph operations and algorithms? | <p>What I need is a JavaScript implementation of <a href="http://en.wikipedia.org/wiki/Graph_%28mathematics%29">pure mathematical graphs</a>. To be clear I DON'T mean graph visualization libraries like <a href="http://sigmajs.org/">sigma.js</a> or <a href="http://bl.ocks.org/4062045">d3.js</a>.</p>
<p>The library I'm looking for would implement following features:</p>
<ul>
<li>creation of directed and undirected graph objects</li>
<li>creation of weighted and unweighted graps objects</li>
<li>adding/removing vertices and edges to/from the graph</li>
<li>adding labels to vertices and edges (i.e. additional meta data)</li>
<li>implementation of basic graph search and traversal algorithms like <a href="http://en.wikipedia.org/wiki/Depth-first_search">depth-first-search</a>, <a href="http://en.wikipedia.org/wiki/Breadth-first_search">breadth-first search</a>, <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra's algorithm</a>, <a href="http://en.wikipedia.org/wiki/A%2a_search_algorithm">A*</a> and <a href="http://en.wikipedia.org/wiki/Graph_traversal">others</a>.</li>
</ul>
<p>Does anyone know if one already exists?</p> | 34,881,445 | 7 | 1 | null | 2013-01-23 15:41:58.713 UTC | 8 | 2022-02-17 16:38:24.063 UTC | null | null | null | null | 638,546 | null | 1 | 30 | javascript|math|graph|graph-algorithm | 13,269 | <p>Now there is a library: <a href="https://github.com/cpettitt/graphlib" rel="noreferrer">graphlib</a></p>
<blockquote>
<p>Graphlib is a JavaScript library that provides data structures for undirected and directed multi-graphs along with algorithms that can be used with them.</p>
</blockquote>
<p>Implements:</p>
<ul>
<li>directed and undirected graphs (does A -> B imply B -> A)</li>
<li>multigraphs (multiple distinct named edges from A -> B)</li>
<li>compound graphs (nodes can have children that form a "subgraph")</li>
<li>Dijkstra algorithm (shortest path)</li>
<li>Floyd-Warshall algorithm (shortest path supporting negative weights)</li>
<li>Prim's algorithm (minimum spanning tree)</li>
<li>Tarjan's algorithm (strongly connected components)</li>
<li>Topological sorting (dependency sort for directed acyclic graphs)</li>
<li>Pre- and postorder traversal (callback on every node)</li>
<li>Finding all cycles and testing if a graph is acyclic</li>
<li>Finding all connected components</li>
</ul>
<p>NPM, Bower and browser supported, MIT license.</p> |
14,473,321 | Generating random, unique values C# | <p>I've searched for a while and been struggling to find this, I'm trying to generate several random, unique numbers is C#. I'm using <code>System.Random</code>, and I'm using a <code>DateTime.Now.Ticks</code> seed:</p>
<pre><code>public Random a = new Random(DateTime.Now.Ticks.GetHashCode());
private void NewNumber()
{
MyNumber = a.Next(0, 10);
}
</code></pre>
<p>I'm calling <code>NewNumber()</code> regularly, but the problem is I often get repeated numbers. Some people suggested because I was declaring the random every time I did it, it would not produce a random number, so I put the declaration outside my function. Any suggestions or better ways than using <code>System.Random</code> ? Thank you</p> | 14,473,371 | 17 | 5 | null | 2013-01-23 05:54:42.09 UTC | 11 | 2021-12-07 22:21:20.647 UTC | 2019-02-21 14:15:54.01 UTC | null | 3,917,754 | null | 2,002,690 | null | 1 | 38 | c#|.net|random|unique | 123,310 | <blockquote>
<p>I'm calling NewNumber() regularly, but the problem is I often get
repeated numbers.</p>
</blockquote>
<p><code>Random.Next</code> doesn't guarantee the number to be unique. Also your range is from 0 to 10 and chances are you will get duplicate values. May be you can setup a list of <code>int</code> and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like:</p>
<pre><code>public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode());
// Since similar code is done in default constructor internally
public List<int> randomList = new List<int>();
int MyNumber = 0;
private void NewNumber()
{
MyNumber = a.Next(0, 10);
if (!randomList.Contains(MyNumber))
randomList.Add(MyNumber);
}
</code></pre> |
14,865,965 | jQuery find() method not working in AngularJS directive | <p>I am having trouble with angularjs directives finding child DOM elements with the injected angular element.</p>
<p>For example I have a directive like so:</p>
<pre class="lang-js prettyprint-override"><code>myApp.directive('test', function () {
return {
restrict: "A",
link: function (scope, elm, attr) {
var look = elm.find('#findme');
elm.addClass("addedClass");
console.log(look);
}
};
});
</code></pre>
<p>and HTML such as :</p>
<pre class="lang-html prettyprint-override"><code><div ng-app="myApp">
<div test>TEST Div
<div id="findme"></div>
</div>
</div>
</code></pre>
<p>I have access to the element which is proffed by adding a class to it.
However attempting to access a child element produces an empty array in the var look.</p>
<p><a href="http://jsfiddle.net/raygarner/FZGKA/7/">JSFiddle demo is here</a>.</p>
<p>Why is something so trivial not working properly?</p> | 14,866,067 | 7 | 0 | null | 2013-02-14 00:43:45.247 UTC | 10 | 2016-02-03 19:17:01.963 UTC | 2016-02-03 19:17:01.963 UTC | null | 1,264,804 | null | 764,797 | null | 1 | 45 | javascript|angularjs|angularjs-directive | 132,100 | <p>From the <a href="http://docs.angularjs.org/api/angular.element">docs on <code>angular.element</code></a>:</p>
<blockquote>
<p><code>find()</code> - Limited to lookups by tag name</p>
</blockquote>
<p>So if you're not using jQuery with Angular, but relying upon its jqlite implementation, you can't do <code>elm.find('#someid')</code>.</p>
<p>You do have access to <code>children()</code>, <code>contents()</code>, and <code>data()</code> implementations, so you can usually find a way around it.</p> |
14,910,667 | How to use if statements in LESS | <p>I'm looking for some kind of if-statement to control the <code>background-color</code> of different <code>div</code> elements.</p>
<p>I have tried the below, but it doesn't compile</p>
<pre><code>@debug: true;
header {
background-color: (yellow) when (@debug = true);
#title {
background-color: (orange) when (@debug = true);
}
}
article {
background-color: (red) when (@debug = true);
}
</code></pre> | 14,916,419 | 4 | 1 | null | 2013-02-16 13:10:33.367 UTC | 22 | 2021-01-28 10:40:49.373 UTC | 2021-01-28 10:40:49.373 UTC | null | 10,698,741 | null | 433,685 | null | 1 | 68 | less | 111,290 | <p>LESS has <a href="http://lesscss.org/features/#css-guards-feature">guard expressions</a> for mixins, not individual attributes.</p>
<p>So you'd create a mixin like this:</p>
<pre><code>.debug(@debug) when (@debug = true) {
header {
background-color: yellow;
#title {
background-color: orange;
}
}
article {
background-color: red;
}
}
</code></pre>
<p>And turn it on or off by calling <code>.debug(true);</code> or <code>.debug(false)</code> (or not calling it at all).</p> |
14,404,704 | How do I replace a git submodule with another repo? | <p>How do I replace a git submodule with a different git repo?</p>
<p>Specifically, I have a submodule:</p>
<ul>
<li>located at <code>./ExternalFrameworks/TestFramework</code> that points to a git repo <code>[email protected]:userA/TestFramework.git</code> </li>
<li>I'd like it to now point to <code>[email protected]:userB/TestFramework.git</code>.</li>
</ul>
<p>The problem is that when I delete the submodule with the method described <a href="https://stackoverflow.com/questions/1260748/how-do-i-remove-a-git-submodule">here</a>, then re-add it using the command </p>
<pre><code>git submodule add [email protected]:userB/TestFramework.git
</code></pre>
<p>I get this error:</p>
<pre><code>A git directory for 'ExternalFrameworks/TestFramework' is found locally with remote(s):
origin [email protected]:userA/TestFramework.git
If you want to reuse this local git directory instead of cloning again from
[email protected]:userB/TestFramework.git
use the '--force' option. If the local git directory is not the correct repo
or you are unsure what this means choose another name with the '--name' option.
</code></pre> | 14,405,542 | 6 | 1 | null | 2013-01-18 17:52:39.323 UTC | 37 | 2022-06-13 04:15:59.263 UTC | 2017-05-23 12:02:13.08 UTC | null | -1 | null | 1,192,740 | null | 1 | 110 | git|git-submodules | 48,067 | <p>If the location (URL) of the submodule has changed, then you can simply:</p>
<ol>
<li>Modify the <code>.gitmodules</code> file in the repo root to use the new URL.</li>
<li>Delete the submodule folder in the repo <code>rm -rf .git/modules/<submodule></code>.</li>
<li>Delete the submodule folder in the working directory <code>rm -rf <submodule></code>.</li>
<li>Run <code>git submodule sync</code>.</li>
<li>Run <code>git submodule update</code>.</li>
</ol>
<p>More complete info can be found elsewhere:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/913701/changing-remote-repository-for-a-git-submodule">Changing remote repository for a git submodule</a></li>
</ul> |
14,869,311 | Start/Stop and Restart Jenkins service on Windows | <p>I have downloaded "jenkins-1.501.zip" from <a href="http://jenkins-ci.org/content/thank-you-downloading-windows-installer">http://jenkins-ci.org/content/thank-you-downloading-windows-installer</a> . </p>
<p>I have extracted zip file and installed Jenkins on Windows 7 successfully. Jenkins runs at <code>http://localhost:8080/</code> well. I want to stop Jenkins service from console. How can I do that? What's the way to start and restart through console/command line?</p> | 14,869,398 | 9 | 0 | null | 2013-02-14 06:51:39.05 UTC | 37 | 2022-07-11 15:53:07.35 UTC | 2013-03-07 09:05:18.307 UTC | null | 617,450 | user2027659 | null | null | 1 | 118 | windows|command-line|console|jenkins|command-prompt | 411,198 | <p>Open Console/Command line --> Go to your Jenkins installation directory. Execute the following commands respectively:</p>
<p><strong>to stop:</strong><br>
<code>jenkins.exe stop</code></p>
<p><strong>to start:</strong><br>
<code>jenkins.exe start</code></p>
<p><strong>to restart:</strong><br>
<code>jenkins.exe restart</code></p> |
2,930,315 | changing iframe source with jquery | <p>I've been trying this for a bit now and have looked at other answers to similar questions on SO, but when I am trying to change the src attribute of an iframe, it updates it for the whole window. Here is the following code I am using that works correctly (no jquery):</p>
<pre><code><html>
<head>
<style type="text/css">
iframe#ifrm {
border:none;
padding:.5em;
margin:1.5em 0 1em;
width:100%;
height:100%;
}
</style>
<script src="./js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
// <![CDATA[
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// this is the function I'm trying to replace:
function loadIframe(iframeName, url) {
if ( window.frames[iframeName] ) {
window.frames[iframeName].location = url;
return false;
}
return true;
}
// ]]>
</script>
</head>
<body>
<ul>
<li><a href="http://www.google.com/" onclick="return loadIframe('ifrm', this.href)">Page 1</a> </li>
<li><a href="tabs.html" onclick="return loadIframe('ifrm', this.href)">Page 2</a></li>
</ul>
<div class="iframe">
<iframe name="ifrm" id="ifrm" src="tabs.html" frameborder="0">
Your browser doesn't support iframes.</iframe>
</code></pre>
<p>
</p>
<p>As I said, I've tried </p>
<pre><code>$('#ifrm').attr('src', "http://www.google.com")
</code></pre>
<p>which displays the page, but not in the iframe. I'm really just learning jquery, but I can't figure out what's different about my situation than other similar questions like this:</p>
<p><a href="https://stackoverflow.com/questions/1477291/jquery-and-iframe-update">Jquery and iFrame update</a></p>
<p>Thanks.</p> | 2,930,516 | 2 | 1 | null | 2010-05-28 15:34:19.963 UTC | 17 | 2021-02-08 23:26:33.49 UTC | 2017-05-23 12:10:35.467 UTC | null | -1 | null | 147,373 | null | 1 | 60 | jquery | 238,994 | <p>Should work.</p>
<p>Here's a working example:</p>
<p><a href="http://jsfiddle.net/rhpNc/" rel="noreferrer">http://jsfiddle.net/rhpNc/</a></p>
<p>Excerpt:</p>
<pre class="lang-js prettyprint-override"><code>function loadIframe(iframeName, url) {
var $iframe = $('#' + iframeName);
if ($iframe.length) {
$iframe.attr('src',url);
return false;
}
return true;
}
</code></pre> |
3,160,347 | Java: How initialize an array in Java in one line? | <pre><code>int[] array1 = {1, 2, 3, 4, 5, 6, ,7, 8}; - working
array1 = {1, 1, 1, 1, 2, 5, ,7, 8}; - NOT working
</code></pre>
<p>The first line is working, but second line is not working.</p>
<p>How can I make the initialization from the second line in one single line of code? </p> | 3,160,356 | 2 | 0 | null | 2010-07-01 17:50:39.09 UTC | 6 | 2017-01-11 13:25:47.637 UTC | null | null | null | null | 381,361 | null | 1 | 69 | java|arrays | 91,042 | <pre><code>array = new int[] {1, 1, 2, 3, 5, 8};
</code></pre>
<p>Source: <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html" rel="noreferrer">Oracle JavaDocs - Arrays</a></p> |
41,052,598 | ReactJS Array.push function not working in setState | <p>I'm making a primitive quiz app with 3 questions so far, all true or false. In my <code>handleContinue</code> method there is a call to push the users input from a radio form into the <code>userAnswers</code> array. It works fine for the first run of <code>handleContinue</code>, after that it throws an error: <code>Uncaught TypeError: this.state.userAnswers.push is not a function(…)</code></p>
<pre><code>import React from "react"
export default class Questions extends React.Component {
constructor(props) {
super(props)
this.state = {
questionNumber: 1,
userAnswers: [],
value: ''
}
this.handleContinue = this.handleContinue.bind(this)
this.handleChange = this.handleChange.bind(this)
}
//when Continue button is clicked
handleContinue() {
this.setState({
//this push function throws error on 2nd go round
userAnswers: this.state.userAnswers.push(this.state.value),
questionNumber: this.state.questionNumber + 1
//callback function for synchronicity
}, () => {
if (this.state.questionNumber > 3) {
this.props.changeHeader(this.state.userAnswers.toString())
this.props.unMount()
} else {
this.props.changeHeader("Question " + this.state.questionNumber)
}
})
console.log(this.state.userAnswers)
}
handleChange(event) {
this.setState({
value: event.target.value
})
}
render() {
const questions = [
"Blargh?",
"blah blah blah?",
"how many dogs?"
]
return (
<div class="container-fluid text-center">
<h1>{questions[this.state.questionNumber - 1]}</h1>
<div class="radio">
<label class="radio-inline">
<input type="radio" class="form-control" name="trueFalse" value="true"
onChange={this.handleChange}/>True
</label><br/><br/>
<label class="radio-inline">
<input type="radio" class="form-control" name="trueFalse" value="false"
onChange={this.handleChange}/>False
</label>
<hr/>
<button type="button" class="btn btn-primary"
onClick={this.handleContinue}>Continue</button>
</div>
</div>
)
}
}
</code></pre> | 41,052,943 | 6 | 0 | null | 2016-12-09 03:26:49.77 UTC | 0 | 2021-08-10 14:06:23.11 UTC | null | null | null | null | 6,351,303 | null | 1 | 10 | javascript|arrays|reactjs|state | 47,220 | <p><a href="https://facebook.github.io/react/docs/state-and-lifecycle.html#do-not-modify-state-directly" rel="noreferrer">Do not modify state directly!</a> In general, try to <a href="https://facebook.github.io/react/docs/optimizing-performance.html#the-power-of-not-mutating-data" rel="noreferrer">avoid mutation</a>.</p>
<p><code>Array.prototype.push()</code> <em>mutates</em> the array in-place. So essentially, when you <code>push</code> to an array inside <code>setState</code>, you mutate the original state by using <code>push</code>. And since <code>push</code> returns the new array length instead of the actual array, you're setting <code>this.state.userAnswers</code> to a numerical value, and this is why you're getting <code>Uncaught TypeError: this.state.userAnswers.push is not a function(…)</code> on the second run, because you can't <code>push</code> to a number.</p>
<p>You need to use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" rel="noreferrer">Array.prototype.concat()</a> instead. It doesn't mutate the original array, and returns a new array with the new concatenated elements. This is what you want to do inside <code>setState</code>. Your code should look something like this:</p>
<pre><code>this.setState({
userAnswers: this.state.userAnswers.concat(this.state.value),
questionNumber: this.state.questionNumber + 1
}
</code></pre> |
1,869,785 | Putting a div on a new line (problem caused by floating <ul> elements) | <p>So I have a 3 unordered lists like so:</p>
<pre><code> <ul class="menu">
<li class="heading">Title (Click To Download)</li>
<li><a title="Download sample.mp3" href="http://example.com/sample.mp3">Sample Song</a></li>
</ul>
</code></pre>
<p>With the following css style:</p>
<pre><code>/* SITE MAP MENUS */
ul.menu {
float: left;
margin: 0 10px 0 10px;
display: block;
font-size: 13px;
line-height: 24px;
color: #898989;
}
ul.menu li {}
.menuText
{
}
li.heading {
color: #493f0b;
font-weight: bold;
border-bottom: 1px solid #d7d7d7;
}
</code></pre>
<p>However when I put a new div:</p>
<pre><code><div class="pleasedontfloat">The paganation would go here..</div>
</code></pre>
<p>Instead of going below the lists it goes next to them. How would I fix this? (the class pleasedontfloat has no rules applied to it)</p> | 1,869,814 | 1 | 0 | null | 2009-12-08 20:58:18.693 UTC | 2 | 2009-12-08 21:02:02.393 UTC | null | null | null | null | 148,766 | null | 1 | 30 | html|css|internet-explorer|firefox | 55,342 | <pre><code>.pleasedontfloat {
clear:both;
}
</code></pre> |
53,853,815 | How to fix 'Cannot use namespace as a type ts(2709)' in typescript? | <p>I'm loading a third-party library called <code>sorted-array</code> and using it like this:</p>
<pre><code>import SortedArray from 'sorted-array';
export class Selector {
private mySortedArray!: SortedArray;
constructor() {
this.mySortedArray = new SortedArray();
}
}
</code></pre>
<p>However, I get this error: <code>Cannot use namespace 'SortedArray' as a type.ts(2709)</code></p>
<p>So, I created this file:</p>
<pre><code>// src/typings/sorted-array/index.d.ts
declare module 'sorted-array' {
class SortedArray {
constructor(arr: number[]);
search(element: any): number;
}
}
</code></pre>
<p>However, the error remains. What am I doing wrong?</p> | 53,855,886 | 4 | 0 | null | 2018-12-19 14:56:08.807 UTC | 3 | 2022-06-25 02:20:05.323 UTC | null | null | null | null | 355,567 | null | 1 | 22 | typescript | 39,701 | <p>You need to export it inside module declaration:</p>
<pre class="lang-js prettyprint-override"><code>declare module 'sorted-array' {
class SortedArray {
constructor(arr: number[]);
search(element: any): number;
}
export = SortedArray;
}
</code></pre> |
40,570,164 | How to customize the message "Changes you made may not be saved." for window.onbeforeunload? | <p>I am testing in Google Chrome.</p>
<p>I did some search and found that someone is using:</p>
<pre><code>window.onbeforeunload = function() {
if (hook) {
return "Did you save your stuff?"
}
}
</code></pre>
<p>But when I use it, I still got the "Changes you made may not be saved." message. How can I change it to something I want?</p> | 40,570,214 | 2 | 1 | null | 2016-11-13 03:09:31.42 UTC | 4 | 2020-12-12 20:34:42.723 UTC | 2017-10-18 20:44:10.08 UTC | null | 206,730 | null | 1,661,640 | null | 1 | 28 | javascript|google-chrome | 29,541 | <p>You can't, the ability to do this was removed in Chrome 51. It is widely considered a security issue, and most vendors have removed support.</p>
<blockquote>
<h2><a href="https://www.chromestatus.com/feature/5349061406228480">Custom messages in onbeforeunload dialogs (removed)</a>:</h2>
<p>A window’s onbeforeunload property may be set to a function that returns a string. If the function returns a string, then before unloading the page, a dialog is shown to have the user confirm that they indeed want to navigate away. The string provided by the function will no longer be shown in the dialog. Rather, a generic string not under the control of the webpage will be shown.</p>
<h3>Comments</h3>
<p>This shipped in Safari 9.1, and has been shipping in Firefox since Firefox 4. Safari considers this a security fix and assigned it CVE-2009-2197 (see <a href="https://support.apple.com/en-us/HT206171">https://support.apple.com/en-us/HT206171</a> ). Approved with the intent <a href="https://groups.google.com/a/chromium.org/d/msg/blink-dev/YIH8CoYVGSg/Di7TsljXDQAJ">https://groups.google.com/a/chromium.org/d/msg/blink-dev/YIH8CoYVGSg/Di7TsljXDQAJ</a> .</p>
<h3>Specification</h3>
<p><a href="https://html.spec.whatwg.org/multipage/browsers.html#unloading-documents">Established standard</a></p>
<h3>Status in Chromium</h3>
<p>Removed (<a href="http://crbug.com/587940">launch bug</a>) in:</p>
<ul>
<li>Chrome for desktop release 51</li>
<li>Chrome for Android release 51</li>
<li>Android WebView release 51</li>
<li>Opera release 38</li>
<li>Opera for Android release 38</li>
</ul>
</blockquote> |
33,844,290 | How to get Telegram channel users list with Telegram Bot API | <p>Anybody give a starter on how may I get information about users from my telegram bot. Imagine my bot in an admin user in my channel and I want to get my channel user list or to be noticed when a new user joins. How can I do that.
Telegram's documents are so unorganized.
So far I have looked at these:</p>
<ul>
<li><a href="https://core.telegram.org/bots" rel="noreferrer">https://core.telegram.org/bots</a></li>
<li><a href="https://core.telegram.org/bots/api" rel="noreferrer">https://core.telegram.org/bots/api</a></li>
<li><a href="https://core.telegram.org/bots/samples" rel="noreferrer">https://core.telegram.org/bots/samples</a></li>
<li><a href="https://core.telegram.org/bots/faq" rel="noreferrer">https://core.telegram.org/bots/faq</a> </li>
</ul>
<p>But none of these really helps.</p> | 44,552,356 | 6 | 0 | null | 2015-11-21 14:08:10.3 UTC | 9 | 2020-10-01 20:01:10.127 UTC | 2018-11-23 00:39:29.97 UTC | null | 147,057 | null | 2,674,938 | null | 1 | 26 | telegram|telegram-bot | 127,753 | <p>In order to get user list, you need to use telegram API. </p>
<p>Telegram API is fairly complicated. There are some clients which can get the job done much faster. </p>
<p>For python, there is <a href="https://github.com/LonamiWebs/Telethon" rel="noreferrer">Telethon</a>, and the method to get channel users is:</p>
<p><code>get_full_channel</code>. </p> |
50,303,454 | How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp? | <p>Google has revamped its <a href="https://material.io/tools/icons/?style=baseline" rel="noreferrer">Material Design Icons</a> with 4 new preset themes:</p>
<p><strong>Outlined, Rounded, Two-Tone and Sharp</strong>, in addition to the regular <strong>Filled/Baseline</strong> theme:</p>
<hr />
<p><em>But, unfortunately, it doesn't say anywhere how to use the new themes.</em></p>
<hr />
<p>I've been <a href="https://google.github.io/material-design-icons/#icon-font-for-the-web" rel="noreferrer">using it via Google Web Fonts</a> by including the link:</p>
<pre class="lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</code></pre>
<p>And then using the required icon <a href="https://google.github.io/material-design-icons/#using-the-icons-in-html" rel="noreferrer">as suggested in the documentation</a>:</p>
<pre class="lang-html prettyprint-override"><code><i class="material-icons">account_balance</i>
</code></pre>
<p>But it always shows the 'Filled/Baseline' version.</p>
<hr />
<p>I've tried doing the following to use the <strong>Outlined</strong> theme instead:</p>
<pre class="lang-html prettyprint-override"><code><i class="material-icons">account_balance_outlined</i>
<i class="material-icons material-icons-outlined">account_balance</i>
</code></pre>
<p>and, changing the Web Fonts link to:</p>
<pre class="lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/icon?family=Material+Icons&style=outlined" rel="stylesheet">
</code></pre>
<p>etc. But it doesn't work.</p>
<hr />
<p><em>And there's no point in taking shots in the dark like that.</em></p>
<hr />
<p><strong>tl;dr: Has anyone tried using the new themes? Does it even work like the baseline version (inline html tag)? Or, is it only meant to be downloaded as SVG or PNG formats?</strong></p> | 51,415,409 | 15 | 0 | null | 2018-05-12 06:20:22.993 UTC | 87 | 2022-05-27 19:14:12.083 UTC | 2020-08-31 09:14:15.437 UTC | null | 5,740,428 | null | 7,364,168 | null | 1 | 261 | icons|material-design|google-material-icons | 193,345 | <h2>Update (31/03/2019) : All icon themes work via Google Web Fonts now.</h2>
<p>As pointed out by Edric, it's just a matter of adding the google web fonts link in your document's head now, like so:</p>
<pre class="lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp" rel="stylesheet">
</code></pre>
<p>And then adding the correct class to output the icon of a particular theme.</p>
<pre class="lang-html prettyprint-override"><code><i class="material-icons">donut_small</i>
<i class="material-icons-outlined">donut_small</i>
<i class="material-icons-two-tone">donut_small</i>
<i class="material-icons-round">donut_small</i>
<i class="material-icons-sharp">donut_small</i>
</code></pre>
<p>The color of the icons can be changed using CSS as well.</p>
<p>Note: the Two-tone theme icons are a bit glitchy at present.</p>
<hr />
<h2>Update (14/11/2018) : List of 16 outline icons that work with the "_outline" suffix.</h2>
<p>Here's the most recent list of 16 outline icons that work with the regular Material-icons Webfont, using the <strong>_outline</strong> suffix (tested and confirmed).</p>
<p>(As found on the <a href="https://github.com/google/material-design-icons/find/master" rel="noreferrer">material-design-icons github page</a>. Search for: "<strong>_outline_24px.svg</strong>")</p>
<pre class="lang-html prettyprint-override"><code><i class="material-icons">help_outline</i>
<i class="material-icons">label_outline</i>
<i class="material-icons">mail_outline</i>
<i class="material-icons">info_outline</i>
<i class="material-icons">lock_outline</i>
<i class="material-icons">lightbulb_outline</i>
<i class="material-icons">play_circle_outline</i>
<i class="material-icons">error_outline</i>
<i class="material-icons">add_circle_outline</i>
<i class="material-icons">people_outline</i>
<i class="material-icons">person_outline</i>
<i class="material-icons">pause_circle_outline</i>
<i class="material-icons">chat_bubble_outline</i>
<i class="material-icons">remove_circle_outline</i>
<i class="material-icons">check_box_outline_blank</i>
<i class="material-icons">pie_chart_outlined</i>
</code></pre>
<p>Note that <em>pie_chart</em> needs to be "<em>pie_chart_<strong>outlined</strong></em>" and not <em>outline</em>.</p>
<hr />
<h2>This is a hack to test out the new icon themes using an inline tag. It's not the official solution.</h2>
<p>As of today (July 19, 2018), a little over 2 months since the new icons themes were introduced, <strong>there is No Way</strong> to include these icons using an inline tag <code><i class="material-icons"></i></code>.</p>
<p><a href="https://stackoverflow.com/a/50364649/7364168">+Martin</a> has pointed out that there's an issue raised on Github regarding the same: <a href="https://github.com/google/material-design-icons/issues/773" rel="noreferrer">https://github.com/google/material-design-icons/issues/773</a></p>
<p>So, until Google comes up with a solution for this, I've started using a hack to include these new icon themes in my <strong>development environment</strong> before downloading the appropriate icons as SVG or PNG. And I thought I'd share it with you all.</p>
<hr />
<p><strong>IMPORTANT</strong>: Do not use this on a production environment as each of the included CSS files from Google are over 1MB in size.</p>
<hr />
<p>Google uses these stylesheets to showcase the icons on their demo page:</p>
<p><strong>Outline:</strong></p>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/outline.css">
</code></pre>
<p><strong>Rounded:</strong></p>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/round.css">
</code></pre>
<p><strong>Two-Tone:</strong></p>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/twotone.css">
</code></pre>
<p><strong>Sharp:</strong></p>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/sharp.css">
</code></pre>
<p>Each of these files contain the icons of the respective themes included as background-images (Base64 image-data). And here's how we can use this to test out the compatibility of a particular icon in our design before downloading it for use in the production environment.</p>
<hr />
<p><strong>STEP 1</strong>:</p>
<p>Include the stylesheet of the theme that you want to use.
Eg: For the 'Outlined' theme, use the stylesheet for 'outline.css'</p>
<p><strong>STEP 2</strong>:</p>
<p>Add the following classes to your <strong>own</strong> stylesheet:</p>
<pre class="lang-css prettyprint-override"><code>.material-icons-new {
display: inline-block;
width: 24px;
height: 24px;
background-repeat: no-repeat;
background-size: contain;
}
.icon-white {
webkit-filter: contrast(4) invert(1);
-moz-filter: contrast(4) invert(1);
-o-filter: contrast(4) invert(1);
-ms-filter: contrast(4) invert(1);
filter: contrast(4) invert(1);
}
</code></pre>
<p><strong>STEP 3</strong>:</p>
<p>Use the icon by adding the following <strong>classes</strong> to the <code><i></code> tag:</p>
<ol>
<li><p><code>material-icons-new</code> class</p>
</li>
<li><p>Icon name as shown on the material icons demo page, prefixed with the theme name followed by a hyphen.</p>
</li>
</ol>
<p><em>Prefixes:</em></p>
<p>Outlined: <code>outline-</code></p>
<p>Rounded: <code>round-</code></p>
<p>Two-Tone: <code>twotone-</code></p>
<p>Sharp: <code>sharp-</code></p>
<p><em>Eg (for 'announcement' icon):</em></p>
<p><code>outline-announcement</code>, <code>round-announcement</code>, <code>twotone-announcement</code>, <code>sharp-announcement</code></p>
<p><em>3) Use an optional 3rd class <code>icon-white</code> for inverting the color from black to white (for dark backgrounds)</em></p>
<hr />
<p><strong>Changing icon size:</strong></p>
<p>Since this is a background-image and not a font-icon, use the <code>height</code> and <code>width</code> properties of CSS to modify the size of the icons. The default is set to 24px in the <code>material-icons-new</code> class.</p>
<hr />
<p><strong>Example:</strong></p>
<p><strong>Case I:</strong> For the <strong>Outlined</strong> Theme of the <strong>account_circle</strong> icon:</p>
<ol>
<li>Include the stylesheet:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/outline.css">
</code></pre>
<ol start="2">
<li>Add the icon tag on your page:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><i class="material-icons-new outline-account_circle"></i>
</code></pre>
<p><em>Optional (For dark backgrounds):</em></p>
<pre class="lang-html prettyprint-override"><code><i class="material-icons-new outline-account_circle icon-white"></i>
</code></pre>
<hr />
<p><strong>Case II:</strong> For the <strong>Sharp</strong> Theme of the <strong>assessment</strong> icon:</p>
<ol>
<li>Include the stylesheet:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/sharp.css">
</code></pre>
<ol start="2">
<li>Add the icon tag on your page:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><i class="material-icons-new sharp-assessment"></i>
</code></pre>
<p><em>(For dark backgrounds):</em></p>
<pre class="lang-html prettyprint-override"><code><i class="material-icons-new sharp-assessment icon-white"></i>
</code></pre>
<hr />
<p>I can't stress enough that this is NOT THE RIGHT WAY to include the icons on your production environment. But if you have to scan through multiple icons on your in-development page, it does make the icon inclusion pretty easy and saves a lot of time.</p>
<p>Downloading the icon as SVG or PNG sure is a better option when it comes to site-speed optimization, but font-icons are a time-saver when it comes to the prototyping phase and checking if a particular icon goes with your design, etc.</p>
<hr />
<p><strong>I will update this post if and when Google comes up with a solution for this issue that does not involve downloading an icon for usage.</strong></p> |
43,023,107 | How to connect Google Cloud SQL from Cloud Functions? | <p>I am trying to use <a href="https://firebase.google.com/docs/functions/" rel="noreferrer">Cloud Functions for Firebase</a> to build an API that talks with a Google Cloud SQL (PostgreSQL) instance.</p>
<p>I am using HTTP(S) trigger.</p>
<p>When I white-list my desktop's IP address, I can connect to the Cloud SQL with the function's node.js code from my local machine. But when I deploy, I can't connect, and I can't figure out the HOST IP address of Firebase Function's server, to white-list.</p>
<p>How do you talk to Google Cloud SQL from Cloud Functions for Firebase?</p>
<p>Thanks!</p>
<pre><code>// Code Sample, of what's working on Localhost.
var functions = require('firebase-functions');
var pg = require('pg');
var pgConfig = {
user: functions.config().pg.user,
database: functions.config().pg.database,
password: functions.config().pg.password,
host: functions.config().pg.host
}
exports.helloSql = functions.https.onRequest((request, response) => {
console.log('connecting...');
try {
client.connect(function(err) {
if (err) throw err;
console.log('connection success');
console.log('querying...');
client.query('SELECT * FROM guestbook;', function(err, result){
if (err) throw err;
console.log('querying success.');
console.log('Results: ', result);
console.log('Ending...');
client.end(function(err){
if (err) throw err;
console.log('End success.');
response.send(result);
});
});
});
} catch(er) {
console.error(er.stack)
response.status(500).send(er);
}
});
</code></pre> | 43,257,853 | 7 | 0 | null | 2017-03-25 23:23:35.09 UTC | 20 | 2021-08-23 14:42:20.213 UTC | 2017-03-26 04:06:59.033 UTC | null | 807,126 | null | 400,836 | null | 1 | 38 | javascript|firebase|google-cloud-platform|google-cloud-sql|google-cloud-functions | 29,230 | <p><strong>New Answer</strong>:</p>
<p>See other answers, it's now officially supported. <a href="https://cloud.google.com/functions/docs/sql" rel="nofollow noreferrer">https://cloud.google.com/functions/docs/sql</a></p>
<p><strong>Old Answer</strong>:</p>
<p>It's not currently possible. It is however a feature request on the issue tracker <a href="https://issuetracker.google.com/issues/36388165" rel="nofollow noreferrer">#36388165</a>:</p>
<blockquote>
<p>Connecting to Cloud SQL from Cloud Functions is currently not
supported, as the UNIX socket does not exist (causing ENOENT) and
there is no defined IP range to whitelist (causing ETIMEDOUT). One
possibility is to whitelist 0.0.0.0/0 from the Cloud SQL instance but
this is not recommended for security reasons.</p>
</blockquote>
<p>If this is an important feature for you I would suggest you visit the issuetracker and star the feature request to help it gain popularity.</p> |
28,969,455 | How to properly instantiate os.FileMode | <p>I have seen countless examples and tutorials that show how to create a file and all of them "cheat" by just setting the permission bits of the file. I would like to know / find out how to properly instantiate os.FileMode to provide to a writer during creation / updating of a file.</p>
<p>A crude example is this below:</p>
<pre><code>func FileWrite(path string, r io.Reader, uid, gid int, perms string) (int64, error){
w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0664)
if err != nil {
if path == "" {
w = os.Stdout
} else {
return 0, err
}
}
defer w.Close()
size, err := io.Copy(w, r)
if err != nil {
return 0, err
}
return size, err
}
</code></pre>
<p>In the basic function above permission bits 0664 is set and although this may make sense sometimes I prefer to have a proper way of setting the filemode correctly. As seen above a common example would be that the UID / GID is known and already provided as int values and the perms being octal digits that were previously gathered and inserted into a db as a string.</p> | 28,969,523 | 3 | 0 | null | 2015-03-10 16:47:09.613 UTC | 10 | 2022-08-18 21:54:10.647 UTC | 2020-05-08 15:48:56.99 UTC | null | 13,860 | null | 1,198,639 | null | 1 | 35 | go|int|file-permissions | 36,130 | <p><code>FileMode</code> is just a uint32. <a href="http://golang.org/pkg/os/#FileMode" rel="noreferrer">http://golang.org/pkg/os/#FileMode</a></p>
<p>Setting via constants isn't "cheating", you use it like other numeric values. If you're not using a constant, you can use a conversion on valid numeric values:</p>
<pre><code>mode := int(0777)
os.FileMode(mode)
</code></pre> |
36,321,899 | Mongorestore to a different database | <p>In MongoDB, is it possible to dump a database and restore the content to a different database? For example like this:</p>
<pre><code>mongodump --db db1 --out dumpdir
mongorestore --db db2 --dir dumpdir
</code></pre>
<p>But it doesn't work. Here's the error message:</p>
<blockquote>
<p>building a list of collections to restore from dumpdir dir</p>
<p>don't know what to do with subdirectory "dumpdir/db1", skipping...</p>
<p>done</p>
</blockquote> | 36,322,080 | 5 | 0 | null | 2016-03-31 00:00:55 UTC | 12 | 2022-02-25 17:48:05.213 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 418,966 | null | 1 | 83 | mongodb|mongorestore | 55,931 | <p>You need to actually point at the <a href="https://docs.mongodb.org/manual/reference/program/mongorestore/#restore-a-collection" rel="noreferrer">"database name" container</a> directory "within" the output directory from the previous dump:</p>
<pre><code>mongorestore -d db2 dumpdir/db1
</code></pre>
<p>And usually just <path> is fine as a positional argument rather than with <code>-dir</code> which would only be needed when "out of position" i.e "in the middle of the arguments list".</p>
<p>p.s. For archive backup file (<a href="https://github.com/namgivu/mongodb-start/blob/master/01.backup-restore.sh" rel="noreferrer">tested</a> with mongorestore v3.4.10)</p>
<pre><code>mongorestore --gzip --archive=${BACKUP_FILE_GZ} --nsFrom "${DB_NAME}.*" --nsTo "${DB_NAME_RESTORE}.*"
</code></pre> |
64,296,359 | How can I install pip for Python2.7 in Ubuntu 20.04 | <p>Is there any way that I can install "pip" for "Python2.7" ?
I could install python2.7 by</p>
<pre><code>sudo apt install python2-minimal
</code></pre>
<p>I tried installing pip for this.</p>
<pre><code>sudo apt install python-pip / python2-pip / python2.7-pip
</code></pre>
<p>but none worked. Can anybody have solution for this.</p> | 64,297,311 | 2 | 0 | null | 2020-10-10 17:33:36.077 UTC | 10 | 2022-08-13 02:00:13.207 UTC | 2020-12-03 11:41:28.13 UTC | null | 1,000,551 | null | 4,472,576 | null | 1 | 21 | python|python-2.7|pip|ubuntu-20.04 | 44,625 | <p>Pip for Python 2 is not included in the Ubuntu 20.04 repositories.</p>
<p>Try <a href="https://linuxize.com/post/how-to-install-pip-on-ubuntu-20.04/" rel="noreferrer">this guide</a> which suggests to fetch a Python 2.7 compatible <code>get_pip.py</code> and use that to bootstrap <code>pip</code>.</p>
<pre><code>curl https://bootstrap.pypa.io/pip/2.7/get-pip.py --output get-pip.py
</code></pre> |
26,414,880 | Create drop down list in input-box | <p>I'm creating a task list for our team, and to enter new tasks i've created input-boxes.
There are only 5 departments that should be entered in the "department question"
Te prevent people from entering a wrong department name, i would like to use that input-box a drop down list. </p>
<p>I've searched the net, but could not find how to create a drop down list in an input-box. I don't know if this is possible? </p>
<p>Can anyone help me?</p>
<p>The code i wrote for the inputs are as followed:</p>
<pre><code>Private Sub Newaction_Click()
Dim content As String, date1 As Date, date2 As Date, department As String
Sheets("DO NOT DELETE").Rows("30:30").Copy
Rows("14:14").Select
Range("C14").Activate
Selection.Insert Shift:=xlDown
content = InputBox("describe the task")
Range("C14").Value = content
department = InputBox("to which department is the task assigned? ") '<-- here i want to create drop down list
Range("D14").Value = department
date1 = InputBox("when does the task start")
Range("F14").Value = date1
date2 = InputBox("when should the task be finished? ")
Range("G14").Value = date2
End Sub
</code></pre> | 26,416,093 | 2 | 0 | null | 2014-10-16 22:21:28.017 UTC | null | 2021-03-06 14:01:58.62 UTC | 2014-10-16 22:46:58.997 UTC | null | 2,165,759 | null | 3,939,900 | null | 1 | 0 | excel|vba | 42,811 | <p>I have created a form in excel in stead of using input box.
For the selection of department i created a combo-box with the correct departments:</p>
<pre><code>Private Sub Newaction_Click()
Sheets("DO NOT DELETE").Rows("30:30").Copy
Rows("14:14").Select
Range("C14").Activate
Selection.Insert Shift:=xlDown
Cells(14, 3) = Taskd.Value
Cells(14, 5) = ComboBox1
Unload Me
UserForm2.Show
End Sub
Private Sub UserForm_Initialize()
Taskd.Value = ""
With ComboBox1
.AddItem "Lean"
.AddItem "Maintenance"
.AddItem "Process Engineering"
.AddItem "Safety"
.AddItem "Workinstructions"
End With
End Sub
</code></pre>
<p>For the dates i created a separate form (userfrom2 and userform3) to enter the dates on a calander. </p>
<pre><code>Private Sub MonthView1_DateClick(ByVal DateClicked As Date)
On Error Resume Next
startd = DateClicked
Cells(14, 6).Value = startd
Unload Me
UserForm3.Show
End Sub
Private Sub MonthView1_DateClick(ByVal DateClicked As Date)
On Error Resume Next
endd = DateClicked
Cells(14, 7).Value = endd
Unload Me
End Sub
</code></pre>
<p>The Monthview1 is an extra option in Excel which you can activate via:
forms toolbox --> right click on toolbox --> select Additional controls --> Microsoft Monthviews control</p> |
28,027,236 | Blade: escaping text and allowing new lines | <p>I have a user-input text displayed on one of the pages. I want to allow new lines, though. How do I display the text, so it is <strong>escaped</strong> AND <strong>allows new lines</strong>?</p>
<p>I used <code>nl2br()</code> and Blade's tripple brackets <code>{{{$text}}}</code>, however, obviously, the tripple brackets escape <code><br/></code> tags as well.</p>
<p>Is there a way to combine escaping and HTML's new lines using Blade?</p>
<p>Thanks.</p> | 28,027,358 | 3 | 0 | null | 2015-01-19 14:47:13.51 UTC | 13 | 2020-02-26 20:20:38.873 UTC | null | null | null | null | 2,890,610 | null | 1 | 58 | php|laravel|escaping|laravel-blade | 52,258 | <p>You can do the escaping first, using <code>e()</code> and then apply <code>nl2br()</code>:</p>
<pre><code>{{ nl2br(e($text)) }}
</code></pre>
<p><code>e()</code> is the function Blade uses when compiling triple brackets</p> |
26,941,529 | Swift: testing against optional value in switch case | <p>In Swift, how can I write a case in a switch statement that tests the value being switched against the contents of an <em>optional</em>, skipping over the case if the optional contains <code>nil</code>?</p>
<p>Here's how I imagine this might look:</p>
<pre><code>let someValue = 5
let someOptional: Int? = nil
switch someValue {
case someOptional:
// someOptional is non-nil, and someValue equals the unwrapped contents of someOptional
default:
// either, someOptional is nil, or someOptional is non-nil but someValue does not equal the unwrapped contents of someOptional
}
</code></pre>
<p>If I just write it exactly like this, the compiler complains that <code>someOptional</code> is not unwrapped, but if I explicitly unwrap it by adding <code>!</code> to the end, I of course get a runtime error any time <code>someOptional</code> contains <code>nil</code>. Adding <code>?</code> instead of <code>!</code> would make some sense to me (in the spirit of optional chaining, I suppose), but doesn't make the compiler error go away (i.e. doesn't actually unwrap the optional).</p> | 26,941,591 | 4 | 0 | null | 2014-11-15 01:30:44.623 UTC | 14 | 2022-06-08 09:48:28.1 UTC | 2017-11-17 17:37:03.177 UTC | null | 5,175,709 | null | 2,680,007 | null | 1 | 112 | swift|enums|switch-statement|option-type | 48,724 | <p>Optional is just a <code>enum</code> like this:</p>
<pre><code>enum Optional<T> : Reflectable, NilLiteralConvertible {
case none
case some(T)
// ...
}
</code></pre>
<p>So you can match them as usual <a href="https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-XID_225" rel="noreferrer">"Associated Values"</a> matching patterns:</p>
<pre><code>let someValue = 5
let someOptional: Int? = nil
switch someOptional {
case .some(someValue):
println("the value is \(someValue)")
case .some(let val):
println("the value is \(val)")
default:
println("nil")
}
</code></pre>
<p>If you want match from <code>someValue</code>, using <a href="https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Statements.html#//apple_ref/doc/uid/TP40014097-CH33-XID_1063" rel="noreferrer">guard expression</a>:</p>
<pre><code>switch someValue {
case let val where val == someOptional:
println(someValue)
default:
break
}
</code></pre>
<p><strong>And for Swift > 2.0</strong></p>
<pre><code>switch someValue {
case let val where val == someOptional:
print("matched")
default:
print("didn't match; default")
}
</code></pre> |
2,505,435 | Good jQuery pagination plugin to use with JSON data | <p>I am looking for a good jQuery pagination plugin to use in my aspx page.</p>
<p>I have the following parameters.
<code>currentpage, pagesize, TotalRecords, NumberofPages</code>. I would like my plugin to do the same as Stack Overflow paging.</p>
<p><strong>EDIT:</strong>
It should paginate through JSON data.</p>
<p>Similar to this,</p>
<p><a href="https://i.stack.imgur.com/Tef7H.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tef7H.jpg" alt="pager"></a>
</p>
<p>I use my JSON data and iterating with jQuery</p>
<pre><code>var jsonObj = jQuery.parseJSON(HfJsonValue);
for (var i = jsonObj.Table.length - 1; i >= 0; i--) {
var employee = jsonObj.Table[i];
$('<div class="resultsdiv"><br /><span class="resultName">' + employee.Emp_Name + '</span><span class="resultfields" style="padding-left:100px;">Category&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" class="resultfields">Salary Basis&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.SalaryBasis + '</span><span class="resultfields" style="padding-left:25px;">Salary&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.FixedSalary + '</span><span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Address + '</span></div>').insertAfter('#ResultsDiv');
}
</code></pre>
<p>There are 25 divs in my page. As a result, how do I show the first five divs in page <code>1</code> and so on?</p>
<p>My <code>HfJsonValue</code> contains the following json data</p>
<pre><code>{
"Table": [{
"Emp_Id": "3",
"Identity_No": "",
"Emp_Name": "Jerome",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Supervisior",
"Desig_Description": "Supervisior of the Construction",
"SalaryBasis": "Monthly",
"FixedSalary": "25000.00"
}, {
"Emp_Id": "4",
"Identity_No": "",
"Emp_Name": "Mohan",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Acc ",
"Desig_Description": "Accountant",
"SalaryBasis": "Monthly",
"FixedSalary": "200.00"
}, {
"Emp_Id": "5",
"Identity_No": "",
"Emp_Name": "Murugan",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Mason",
"Desig_Description": "Mason",
"SalaryBasis": "Weekly",
"FixedSalary": "150.00"
}, {
"Emp_Id": "6",
"Identity_No": "",
"Emp_Name": "Ram",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Mason",
"Desig_Description": "Mason",
"SalaryBasis": "Weekly",
"FixedSalary": "120.00"
}, {
"Emp_Id": "7",
"Identity_No": "",
"Emp_Name": "Raja",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Mason",
"Desig_Description": "Mason",
"SalaryBasis": "Weekly",
"FixedSalary": "135.00"
}, {
"Emp_Id": "8",
"Identity_No": "",
"Emp_Name": "Raja kumar",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Mason Helper",
"Desig_Description": "Mason Helper",
"SalaryBasis": "Weekly",
"FixedSalary": "105.00"
}, {
"Emp_Id": "9",
"Identity_No": "",
"Emp_Name": "Lakshmi",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Mason Helper",
"Desig_Description": "Mason Helper",
"SalaryBasis": "Weekly",
"FixedSalary": "100.00"
}, {
"Emp_Id": "10",
"Identity_No": "",
"Emp_Name": "Palani",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Carpenter",
"Desig_Description": "Carpenter",
"SalaryBasis": "Weekly",
"FixedSalary": "200.00"
}, {
"Emp_Id": "11",
"Identity_No": "",
"Emp_Name": "Annamalai",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Carpenter",
"Desig_Description": "Carpenter",
"SalaryBasis": "Weekly",
"FixedSalary": "220.00"
}, {
"Emp_Id": "12",
"Identity_No": "",
"Emp_Name": "David",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Steel Fixer",
"Desig_Description": "Steel Fixer",
"SalaryBasis": "Weekly",
"FixedSalary": "220.00"
}, {
"Emp_Id": "13",
"Identity_No": "",
"Emp_Name": "Chandru",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Steel Fixer",
"Desig_Description": "Steel Fixer",
"SalaryBasis": "Weekly",
"FixedSalary": "220.00"
}, {
"Emp_Id": "14",
"Identity_No": "",
"Emp_Name": "Mani",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Steel Helper",
"Desig_Description": "Steel Helper",
"SalaryBasis": "Weekly",
"FixedSalary": "175.00"
}, {
"Emp_Id": "15",
"Identity_No": "",
"Emp_Name": "Karthik",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Wood Fixer",
"Desig_Description": "Wood Fixer",
"SalaryBasis": "Weekly",
"FixedSalary": "195.00"
}, {
"Emp_Id": "16",
"Identity_No": "",
"Emp_Name": "Bala",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Wood Fixer",
"Desig_Description": "Wood Fixer",
"SalaryBasis": "Weekly",
"FixedSalary": "185.00"
}, {
"Emp_Id": "17",
"Identity_No": "",
"Emp_Name": "Tamil arasi",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Wood Helper",
"Desig_Description": "Wood Helper",
"SalaryBasis": "Weekly",
"FixedSalary": "185.00"
}, {
"Emp_Id": "18",
"Identity_No": "",
"Emp_Name": "Perumal",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Cook",
"Desig_Description": "Cook",
"SalaryBasis": "Weekly",
"FixedSalary": "105.00"
}, {
"Emp_Id": "19",
"Identity_No": "",
"Emp_Name": "Andiappan",
"Address": "Madurai",
"Date_Of_Birth": "",
"Desig_Name": "Watchman",
"Desig_Description": "Watchman",
"SalaryBasis": "Weekly",
"FixedSalary": "150.00"
}]
}
</code></pre>
<blockquote>
<p><strong>See additional answers to duplicate of this question:</strong> </p>
<p><a href="https://stackoverflow.com/questions/2507844/how-to-use-jquery-to-paginate-json-data">How to use jQuery to paginate JSON data?</a></p>
</blockquote> | 2,546,799 | 1 | 2 | null | 2010-03-24 05:00:05.917 UTC | 10 | 2019-07-05 16:04:02.907 UTC | 2019-07-05 16:04:02.907 UTC | null | 4,751,173 | null | 207,556 | null | 1 | 9 | jquery|plugins|pagination | 23,606 | <p>Duplicate question, duplicate anwser...</p>
<p>You can use the jQuery Pagination plugin:</p>
<p><a href="http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm" rel="noreferrer">http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm</a></p>
<p>(Download it <a href="http://plugins.jquery.com/project/pagination" rel="noreferrer">here</a>)</p>
<hr>
<p>Here is one way (of several different) how you can use the plugin.</p>
<p><strong>Step 1:</strong> Generate markup from your JSON-data like the following:</p>
<pre><code><div id="display">
<!-- This is the div where the visible page will be displayed -->
</div>
<div id="hiddenData">
<!-- This is the div where you output your records -->
<div class="record">
<!-- create one record-div for each record you have in your JSON data -->
</div>
<div class="record">
</div>
</div>
</code></pre>
<p>The idea is to copy the respective record to the display div when clicking on a page-link. Therefore, the plugin offers a pageSelect-callback function. <strong>Step 2</strong> is to implement this function, for instance:</p>
<pre><code>function pageselectCallback(pageIndex, jq) {
// Clone the record that should be displayed
var newContent = $('#hiddenData div.record:eq('+pageIndex+')').clone();
// Update the display container
$('#display').empty().append(newContent);
return false;
}
</code></pre>
<p>This would mean that you have one page per record. If you want to display multiple records per page, you have to modify the above function accordingly.</p>
<p><strong>The third and final step</strong> is to initialize the whole thing correctly.</p>
<pre><code>function initPagination() {
// Hide the records... they shouldn't be displayed
$("#hiddenData").css("display", "none");
// Get the number of records
var numEntries = $('#hiddenData div.result').length;
// Create pagination element
$("#pagination").pagination(numEntries, {
num_edge_entries: 2,
num_display_entries: 8, // number of page links displayed
callback: pageselectCallback,
items_per_page: 1 // Adjust this value if you change the callback!
});
}
</code></pre>
<p>So, you just have to generate the HTML markup from your JSON data and call the init-function afterwards.</p> |
3,054,612 | How to vectorize R strsplit? | <p>When creating functions that use <code>strsplit</code>, vector inputs do not behave as desired, and <code>sapply</code> needs to be used. This is due to the list output that <code>strsplit</code> produces. Is there a way to vectorize the process - that is, the function produces the correct element in the list for each of the elements of the input?</p>
<p>For example, to count the lengths of words in a character vector:</p>
<pre><code>words <- c("a","quick","brown","fox")
> length(strsplit(words,""))
[1] 4 # The number of words (length of the list)
> length(strsplit(words,"")[[1]])
[1] 1 # The length of the first word only
> sapply(words,function (x) length(strsplit(x,"")[[1]]))
a quick brown fox
1 5 5 3
# Success, but potentially very slow
</code></pre>
<p>Ideally, something like <code>length(strsplit(words,"")[[.]])</code> where <code>.</code> is interpreted as the being the relevant part of the input vector.</p> | 3,054,644 | 1 | 0 | null | 2010-06-16 15:14:31.757 UTC | 9 | 2015-05-18 02:00:59.043 UTC | 2015-05-18 02:00:59.043 UTC | null | 202,229 | null | 269,476 | null | 1 | 15 | r|vectorization|strsplit | 14,186 | <p>In general, you should try to use a vectorized function to begin with. Using <code>strsplit</code> will frequently require some kind of iteration afterwards (which will be slower), so try to avoid it if possible. In your example, you should use <code>nchar</code> instead:</p>
<pre><code>> nchar(words)
[1] 1 5 5 3
</code></pre>
<p>More generally, take advantage of the fact that <code>strsplit</code> returns a list and use <code>lapply</code>:</p>
<pre><code>> as.numeric(lapply(strsplit(words,""), length))
[1] 1 5 5 3
</code></pre>
<p>Or else use an <code>l*ply</code> family function from <code>plyr</code>. For instance:</p>
<pre><code>> laply(strsplit(words,""), length)
[1] 1 5 5 3
</code></pre>
<p><em>Edit:</em></p>
<p>In honor of <a href="http://en.wikipedia.org/wiki/Bloomsday" rel="noreferrer"><strong>Bloomsday</strong></a>, I decided to test the performance of these approaches using Joyce's Ulysses:</p>
<pre><code>joyce <- readLines("http://www.gutenberg.org/files/4300/4300-8.txt")
joyce <- unlist(strsplit(joyce, " "))
</code></pre>
<p>Now that I have all the words, we can do our counts:</p>
<pre><code>> # original version
> system.time(print(summary(sapply(joyce, function (x) length(strsplit(x,"")[[1]])))))
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.000 3.000 4.000 4.666 6.000 69.000
user system elapsed
2.65 0.03 2.73
> # vectorized function
> system.time(print(summary(nchar(joyce))))
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.000 3.000 4.000 4.666 6.000 69.000
user system elapsed
0.05 0.00 0.04
> # with lapply
> system.time(print(summary(as.numeric(lapply(strsplit(joyce,""), length)))))
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.000 3.000 4.000 4.666 6.000 69.000
user system elapsed
0.8 0.0 0.8
> # with laply (from plyr)
> system.time(print(summary(laply(strsplit(joyce,""), length))))
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.000 3.000 4.000 4.666 6.000 69.000
user system elapsed
17.20 0.05 17.30
> # with ldply (from plyr)
> system.time(print(summary(ldply(strsplit(joyce,""), length))))
V1
Min. : 0.000
1st Qu.: 3.000
Median : 4.000
Mean : 4.666
3rd Qu.: 6.000
Max. :69.000
user system elapsed
7.97 0.00 8.03
</code></pre>
<p>The vectorized function and <code>lapply</code> are considerably faster than the original <code>sapply</code> version. All solutions return the same answer (as seen by the summary output). </p>
<p>Apparently the latest version of <code>plyr</code> is faster (this is using a slightly older version).</p> |
6,238,232 | How to clear the entire console window? | <p>I am making a console window RPG, yet I'm having problems clearing the entire console window. Is there a way for me to clear the entire console window with one command?</p> | 6,238,239 | 1 | 0 | null | 2011-06-04 17:18:16.19 UTC | 6 | 2020-07-04 13:16:47.563 UTC | 2020-07-04 13:16:47.563 UTC | null | 8,422,953 | null | 784,125 | null | 1 | 36 | c#|console|window | 57,137 | <p>You can use the <a href="http://msdn.microsoft.com/en-us/library/system.console.clear.aspx">Clear()</a> method:</p>
<pre><code>Console.Clear();
</code></pre> |
44,805,984 | Golang interface to struct | <p>I have a function that has a parameter with the type interface{}, something like:</p>
<pre><code>func LoadTemplate(templateData interface{}) {
</code></pre>
<p>In my case, templateData is a struct, but each time it has a different structure. I used the type "interface{}" because it allows me to send all kind of data.</p>
<p>I'm using this templateData to send the data to the template:</p>
<pre><code>err := tmpl.ExecuteTemplate(w, baseTemplateName, templateData)
</code></pre>
<p>But now I want to append some new data and I don't know how to do it because the "interface" type doesn't allow me to add/append anything. </p>
<p>I tried to convert the interface to a struct, but I don't know how to append data to a struct with an unknown structure. </p>
<p>If I use the following function I can see the interface's data:</p>
<pre><code>templateData = appendAssetsToTemplateData(templateData)
func appendAssetsToTemplateData(t interface{}) interface{} {
switch reflect.TypeOf(t).Kind() {
case reflect.Struct:
fmt.Println("struct")
s := reflect.ValueOf(t)
fmt.Println(s)
//create a new struct based on current interface data
}
return t
}
</code></pre>
<p>Any idea how can I append a child to the initial interface parameter (templateData)? Or how can I transform it to a struct or something else in order to append the new child/data?</p> | 44,813,472 | 4 | 1 | null | 2017-06-28 14:53:44.763 UTC | 6 | 2019-05-05 12:22:23.043 UTC | 2017-06-29 09:25:15.477 UTC | null | 6,375,113 | null | 1,564,840 | null | 1 | 9 | go|struct|interface | 64,271 | <p>Adrian is correct. To take it a step further, you can only do anything with interfaces if you know the type that implements that interface. The empty interface, <code>interface{}</code> isn't really an "anything" value like is commonly misunderstood; it is just an interface that is immediately satisfied by all types.</p>
<p>Therefore, you can only get values from it or create a new "interface" with added values by knowing the type satisfying the empty interface before and after the addition.</p>
<p>The closest you can come to doing what you want, given the static typing, is by embedding the before type in the after type, so that everything can still be accessed at the root of the after type. The following illustrates this.</p>
<p><a href="https://play.golang.org/p/JdF7Uevlqp" rel="noreferrer">https://play.golang.org/p/JdF7Uevlqp</a></p>
<pre><code>package main
import (
"fmt"
)
type Before struct {
m map[string]string
}
type After struct {
Before
s []string
}
func contrivedAfter(b interface{}) interface{} {
return After{b.(Before), []string{"new value"}}
}
func main() {
b := Before{map[string]string{"some": "value"}}
a := contrivedAfter(b).(After)
fmt.Println(a.m)
fmt.Println(a.s)
}
</code></pre>
<p>Additionally, since the data you are passing to the template does not require you to specify the type, you could use an anonymous struct to accomplish something very similar.</p>
<p><a href="https://play.golang.org/p/3KUfHULR84" rel="noreferrer">https://play.golang.org/p/3KUfHULR84</a></p>
<pre><code>package main
import (
"fmt"
)
type Before struct {
m map[string]string
}
func contrivedAfter(b interface{}) interface{} {
return struct{
Before
s []string
}{b.(Before), []string{"new value"}}
}
func main() {
b := Before{map[string]string{"some": "value"}}
a := contrivedAfter(b)
fmt.Println(a)
}
</code></pre> |
48,429,390 | Firebase deploy errors starting with non-zero exit code (space in project path) | <p>I was having issues with firebase deploy command recently. After firebase deploy command all others were being deployed except firebase (storage, database etc) So I decided to reinstall firebase to fix this situation but after reinstall my problem got bigger. Now none of them are deployed with the following error:</p>
<pre><code>i deploying database, functions
Running command: npm --prefix $RESOURCE_DIR run lint
npm ERR! path C:\Users\faruk\Google Drive\Android\firebase\1\$RESOURCE_DIR\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\faruk\Google Drive\Android\firebase\1\$RESOURCE_DIR\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\faruk\AppData\Roaming\npm-cache\_logs\2018-01-24T18_21_34_878Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code4294963238
</code></pre>
<p>After a bit research, I saw some topics about this which advice to change</p>
<pre><code>$RESOURCE_DIR to %RESOURCE_DIR%
</code></pre>
<p>in windows systems (I am using windows 10 btw). So, I edited my <em>firebase.json</em> file which is in one upper level of my functions folder. like this. (I don't know if this is the right file that I should edit)</p>
<pre><code> "database": {
"rules": "database.rules.json"
},
"functions": {
"predeploy": [
"npm --prefix %RESOURCE_DIR% run lint"
]
}
}
</code></pre>
<p>but after this edit, I started to get another error message like this.</p>
<pre><code>i deploying database, functions
Running command: npm --prefix %RESOURCE_DIR% run lint
Usage: npm <command>
where <command> is one of:
access, adduser, bin, bugs, c, cache, completion, config,
ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
explore, get, help, help-search, i, init, install,
install-test, it, link, list, ln, login, logout, ls,
outdated, owner, pack, ping, prefix, profile, prune,
publish, rb, rebuild, repo, restart, root, run, run-script,
s, se, search, set, shrinkwrap, star, stars, start, stop, t,
team, test, token, tst, un, uninstall, unpublish, unstar,
up, update, v, version, view, whoami
npm <command> -h quick help on <command>
npm -l display full usage info
npm help <term> search for help on <term>
npm help npm involved overview
Specify configs in the ini-formatted file:
C:\Users\faruk\.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config
[email protected] C:\Program Files\nodejs\node_modules\npm
Error: functions predeploy error: Command terminated with non-zero exit code1
</code></pre>
<p>Any advice is appreciated. Thanks in advance.</p> | 48,430,314 | 17 | 0 | null | 2018-01-24 18:33:43.487 UTC | 8 | 2022-09-16 04:11:08.653 UTC | 2018-06-24 03:29:30.76 UTC | null | 7,379,765 | null | 4,688,845 | null | 1 | 34 | node.js|firebase|google-cloud-functions|firebase-cli | 41,553 | <p>The error stems from the fact that you have a space somewhere in the path of your project ("Google Drive"):</p>
<pre><code>C:\Users\faruk\Google Drive\Android\firebase\1\$RESOURCE_DIR\package.json
</code></pre>
<p>Unfortunately, this is confusing the npm command line, and it's taking that as two arguments separated by that space.</p>
<p>Normally, I would expect to be able to place quotes around the whole thing to keep the space from being interpreted that way. So I tried this:</p>
<pre><code>"predeploy": [
"npm --prefix \"%RESOURCE_DIR%\" run lint"
]
</code></pre>
<p>And it works for me.</p>
<p>I'll follow up with the Firebase team internally about this issue, as well as the fact that changes need to be made for Windows.</p> |
21,122,842 | What's the difference between synchronous and asynchronous calls in Objective-C, versus multi-threading? | <p>For the longest time I thought asynchronous was synonymous to running something on a background thread, while synchronous meant on the main thread (blocking UI updates and interactions). I understand that not running on the main thread for expensive actions is because it doesn't allow UI actions to occur as the main thread is occupied, but why is synchronous troublesome?</p>
<p>However, it's since came to my attention that you can make asynchronous calls on the main thread, and synchronous calls on background threads.</p>
<p>I always hear people saying not to use expensive calls synchronously or on the main thread, as it will block the UI for the user. Are these two separate issues I should be making sure I don't do? What are the differences?</p> | 21,123,301 | 6 | 0 | null | 2014-01-14 20:01:01.237 UTC | 44 | 2018-07-16 06:26:15.407 UTC | null | null | null | null | 998,117 | null | 1 | 58 | ios|objective-c|multithreading|asynchronous|grand-central-dispatch | 82,589 | <p>When you invoke something synchronously, it means that the thread that initiated that operation will wait for the task to finish before continuing. Asynchronous means that it will not wait.</p>
<p>Having said that, when people suggest that you perform some slow or expensive process asynchronously, they are implicitly suggesting not only that you should run it asynchronously, but that you should do that on a background thread. The goal is to free the main thread so that it can continue to respond to the user interface (rather than freezing), so you are dispatching tasks to a background thread asynchronously.</p>
<p>So, there are two parts to that. First, using GCD as an example, you grab a background queue (either grab one of the global background queues, or create your own):</p>
<pre><code>// one of the global concurrent background queues
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// or you could create your own serial background queue:
//
// dispatch_queue_t queue = dispatch_queue_create("com.domain.app.queuename", 0);
</code></pre>
<p>Second, you dispatch your tasks to that queue asynchronously:</p>
<pre><code>dispatch_async(queue, ^{
// the slow stuff to be done in the background
});
</code></pre>
<p>The pattern for operation queues is very similar. Create an operation queue and add operations to that queue.</p>
<p>In reality, the synchronous vs asynchronous distinction is completely different from the main queue vs background queue distinction. But when people talk about "run some slow process asynchronously", they're really saying "run some slow process asynchronously on a background queue."</p> |
49,475,177 | Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified | <p>I have created a basic spring boot application from <strong>SPRING INITIALIZR</strong> with the Web, MongoDB and JPA dependencies. </p>
<p>When I try to run the spring boot application I am getting the following exception:</p>
<pre><code>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-03-25 16:27:02.807 ERROR 16256 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following situation:
If you want an embedded database like H2, HSQL or Derby, please add it in the Classpath.
If you have database settings to be loaded from a particular profile you may need to activate it since no profiles were currently active.
</code></pre>
<p>In application.properties file I am having the following configuration:</p>
<pre><code>server.port=8081
spring.data.mongodb.database=TestDatabase
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
</code></pre>
<p><strong>Versions which I use:</strong>
Spring : 5.0.4,
MongoDB : 3.6,
Spring Boot: 2.0</p> | 49,475,397 | 13 | 0 | null | 2018-03-25 11:14:36.067 UTC | 15 | 2022-03-29 06:07:01.503 UTC | 2018-04-11 13:03:42.843 UTC | null | 7,855,784 | null | 7,855,784 | null | 1 | 50 | java|spring|mongodb|spring-boot|spring-data-jpa | 149,227 | <p>Since you have added both mongodb and data-jpa dependencies in your pom.xml file, it was creating a dependency conflict like below</p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</code></pre>
<p>Try removing jpa dependency and run. It should work fine.</p> |
34,763,090 | Bootstrap 4 with remote Modal | <p>I can't make the Modal work in the remote mode with the new Twitter Bootstrap release : Bootstrap 4 alpha. It works perfectly fine with Bootstrap 3. With bootstrap 4 I am getting the popup window, but the model body is not getting loaded. There is no remote call being made to <code>myRemoteURL.do</code> to load the model body.</p>
<p>Code:</p>
<pre><code><button type="button" data-toggle="modal" data-remote="myRemoteURL.do" data-target="#myModel">Open Model</button>
<!-- Model -->
<div class="modal fade" id="myModel" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h3 class="modal-title" id="myModalLabel">Model Title</h3>
</div>
<div class="modal-body">
<p>
<img alt="loading" src="resources/img/ajax-loader.gif">
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</div>
</code></pre> | 34,763,263 | 6 | 0 | null | 2016-01-13 09:40:16.7 UTC | 11 | 2020-12-16 00:02:52.593 UTC | 2018-02-22 18:13:10.58 UTC | null | 171,456 | null | 2,032,823 | null | 1 | 40 | jquery|css|twitter-bootstrap|bootstrap-4 | 60,156 | <p>Found the problem: <a href="https://getbootstrap.com/docs/3.4/javascript/#modals-options" rel="noreferrer">They have removed the remote option in bootstrap 4</a></p>
<blockquote>
<p><strong>remote</strong> : This option is deprecated since v3.3.0 and will be removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.</p>
</blockquote>
<p>I used JQuery to implement this removed feature.</p>
<pre><code>$('body').on('click', '[data-toggle="modal"]', function(){
$($(this).data("target")+' .modal-body').load($(this).data("remote"));
});
</code></pre> |
54,892,546 | Unit Testing Jest in Reactjs Component state | <p>Hello :) I'm starting to learn <strong>Unit Testing</strong> using <strong>JEST & Enzyme</strong></p>
<p>on my version (already done) of "Color Guessing Game" using with <strong>Reactjs</strong>,
but when I started to test my Square Component I can't even test my color state value and my color state when clicked (clickSquare function)...</p>
<p>and I can't find much resources about it, can you see what's wrong, and how can I test my Square Component?</p>
<p><strong>Square.js Component:</strong></p>
<pre><code>import React, { Component } from 'react';
class Square extends Component {
constructor(props) {
super(props);
this.state = {
color: undefined
}
this.clickSquare = this.clickSquare.bind(this);
}
componentDidMount() {
if (this.props.color) {
this.setState({
color: this.props.color
})
}
};
componentWillReceiveProps(props) {
//results in the parent component to send updated props,,
//whenever the propositions are updated in the parent, runs this
//to update the son as well
this.setState({
color: props.color
})
}
clickSquare() {
if (this.state.color === this.props.correctColor) {
this.props.gameWon(true);
console.log('correct', this.state.color)
} else {
this.setState({
color: 'transparent'
})
// this.props.gameWon(false);
console.log('wrong')
}
};
render() {
return (
<div className='square square__elem'
style={{ backgroundColor: this.state.color }}
onClick={this.clickSquare}>
</div>
);
}
};
export default Square;
</code></pre>
<p><strong>Square.test.js Testing:</strong></p>
<pre><code>import React from 'react';
import Square from '../components/Square/Square';
import { shallow, mount } from 'enzyme';
describe('Square component', () => {
let wrapper;
beforeEach(() => wrapper = shallow(
<Square
color={undefined}
clickSquare={jest.fn()}
/>
));
it('should render correctly', () => expect(wrapper).toMatchSnapshot());
it('should render a <div />', () => {
expect(wrapper.find('div.square.square__elem').length).toEqual(1);
});
it('should render the value of color', () => {
wrapper.setProps({ color: undefined});
expect(wrapper.state()).toEqual('transparent');
});
});
</code></pre>
<blockquote>
<p>Expected value to equal:
"transparent"
Received:
{"color": undefined}</p>
<pre><code>Difference:
Comparing two different types of values. Expected string but received object.
</code></pre>
</blockquote> | 54,892,856 | 1 | 0 | null | 2019-02-26 19:15:16.95 UTC | 1 | 2022-07-30 07:31:24.037 UTC | 2019-02-26 21:59:13.247 UTC | null | 2,071,697 | null | 10,327,790 | null | 1 | 9 | reactjs|unit-testing|jestjs|enzyme | 44,538 | <p>Well, you're not so far from the solution. :)</p>
<p>The only issue is that between the parentheses in the expression <code>wrapper.state()</code>, you don't pass any argument - that's why you receive the whole object instead of a single value. That being said, you should do the following in this case:</p>
<pre><code>it('should render the value of color', () => {
wrapper.setProps({ color: undefined});
expect(wrapper.state('color')).toEqual('transparent');
});
</code></pre>
<p>Notice the usage of <code>wrapper.state('color')</code>.</p>
<hr>
<p><strong>EDIT</strong></p>
<p>Based on your comment below, I didn't realize that the <code>transparent</code> value is set via a click event.</p>
<p>Here is the full test suite that should be verified by Jest:</p>
<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import Square from '../components/Square/Square';
describe('<Square />', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Square color={undefined} />); // Here it's not necessary to mock the clickSquare function.
});
it('should render the value of color', () => {
wrapper.setProps({ color: undefined });
wrapper.find('div').simulate('click'); // Simulating a click event.
expect(wrapper.state('color')).toEqual('transparent');
});
});
</code></pre> |
67,185,817 | Package.resolved file is corrupted or malformed | <p>I have a build error saying that all my SPM packages are missing. I decided to remove and re-add each package to the project, but each attempt at adding a package gives me the following error:</p>
<blockquote>
<p>Package.resolved file is corrupted or malformed; fix or delete the file to continue</p>
</blockquote>
<p>I've tried deleting the <code>Package.resolved</code> file and letting it regenerate (it didn't), but I get the same error message. Any ideas on how to fix this?</p>
<p><a href="https://i.stack.imgur.com/8AuNG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8AuNG.png" alt="enter image description here" /></a></p> | 69,389,411 | 9 | 0 | null | 2021-04-20 20:20:01.587 UTC | 11 | 2022-08-20 13:56:19.413 UTC | 2022-07-12 18:16:41.597 UTC | null | 1,265,393 | null | 1,102,687 | null | 1 | 65 | xcode|swift-package-manager | 31,692 | <p>I tried the solution suggested by Maxwell above but it didn't resolve the problem for me.</p>
<p>The error appeared with Xcode 12 but upgrading to Xcode 13 didn't fix it either.</p>
<p>Instead, I decided to take Xcode at its word and delete the Package.resolved file. But where is it? I did this:</p>
<ol>
<li><p>In Finder, tap Shift+Cmd+. to reveal hidden files and folders.</p>
</li>
<li><p>The Package.resolved file is inside your .xcodeproj directory at [appName].xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved</p>
</li>
<li><p>Right click on .xcodeproj and project.xcworkspace to show package contents.</p>
</li>
<li><p>Move the Package.resolved file to the bin, and then empty the bin.</p>
</li>
<li><p>Reopen Xcode and open your project again. This gave me another error:
the package at '/' cannot be accessed (Couldn’t read '4.5.0':</p>
</li>
<li><p>In Xcode, File / Packages / Reset package caches.
The Swift Package Manager starts working on this.</p>
</li>
<li><p>Rebuild the project. The error had gone and my project rebuilt successfully.</p>
</li>
</ol>
<p>Good luck!</p> |
39,390,160 | pandas.factorize on an entire data frame | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="noreferrer"><code>pandas.factorize</code></a> encodes input values as an enumerated type or categorical variable. </p>
<p>But how can I easily and efficiently convert many columns of a data frame? What about the reverse mapping step?</p>
<p>Example: This data frame contains columns with string values such as "type 2" which I would like to convert to numerical values - and possibly translate them back later.</p>
<p><a href="https://i.stack.imgur.com/MLATh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MLATh.png" alt="enter image description here"></a></p> | 39,390,208 | 3 | 0 | null | 2016-09-08 11:50:52.33 UTC | 25 | 2018-02-26 11:26:41.483 UTC | null | null | null | null | 626,537 | null | 1 | 24 | python|pandas|dataframe|machine-learning | 28,617 | <p>You can use <code>apply</code> if you need to <code>factorize</code> each column separately:</p>
<pre><code>df = pd.DataFrame({'A':['type1','type2','type2'],
'B':['type1','type2','type3'],
'C':['type1','type3','type3']})
print (df)
A B C
0 type1 type1 type1
1 type2 type2 type3
2 type2 type3 type3
print (df.apply(lambda x: pd.factorize(x)[0]))
A B C
0 0 0 0
1 1 1 1
2 1 2 1
</code></pre>
<p>If you need for the same string value the same numeric one:</p>
<pre><code>print (df.stack().rank(method='dense').unstack())
A B C
0 1.0 1.0 1.0
1 2.0 2.0 3.0
2 2.0 3.0 3.0
</code></pre>
<hr>
<p>If you need to apply the function only for some columns, use a subset:</p>
<pre><code>df[['B','C']] = df[['B','C']].stack().rank(method='dense').unstack()
print (df)
A B C
0 type1 1.0 1.0
1 type2 2.0 3.0
2 type2 3.0 3.0
</code></pre>
<p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.factorize.html" rel="noreferrer"><code>factorize</code></a>:</p>
<pre><code>stacked = df[['B','C']].stack()
df[['B','C']] = pd.Series(stacked.factorize()[0], index=stacked.index).unstack()
print (df)
A B C
0 type1 0 0
1 type2 1 2
2 type2 2 2
</code></pre>
<p>Translate them back is possible via <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="noreferrer"><code>map</code></a> by <code>dict</code>, where you need to remove duplicates by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.drop_duplicates.html" rel="noreferrer"><code>drop_duplicates</code></a>:</p>
<pre><code>vals = df.stack().drop_duplicates().values
b = [x for x in df.stack().drop_duplicates().rank(method='dense')]
d1 = dict(zip(b, vals))
print (d1)
{1.0: 'type1', 2.0: 'type2', 3.0: 'type3'}
df1 = df.stack().rank(method='dense').unstack()
print (df1)
A B C
0 1.0 1.0 1.0
1 2.0 2.0 3.0
2 2.0 3.0 3.0
print (df1.stack().map(d1).unstack())
A B C
0 type1 type1 type1
1 type2 type2 type3
2 type2 type3 type3
</code></pre> |
3,216,440 | Probabilistic Generation of Semantic Networks | <p>I've studied some simple semantic network implementations and basic techniques for parsing natural language. However, I haven't seen many projects that try and bridge the gap between the two.</p>
<p>For example, consider the dialog:</p>
<pre><code>"the man has a hat"
"he has a coat"
"what does he have?" => "a hat and coat"
</code></pre>
<p>A simple semantic network, based on the grammar tree parsing of the above sentences, might look like:</p>
<pre><code>the_man = Entity('the man')
has = Entity('has')
a_hat = Entity('a hat')
a_coat = Entity('a coat')
Relation(the_man, has, a_hat)
Relation(the_man, has, a_coat)
print the_man.relations(has) => ['a hat', 'a coat']
</code></pre>
<p>However, this implementation assumes the prior knowledge that the text segments "the man" and "he" refer to the same network entity.</p>
<p>How would you design a system that "learns" these relationships between segments of a semantic network? I'm used to thinking about ML/NL problems based on creating a simple training set of attribute/value pairs, and feeding it to a classification or regression algorithm, but I'm having trouble formulating this problem that way.</p>
<p>Ultimately, it seems I would need to overlay probabilities on top of the semantic network, but that would drastically complicate an implementation. Is there any prior art along these lines? I've looked at a few libaries, like NLTK and OpenNLP, and while they have decent tools to handle symbolic logic and parse natural language, neither seems to have any kind of proabablilstic framework for converting one to the other.</p> | 3,218,352 | 3 | 0 | null | 2010-07-09 20:47:16.163 UTC | 10 | 2010-07-10 08:24:55.823 UTC | null | null | null | null | 247,542 | null | 1 | 10 | machine-learning|data-mining|nlp | 745 | <p>There is quite a lot of history behind this kind of task. Your best start is probably by looking at <a href="http://en.wikipedia.org/wiki/Question_answering" rel="nofollow noreferrer">Question Answering</a>. </p>
<p>The general advice I always give is that if you have some highly restricted domain where you know about all the things that might be mentioned and all the ways they interact then you can probably be quite successful. If this is more of an 'open-world' problem then it will be extremely difficult to come up with something that works acceptably.</p>
<p>The task of extracting relationship from natural language is called 'relationship extraction' (funnily enough) and sometimes fact extraction. This is a pretty large field of research, <a href="http://ace.cs.ohiou.edu/~razvan/papers/thesis-white.pdf" rel="nofollow noreferrer">this guy</a> did a PhD thesis on it, as have many others. There are a large number of challenges here, as you've noticed, like entity detection, anaphora resolution, etc. This means that there will probably be a lot of 'noise' in the entities and relationships you extract.</p>
<p>As for representing facts that have been extracted in a knowledge base, most people tend not to use a probabilistic framework. At the simplest level, entities and relationships are stored as triples in a flat table. Another approach is to use an ontology to add structure and allow reasoning over the facts. This makes the knowledge base vastly more useful, but adds a lot of scalability issues. As for adding probabilities, I know of the <a href="http://www.pr-owl.org/" rel="nofollow noreferrer">Prowl</a> project that is aimed at creating a probabilistic ontology, but it doesn't look very mature to me.</p>
<p>There is some research into probabilistic relational modelling, mostly into <a href="http://en.wikipedia.org/wiki/Markov_logic_network" rel="nofollow noreferrer">Markov Logic Networks</a> at the University of Washington and <a href="http://dags.stanford.edu/PRMs/" rel="nofollow noreferrer">Probabilstic Relational Models</a> at Stanford and other places. I'm a little out of touch with the field, but this is is a difficult problem and it's all early-stage research as far as I know. There are a lot of issues, mostly around efficient and scalable inference.</p>
<p>All in all, it's a good idea and a very sensible thing to want to do. However, it's also very difficult to achieve. If you want to look at a slick example of the state of the art, (i.e. what is possible with a bunch of people and money) maybe check out <a href="http://www.powerset.com/" rel="nofollow noreferrer">PowerSet</a>.</p> |
3,119,280 | Assistance need to get Spring MVC project going with IntelliJ IDEA | <p>So I downloaded a trial of idea ultimate, and I want to get spring mvc going with tomcat.</p>
<p>So I setup a new project, configured it to use sun jdk.</p>
<p>I chose a spring application, and it created and downloaded the following:</p>
<p><a href="https://i.stack.imgur.com/Vfk3D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vfk3D.png" alt="http://img15.imageshack.us/img15/4853/idealspring1.png"></a>
</p>
<p>I don't see any spring-mvc libraries, are they included in there or do I have to do something about that?</p>
<p>Can someone outline what I have to do to get this to build like a spring mvc web application?</p> | 3,120,301 | 3 | 0 | null | 2010-06-25 15:29:06.793 UTC | 11 | 2019-07-31 07:58:21.85 UTC | 2019-07-31 07:58:21.85 UTC | null | 4,751,173 | null | 39,677 | null | 1 | 12 | java|spring|spring-mvc|intellij-idea | 17,467 | <p>I find that the best way to start a new IDEA project is to use the Maven. This allows you to easily build your project without launching the IDE, automatically maintaining all libraries for you.</p>
<p>"Create project from scratch", then select "Maven module" in the next screen. Click on "Create from archetype" and select the "maven-archetype-webapp". This will give you a basic Maven layout which builds a simple WAR file.</p>
<p>Now to add the Spring libraries, open the Maven build file - pom.xml - and insert a new dependency on the Spring MVC framework:</p>
<pre><code> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
</code></pre>
<p>From here, you can follow the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html" rel="nofollow noreferrer">Spring MVC reference documentation</a> - add the Dispatcher Servlet and Context Listener to web.xml, a Spring XML context and so on.</p>
<p>Something else you might find useful is the <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin" rel="nofollow noreferrer">Maven Jetty plugin</a>. Once configured, you can run your app by simply typing "mvn jetty:run" at the command prompt (or launching it from within the IDE). Maven will fetch all that's required and deploy the app for you, no need for an external app server setup for quick testing.</p> |
2,686,320 | How to put a newline into a column header in an xtable in R | <p>I have a dataframe that I am putting into a <a href="http://www.stat.uni-muenchen.de/~leisch/Sweave/" rel="noreferrer">sweave</a> document using xtable, however one of my column names is quite long, and I would like to break it over two lines to save space</p>
<pre><code>calqc_table<-structure(list(RUNID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), ANALYTEINDEX = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), ID = structure(1:11, .Label = c("Cal A", "Cal B", "Cal C",
"Cal D", "Cal E", "Cal F", "Cal G", "Cal H", "Cal High", "Cal Low",
"Cal Mid"), class = "factor"), mean_conc = c(200.619459644855,
158.264703128903, 102.469121407733, 50.3551544728544, 9.88296440865076,
4.41727762501703, 2.53494715706024, 1.00602831741361, 199.065054555735,
2.48063347296935, 50.1499780776199), sd_conc = c(2.3275711264554,
NA, NA, NA, NA, NA, NA, 0.101636943231162, 0, 0, 0), nrow = c(3,
1, 1, 1, 1, 1, 1, 3, 2, 2, 2)), .Names = c("Identifier of the Run within the Study", "ANALYTEINDEX",
"ID", "mean_conc", "sd_conc", "nrow"), row.names = c(NA, -11L
), class = "data.frame")
calqc_xtable<-xtable(calqc_table)
</code></pre>
<p>I have tried putting a newline into the name, but this didn't seem to work</p>
<pre><code>names(calqc_table)[1]<-"Identifier of the \nRun within the Study"
</code></pre>
<p>Is there a way to do this ? I have seen someone suggest using the latex function from the <a href="http://cran.r-project.org/web/packages/Hmisc/index.html" rel="noreferrer">hmisc</a> package to manually iterate over the table and write it out in latex manually, including the newline, but this seems like a bit of a faf !</p> | 2,687,142 | 3 | 2 | null | 2010-04-21 20:28:58.367 UTC | 11 | 2022-08-10 13:35:15.493 UTC | 2010-04-23 15:35:16.14 UTC | null | 135,870 | null | 74,658 | null | 1 | 19 | r|latex|tex|sweave|xtable | 7,822 | <p>The best way I have found to do this is to indicate the table column as a "fixed width" column so that the text inside it wraps. With the <code>xtable</code> package, this can be done with:</p>
<pre><code>align( calqc_xtable ) <- c( 'l', 'p{1.5in}', rep('c',5) )
</code></pre>
<p><code>xtable</code> demands that you provide an alignment for the option "rownames" column- this is the initial <code>l</code> specification. The section specification, <code>p{1.5in}</code>, is used for your first column header, which is quite long. This limits it to a box 1.5 inches in width and the header will wrap onto multiple lines if necessary. The remaining five columns are set centered using the <code>c</code> specifier.</p>
<p>One major problem with fixed width columns like <code>p{1.5in}</code> is that <strong>they set the text using a justified alignment</strong>. This causes the inter-word spacing in each line to be expanded such that the line will fill up the entire 1.5 inches allotted.</p>
<p>Frankly, in most cases this produces results which I cannot describe using polite language (I'm an amateur typography nut and this sort of behavior causes facial ticks).</p>
<p>The fix is to provide a latex alignment command by prepending a <code>>{}</code> field to the column specification:</p>
<pre><code>align( calqc_xtable ) <- c( 'l', '>{\\centering}p{1.5in}', rep('c',4) )
</code></pre>
<p>Other useful alignment commands are:</p>
<ul>
<li>\raggedright -> causes text to be <strong>left aligned</strong></li>
<li>\raggedleft -> causes text to be <strong>right aligned</strong></li>
</ul>
<p>Remember to double backslashes to escape them in R strings. You may also need to disable the string sanitation function that <code>xtable</code> uses by default.</p>
<p><strong>Note</strong></p>
<p>This alignment technique <strong>will fail</strong> if used on the last column of a table <strong>unless</strong> table rows are ended with <code>\tabularnewline</code> instead of <code>\\</code>, which I think is not the case with <code>xtable</code> and is not easily customizable through any user-settable option.</p>
<p>The other thing to consider is that you may not want the entire column line-wrapped to 1.5 inches and centered- just the header. In that case, disable <code>xtable</code> string sanitization and set your header using a <code>\multicolumn</code> cell of width 1:</p>
<pre><code>names(calqc_table)[1]<-"\\multicolumn{1}{>{\\centering}p{1.5in}}{Identifier of the Run within the Study}"
</code></pre> |
2,484,806 | Accessing Textboxes in Repeater Control | <p>All the ways I can think to do this seem very hackish. What is the right way to do this, or at least most common?</p>
<p>I am retrieving a set of images from a LINQ-to-SQL query and databinding it and some other data to a repeater. I need to add a textbox to each item in the repeater that will let the user change the title of each image, very similar to Flickr.</p>
<p><strong>How do I access the textboxes in the repeater control and know which image that textbox belongs to?</strong></p>
<p>Here is what the repeater control would look like, with a submit button which would update all the image rows in Linq-to-SQL:</p>
<p><a href="http://casonclagg.com/layout.jpg">alt text http://casonclagg.com/layout.jpg</a></p>
<p><strong>Edit:</strong></p>
<p><strong>This code works</strong></p>
<p>Just make sure you don't blow your values away by Binding outside of if(!Page.IsPostBack) like me.. Oops.</p>
<pre><code><asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="itemBox">
<div class="imgclass">
<a title='<%# Eval("Name") %>' href='<%# Eval("Path") %>' rel="gallery">
<img alt='<%# Eval("Name") %>' src='<%# Eval("Path") %>' width="260" />
</a>
</div>
<asp:TextBox ID="TextBox1" Width="230px" runat="server"></asp:TextBox>
</div>
</ItemTemplate>
</asp:Repeater>
</code></pre>
<p>And Submit Click:</p>
<pre><code>protected void Button1_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
TextBox txtName = (TextBox)item.FindControl("TextBox1");
if (txtName != null)
{
string val = txtName.Text;
//do something with val
}
}
}
</code></pre> | 2,484,837 | 3 | 1 | null | 2010-03-20 21:16:18.377 UTC | 6 | 2012-12-13 23:19:08.957 UTC | 2010-03-20 22:57:34.487 UTC | null | 452,047 | null | 452,047 | null | 1 | 25 | c#|asp.net|textbox|repeater | 47,000 | <p>Have you tried something like following on the button click:-</p>
<pre><code>foreach (RepeaterItem item in Repeater1.Items)
{
TextBox txtName= (TextBox)item.FindControl("txtName");
if(txtName!=null)
{
//do something with txtName.Text
}
Image img= (Image)item.FindControl("Img");
if(img!=null)
{
//do something with img
}
}
</code></pre>
<p>/* Where txtName and Img are the Ids of the textbox and the image controls respectively in the repeater.*/</p>
<p>Hope this helps.</p> |
2,647,786 | Landscape Mode ONLY for iPhone or iPad | <p>I want to create an application that doesn't use Portrait mode.</p>
<p>I am not sure if I need to edit the plist or have code in addition to the plist</p> | 2,647,807 | 4 | 0 | null | 2010-04-15 17:59:54.643 UTC | 14 | 2015-12-03 08:20:49.067 UTC | 2010-04-15 19:48:12.52 UTC | null | 30,461 | null | 317,785 | null | 1 | 37 | iphone|objective-c|cocoa-touch|uikit|ipad | 38,850 | <p><a href="http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationEnvironment/ApplicationEnvironment.html" rel="noreferrer">Code found here</a></p>
<blockquote>
<p>Launching in Landscape Mode</p>
<p>Applications in iPhone OS normally
launch in portrait mode to match the
orientation of the Home screen. If you
have an application that runs in both
portrait and landscape modes, your
application should always launch in
portrait mode initially and then let
its view controllers rotate the
interface as needed based on the
device’s orientation. If your
application runs in landscape mode
only, however, you must perform the
following steps to make it launch in a
landscape orientation initially.</p>
<ul>
<li><p>In your application’s Info.plist file, add the <code>UIInterfaceOrientation</code><br>
key and set its value to the<br>
landscape mode. For landscape<br>
orientations, you can set the value<br>
of this key to<br>
<code>UIInterfaceOrientationLandscapeLeft</code><br>
or<br>
<code>UIInterfaceOrientationLandscapeRight.</code></p></li>
<li><p>Lay out your views in landscape mode and make sure that their
autoresizing options are set
correctly.</p></li>
<li><p>Override your view controller’s <code>shouldAutorotateToInterfaceOrientation:</code>
method and return YES only for the<br>
desired landscape orientation and NO<br>
for portrait orientations.</p></li>
</ul>
</blockquote> |
2,527,845 | How to do calendar operations in Java GWT? How to add days to a Date? | <p>Since GWT does not provide the GregorianCalendar class, how to do calendar operations on the client?</p>
<p>I have a Date <code>a</code> and I want the Date, which is <code>n</code> days after <code>a</code>.</p>
<p>Examples:</p>
<pre><code>a (2000-01-01) + n (1) -> 2000-01-02
a (2000-01-01) + n (31) -> 2000-02-01
</code></pre> | 5,384,777 | 4 | 0 | null | 2010-03-27 01:55:16.073 UTC | 7 | 2012-06-25 14:26:31.893 UTC | null | null | null | null | 176,336 | null | 1 | 49 | java|gwt | 38,643 | <p>Updated answer for GWT 2.1</p>
<pre><code>final Date dueDate = new Date();
CalendarUtil.addDaysToDate(dueDate, 21);
</code></pre>
<p>Edit: the fully qualified name of this class is <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/user/datepicker/client/CalendarUtil.html" rel="noreferrer">com.google.gwt.user.datepicker.client.CalendarUtil</a>.</p> |
2,597,098 | Get the last N rows in the database in order? | <p>Let's say I have the following database table:</p>
<pre><code> record_id | record_date | record_value
-----------+-------------+--------------
1 | 2010-05-01 | 195.00
2 | 2010-07-01 | 185.00
3 | 2010-09-01 | 175.00
4 | 2010-05-01 | 189.00
5 | 2010-06-01 | 185.00
6 | 2010-07-01 | 180.00
7 | 2010-08-01 | 175.00
8 | 2010-09-01 | 170.00
9 | 2010-10-01 | 165.00
</code></pre>
<p>I want to grab the last 5 rows with the data ordered by record_date ASC. This is easy to do with: </p>
<pre><code>SELECT * FROM mytable ORDER BY record_date ASC LIMIT 5 OFFSET 4
</code></pre>
<p>Which would give me: </p>
<pre><code> record_id | record_date | record_value
-----------+-------------+--------------
6 | 2010-07-01 | 180.00
7 | 2010-08-01 | 175.00
3 | 2010-09-01 | 175.00
8 | 2010-09-01 | 170.00
9 | 2010-10-01 | 165.00
</code></pre>
<p>But how do I do this when I don't know how many records there are and can't compute the magic number of 4? </p>
<p>I've tried this query, but if there are less than 5 records, it results in a negative OFFSET, which is invalid:</p>
<pre><code>SELECT * FROM mytable ORDER BY record_date ASC LIMIT 5
OFFSET (SELECT COUNT(*) FROM mytable) - 5;
</code></pre>
<p>So how do I accomplish this?</p> | 2,597,100 | 4 | 0 | null | 2010-04-08 02:04:02.293 UTC | 8 | 2022-07-11 07:01:37.313 UTC | null | null | null | null | 1,497,409 | null | 1 | 69 | postgresql | 100,919 | <p>Why don't you just order the opposite way?</p>
<pre><code>SELECT *
FROM mytable
ORDER BY record_date
DESC LIMIT 5;
</code></pre>
<p>If you don't want to flip back correctly in the application, you can nest a query and flip them twice:</p>
<pre><code>SELECT *
FROM (SELECT *
FROM mytable
ORDER BY record_date
DESC LIMIT 5)
ORDER BY record_date ASC;
</code></pre>
<p>... which turns out to be a pretty cheap operation.</p> |
36,546,860 | Require nodejs "child_process" with TypeScript, SystemJS and Electron | <p>I'm working on a simple nodejs <a href="http://electron.atom.io/" rel="noreferrer">electron</a> (formerly known as atom shell) project.
I'm writing it using angular 2, using the project the same project setup as they recommend in the documentation for typescript:</p>
<p>tsc:</p>
<pre><code>{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
</code></pre>
<p>I need to run a command, I found out that I can do it with node "child_process".
I couldn't find anyway for me to "import" or "require" it while having its type used from the node.d.ts file. I have found the "child_process" interface in the node.d.ts file which suits my need,
this is how it looking in the node.d.ts file:</p>
<pre><code> declare module "child_process" {
import * as events from "events";
import * as stream from "stream";
export interface ChildProcess extends events.EventEmitter {
stdin: stream.Writable;
stdout: stream.Readable;
stderr: stream.Readable;
pid: number;
kill(signal?: string): void;
send(message: any, sendHandle?: any): void;
disconnect(): void;
unref(): void;
}
export function spawn(command: string, args?: string[], options?: {
cwd?: string;
stdio?: any;
custom?: any;
env?: any;
detached?: boolean;
}): ChildProcess;
export function exec(command: string, options: {
cwd?: string;
stdio?: any;
customFds?: any;
env?: any;
encoding?: string;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
}, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function execFile(file: string,
callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function execFile(file: string, args?: string[],
callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function execFile(file: string, args?: string[], options?: {
cwd?: string;
stdio?: any;
customFds?: any;
env?: any;
encoding?: string;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
}, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function fork(modulePath: string, args?: string[], options?: {
cwd?: string;
env?: any;
execPath?: string;
execArgv?: string[];
silent?: boolean;
uid?: number;
gid?: number;
}): ChildProcess;
export function spawnSync(command: string, args?: string[], options?: {
cwd?: string;
input?: string | Buffer;
stdio?: any;
env?: any;
uid?: number;
gid?: number;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
encoding?: string;
}): {
pid: number;
output: string[];
stdout: string | Buffer;
stderr: string | Buffer;
status: number;
signal: string;
error: Error;
};
export function execSync(command: string, options?: {
cwd?: string;
input?: string|Buffer;
stdio?: any;
env?: any;
uid?: number;
gid?: number;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
encoding?: string;
}): string | Buffer;
export function execFileSync(command: string, args?: string[], options?: {
cwd?: string;
input?: string|Buffer;
stdio?: any;
env?: any;
uid?: number;
gid?: number;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
encoding?: string;
}): string | Buffer;
}
</code></pre>
<p>but I can only (as I know of) get this type only by using import:</p>
<pre><code>import * as child_process from 'child_process';
</code></pre>
<p>Only problem is that when I do this, my app cant load and I get the following error in the console:</p>
<pre><code>GET file:///C:/angular2Samples/NGW-electron-VS%20-%20TEMP/child_process net::ERR_FILE_NOT_FOUND
</code></pre>
<p>For now, im getting my way around by using:</p>
<pre><code>var child_process = require('child_process');
</code></pre>
<p>but I couldn't find anyway to add the type information to this var:</p>
<pre><code>var child_process : I_CANT_PUT_ANY_CHILD_PROCESS_TYPE_HERE = require('child_process');
</code></pre>
<p>Any ideas on how I can get the child_process (or any other declared node modules that arent public interface that I can state after ":" operator) with type information?</p>
<p>Thanks alot in advance for any help and explanations :)</p>
<p>UPDATE ------------------------------------------------------------------</p>
<p>As tenbits suggested I have added the reference as follows to the top of the file:
/// </p>
<p>and used the import statment you said, but didnt chage my module loader. it still didnt work with the same error as expected.
Im not feeling very comfortable about changing the module system, as my project uses angular 2 and their docs and some of their guides said that new projects that has no former prefernce to this matter (I am very new to the module loaders scene and im not fully understanding how it works yet).
When I tried to change it I got some errors regarding angular 2 stuffs which I dont have enough time to get into at the moment. Shouldn't there be a way to this without changing the module loader? by glancing at the systemjs site it says at the start that it supports commonjs modules:
<a href="https://github.com/systemjs/systemjs/blob/master/docs/module-formats.md" rel="noreferrer">Systemjs doc</a></p>
<p>I would really appriciate a solution that doesn't change the module system, or maybe a more depth explanition about what's going on and which approaches to these kind of module loading problems exists out there</p> | 36,549,645 | 3 | 0 | null | 2016-04-11 11:02:22.253 UTC | 2 | 2020-10-04 15:56:57.47 UTC | 2016-04-14 09:56:55.82 UTC | null | 2,436,109 | null | 1,245,668 | null | 1 | 22 | node.js|typescript|require|electron|systemjs | 38,814 | <p><em>Ok, after some research <a href="https://github.com/systemjs/systemjs/blob/8703bf0f93c20a6e6a7ad976a5a49a0c4cedc2ec/lib/core.js#L138" rel="noreferrer">#L138</a> I have found the solution</em></p>
<p>You can use <code>import</code> as before</p>
<pre><code>import * as child from 'child_process';
var foo: child.ChildProcess = child.exec('foo.sh');
console.log(typeof foo.on);
</code></pre>
<p>But you should configure <code>SystemJS</code> to map the module to <code>NodeJS</code>.</p>
<pre><code>System.config({
map: {
'child_process': '@node/child_process'
}
});
</code></pre>
<p><em>That's it!</em></p> |
51,197,940 | 'File name differs from already included file name only in casing' on relative path with same casing | <blockquote>
<p>Error TS1149: File name 'C:/Project/frontend/scripts/State.ts' differs from already included file name '../frontend/scripts/State.ts' only in casing.</p>
</blockquote>
<p>I've triple checked the casing in our references and the actual files have the correct casing as well. As far as I can tell, this is solely because the relative path uses incorrect casing, or perhaps it's just because of the relative path itself?</p>
<p>The thing is, it compiles just fine on Mac and Linux, but throws this error on Windows.</p>
<p>If it helps, <code>forceConsistentCasingInFileNames</code> is enabled in the tsconfig, and we're using tsify to compile.</p> | 51,213,274 | 19 | 1 | null | 2018-07-05 18:40:09.15 UTC | 9 | 2022-08-11 02:53:48.78 UTC | null | null | null | null | 1,982,313 | null | 1 | 130 | javascript|windows|typescript|compiler-errors | 100,402 | <p>The answer was that we were using tisfy 1.0.1, when <code>forceConsistentCasingInFileNames</code> wasn't supported until 4.0.0. Updating fixed the issue.</p> |
1,249,205 | How to get the request context in a freemaker template in spring | <p>How to get the request context path in <code>freemarker</code> template when using with <code>spring</code>?</p>
<p>My view resolver is like this</p>
<pre><code> <bean id="freeMarkerViewResolver" class="learn.common.web.view.FreemarkerViewResolver">
<property name="order" value="1" />
<property name="viewClass"
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
<property name="suffix" value=".ftl" />
<property name="cache" value="false" />
</bean>
</code></pre>
<p>My view resolver <code>learn.common.web.view.FreemarkerViewResolver</code> extends <code>org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver</code></p> | 1,249,213 | 2 | 0 | null | 2009-08-08 15:57:46.027 UTC | 4 | 2018-02-28 07:12:21.27 UTC | 2018-02-28 07:12:21.27 UTC | null | 184,792 | null | 114,251 | null | 1 | 29 | spring|spring-mvc|freemarker | 19,320 | <p>In your view resolver you can add the following property</p>
<pre><code><property name="requestContextAttribute" value="rc"/>
</code></pre>
<p>Then in your freemarker template you can get the request context patch like </p>
<pre><code>${rc.getContextPath()}
</code></pre> |
986,183 | Mocking The RouteData Class in System.Web.Routing for MVC applications | <p>I'm trying to test some application logic that is dependent on the Values property in ControllerContext.RouteData. </p>
<p>So far I have</p>
<pre><code>// Arrange
var httpContextMock = new Mock<HttpContextBase>(MockBehavior.Loose);
var controllerMock = new Mock<ControllerBase>(MockBehavior.Loose);
var routeDataMock = new Mock<RouteData>();
var wantedRouteValues = new Dictionary<string, string>();
wantedRouteValues.Add("key1", "value1");
var routeValues = new RouteValueDictionary(wantedRouteValues);
routeDataMock.SetupGet(r => r.Values).Returns(routeValues); <=== Fails here
var controllerContext = new ControllerContext(httpContextMock.Object, routeDataMock.Object, controllerMock.Object);
</code></pre>
<p>The unit test fails with:
System.ArgumentException: Invalid setup on a non-overridable member:
r => r.Values</p>
<p>Creating a fake RouteData doesn't work either as the constructor is RouteData(RouteBase,IRouteHandler).</p>
<p>The important class here is the abstract class RouteBase which has the method GetRouteData(HttpContextBase) which returns an instance of RouteData, the class I'm trying to fake. Taking me around in circles!</p>
<p>Any help on this would be most welcome.</p> | 986,276 | 2 | 0 | null | 2009-06-12 11:30:03.133 UTC | 8 | 2009-06-12 12:23:03.117 UTC | null | null | null | null | 5,170 | null | 1 | 35 | c#|asp.net-mvc|moq | 16,933 | <p>RouteData also has a <a href="http://msdn.microsoft.com/en-us/library/cc680271.aspx" rel="noreferrer">constructor that takes no arguments</a>. Simply create one and add the values to it that you want. No need to mock it when you can create one.</p>
<pre><code> var routeData = new RouteData();
routeData.Values.Add( "key1", "value1" );
var controllerContext = new ControllerContext(httpContextMock.Object, routeData, controllerMock.Object);
</code></pre> |
2,902,640 | Android: Get the screen resolution / pixels as integer values | <p>this is a really simple question on which I've found no answer :/
How can I quickly access the screen resolution (width, height) as integer values?</p>
<p>I've tried this one, but it always shows zero on my emulator:</p>
<pre><code>DisplayMetrics dm = new DisplayMetrics();
int width = dm.widthPixels / 2;
</code></pre>
<p>In my case I want to dynamically create a table with tableRows, each containing two cols. This cols all shall fill half of the screen in width.</p>
<p>Can someone give me a hint?</p> | 2,902,701 | 5 | 2 | null | 2010-05-25 07:03:26.09 UTC | 9 | 2015-10-29 07:14:01.023 UTC | null | null | null | null | 317,301 | null | 1 | 11 | android|resolution | 54,497 | <p>The easiest way will be to implement <a href="http://developer.android.com/reference/android/view/View.html#onSizeChanged%28int,%20int,%20int,%20int%29" rel="nofollow noreferrer">onSizeChanged</a>. You are probably getting a value of 0 because the view hasn't initialized yet. You can't call the above code in the View constructor for example.</p> |
2,517,245 | Why, really, deleting an incomplete type is undefined behaviour? | <p>Consider this classic example used to explain what <em>not</em> to do with forward declarations:</p>
<pre><code>//in Handle.h file
class Body;
class Handle
{
public:
Handle();
~Handle() {delete impl_;}
//....
private:
Body *impl_;
};
//---------------------------------------
//in Handle.cpp file
#include "Handle.h"
class Body
{
//Non-trivial destructor here
public:
~Body () {//Do a lot of things...}
};
Handle::Handle () : impl_(new Body) {}
//---------------------------------------
//in Handle_user.cpp client code:
#include "Handle.h"
//... in some function...
{
Handle handleObj;
//Do smtg with handleObj...
//handleObj now reaches end-of-life, and BUM: Undefined behaviour
}
</code></pre>
<p>I understand from the standard that this case is headed towards UB since Body's destructor is non trivial.
What I'm trying to understand is really the root cause of this.</p>
<p>I mean, the problem seems to be "triggered" by the fact that Handle's dtor is inline, and so the compiler does something like the following "inline expansion" (almost pseudo-code here).</p>
<pre><code>inline Handle::~Handle()
{
impl_->~Body();
operator delete (impl_);
}
</code></pre>
<p>In all translation units (only <code>Handle_user.cpp</code> in this case) where a Handle instance gets to be destroyed, right?
I just can't understand this: ok, when generating the above inline expansion the compiler doesn't have a full definition of the Body class, but why cannot it simply have the linker resolve for the <code>impl_->~Body()</code> thing and so have it call the Body's destructor function that's actually defined in its implementation file?</p>
<p>In other words: I understand that at the point of Handle destruction the compiler doesn't even know if a (non-trivial) destructor exists or not for Body, but why can't it do as it always does, that is leave a "placeholder" for the linker to fill in, and eventually have a linker "unresolved external" if that function is really not available?</p>
<p>Am I missing something big here (and in that case sorry for the stupid question)?
If that's not the case, I'm just curious to understand the rationale behind this.</p> | 2,517,455 | 6 | 0 | null | 2010-03-25 16:13:49.49 UTC | 8 | 2014-08-12 09:22:15.57 UTC | 2014-08-12 09:22:15.57 UTC | null | 2,246,344 | null | 41,789 | null | 1 | 29 | c++|memory-management|destructor|forward-declaration|delete-operator | 10,832 | <p>To combine several answers and add my own, without a class definition the calling code doesn't know:</p>
<ul>
<li>whether the class has a declared destructor, or if the default destructor is to be used, and if so whether the default destructor is trivial,</li>
<li>whether the destructor is accessible to the calling code,</li>
<li>what base classes exist and have destructors,</li>
<li>whether the destructor is virtual. Virtual function calls in effect use a different calling convention from non-virtual ones. The compiler can't just "emit the code to call ~Body", and leave the linker to work out the details later,</li>
<li>(this just in, thanks GMan) whether <code>delete</code> is overloaded for the class.</li>
</ul>
<p>You can't call any member function on an incomplete type for some or all of those reasons (plus another that doesn't apply to destructors - you wouldn't know the parameters or return type). A destructor is no different. So I'm not sure what you mean when you say "why can't it do as it always does?".</p>
<p>As you already know, the solution is to define the destructor of <code>Handle</code> in the TU which has the definition of <code>Body</code>, same place as you define every other member function of <code>Handle</code> which calls functions or uses data members of <code>Body</code>. Then at the point where <code>delete impl_;</code> is compiled, all the information is available to emit the code for that call.</p>
<p>Note that the standard actually says, 5.3.5/5: </p>
<blockquote>
<p>if the object being deleted has
incomplete class type at the point of
deletion and the complete class has a
non-trivial destructor or a
deallocation function, the behavior is
undefined.</p>
</blockquote>
<p>I presume this is so that you can delete an incomplete POD type, same as you could <code>free</code> it in C. g++ gives you a pretty stern warning if you try it, though.</p> |
3,115,537 | Java compilation errors limited to 100 | <p>I have a Java file,which when I compiled, I will be able to see only first 100 errors on console after that java compiler(javac) exits. How will I be able to see all the compilation errors on console?
Thanks in advance- opensid </p> | 3,115,546 | 8 | 6 | null | 2010-06-25 04:27:33.86 UTC | 8 | 2017-05-30 22:37:27.407 UTC | 2010-06-25 13:53:29.087 UTC | null | 21,234 | null | 327,765 | null | 1 | 39 | java|javac | 15,015 | <p>Generally the compiler will give up after 100 errors. Most of the errors after this point will likely be caused by one of the first errors. If you must have more errors check out the javac options <code>-Xmaxerrs</code> and <code>-Xmaxwarns</code></p> |
2,648,074 | How to convert "0" and "1" to false and true | <p>I have a method which is connecting to a database via Odbc. The stored procedure which I'm
calling has a return value which from the database side is a 'Char'. Right now I'm grabbing
that return value as a string and using it in a simple if statement. I really don't like the idea
of comparing a string like this when only two values can come back from the database, 0 and 1.</p>
<pre><code>OdbcCommand fetchCommand = new OdbcCommand(storedProc, conn);
fetchCommand.CommandType = CommandType.StoredProcedure;
fetchCommand.Parameters.AddWithValue("@column ", myCustomParameter);
fetchCommand.Parameters.Add("@myReturnValue", OdbcType.Char, 1)
.Direction = ParameterDirection.Output;
fetchCommand.ExecuteNonQuery();
string returnValue = fetchCommand.Parameters["@myReturnValue"].Value.ToString();
if (returnValue == "1")
{
return true;
}
</code></pre>
<p>What would be the proper way to handle this situation. I've tried 'Convert.ToBoolean()' which seemed
like the obvious answer but I ran into the 'String was not recognized as a valid Boolean. ' exception being thrown. Am I missing something
here, or is there another way to make '1' and '0' act like true and false?</p>
<p>Thanks!</p> | 2,648,080 | 9 | 0 | null | 2010-04-15 18:44:17.873 UTC | 6 | 2019-01-07 17:21:05.93 UTC | 2014-06-10 20:56:11.97 UTC | null | 121,363 | null | 121,363 | null | 1 | 99 | c#|.net|asp.net|odbc|boolean-logic | 219,204 | <p>How about:</p>
<pre><code>return (returnValue == "1");
</code></pre>
<p>or as suggested below:</p>
<pre><code>return (returnValue != "0");
</code></pre>
<p>The correct one will depend on what you are looking for as a success result. </p> |
3,034,054 | When to use Spring Integration vs. Camel? | <p>As a seasoned Spring user I was assuming that Spring Integration would make the most sense in a recent project requiring some (JMS) messaging capabilities (<a href="https://stackoverflow.com/questions/3012802/how-to-leverage-spring-integration-in-a-real-world-jms-distributed-architecture">more details</a>). After some days working with Spring Integration it still feels like a lot of configuration overhead given the amount of channels you have to configure to bring some request-response (listening on different JMS queues) communications in place. </p>
<p>Therefore I was looking for some background information how Camel is different from Spring Integration, but it seems like information out there are pretty spare, I found:</p>
<ul>
<li><a href="http://java.dzone.com/articles/spring-integration-and-apache" rel="noreferrer">http://java.dzone.com/articles/spring-integration-and-apache</a> (Very neutral comparison between implementing a real-world integration scenario in Spring Integration vs. Camel, from December 2009)</li>
<li><a href="http://hillert.blogspot.com/2009/10/apache-camel-alternatives.html" rel="noreferrer">http://hillert.blogspot.com/2009/10/apache-camel-alternatives.html</a> (Comparing Camel with other solutions, October 2009)</li>
<li><a href="http://raibledesigns.com/rd/entry/taking_apache_camel_for_a" rel="noreferrer">http://raibledesigns.com/rd/entry/taking_apache_camel_for_a</a> (Matt Raible, October 2008)</li>
</ul>
<p>Question is: what experiences did you make on using the one stack over the other? In which scenarios would you recommend Camel were Spring Integration lacks support? Where do you see pros and cons of each? Any advise from real-world projects are highly appreciated.</p> | 3,034,150 | 11 | 1 | null | 2010-06-13 21:45:42.783 UTC | 64 | 2020-06-12 09:40:14.703 UTC | 2017-05-23 10:31:34.033 UTC | null | -1 | null | 267,001 | null | 1 | 163 | java|jms|messaging|apache-camel|spring-integration | 94,961 | <p>We choose Camel over Spring-Integration because the fluent API is really nice. We actually use it in Spring projects and use Spring to configure part of it. The programming API's are clear and there is a large set of sensible components. </p>
<p>We did a small scale shootout and basically at that time for our requirement Camel won. We use it mainly to transfer internal datafiles to/from external parties which usually requires format conversions sending it using ftp/sftp/... or attaching it to an email and sending it out.</p>
<p>We found the edit-compile-debug cycle reduced. Using groovy to experiment setting up routes are added bonuses.</p>
<p>Spring-Integration is a great product too, and I am quite sure it would satisfy our needs too. </p> |
3,043,978 | How to check if a process id (PID) exists | <p>In a bash script, I want to do the following (in pseudo-code):</p>
<pre><code>if [ a process exists with $PID ]; then
kill $PID
fi
</code></pre>
<p>What's the appropriate expression for the conditional statement?</p> | 3,044,045 | 11 | 2 | null | 2010-06-15 09:30:26.743 UTC | 62 | 2022-07-04 17:35:48.383 UTC | 2018-04-21 03:52:38.12 UTC | null | 6,862,601 | null | 183,579 | null | 1 | 233 | bash|process|pid | 350,897 | <p>To check for the existence of a process, use</p>
<pre><code>kill -0 $pid
</code></pre>
<p>But just as <a href="https://stackoverflow.com/a/3043991/4575793">@unwind said</a>, if you want it to terminate in any case, then just</p>
<pre><code>kill $pid
</code></pre>
<p>Otherwise you will have a race condition, where the process might have disappeared after the first <code>kill -0</code>.</p>
<p>If you want to ignore the text output of <code>kill</code> and do something based on the exit code, you can</p>
<pre><code>if ! kill $pid > /dev/null 2>&1; then
echo "Could not send SIGTERM to process $pid" >&2
fi
</code></pre> |
3,068,843 | Permission to view, but not to change! - Django | <p>is it possible to give users the permission to view, but not to change or delete.</p>
<p>currently in the only permissions I see are "add", "change" and "delete"... but there is no "read/view" in there.</p>
<p>I really need this as some users will only be able to consult the admin panel, in order to see what has been added in.</p> | 5,364,408 | 12 | 2 | null | 2010-06-18 10:30:39.027 UTC | 12 | 2021-03-25 15:53:15.997 UTC | 2016-05-11 22:30:26.6 UTC | null | 895,245 | null | 208,827 | null | 1 | 27 | python|django|django-admin | 26,326 | <p><strong>Update</strong>: Since Django 2.1 <a href="https://docs.djangoproject.com/en/2.1/releases/2.1/#model-view-permission" rel="nofollow noreferrer">this is now built-in</a>.</p>
<p>In admin.py</p>
<pre><code># Main reusable Admin class for only viewing
class ViewAdmin(admin.ModelAdmin):
"""
Custom made change_form template just for viewing purposes
You need to copy this from /django/contrib/admin/templates/admin/change_form.html
And then put that in your template folder that is specified in the
settings.TEMPLATE_DIR
"""
change_form_template = 'view_form.html'
# Remove the delete Admin Action for this Model
actions = None
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
def save_model(self, request, obj, form, change):
#Return nothing to make sure user can't update any data
pass
# Example usage:
class SomeAdmin(ViewAdmin):
# put your admin stuff here
# or use pass
</code></pre>
<p>In change_form.html replace this:</p>
<pre><code>{{ adminform.form.non_field_errors }}
</code></pre>
<p>with this:</p>
<pre><code><table>
{% for field in adminform.form %}
<tr>
<td>{{ field.label_tag }}:</td><td>{{ field.value }}</td>
</tr>
{% endfor %}
</table>
</code></pre>
<p>Then remove the submit button by deleting this row:</p>
<pre><code>{% submit_row %}
</code></pre> |
23,727,255 | Multiple checkMark when row selected in UITableView IOS | <p>I have a <code>UITableView</code> that displays checkmarks when a row is selected. The problem is that When i select a row in <code>didSelectRowAtIndexPath</code> and add a checkmark on the selected row it adds an additional checkmark. Here's my code </p>
<p>Any help would be very much appreciated.</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text=[[Model.category objectAtIndex:indexPath.row] categoryName];
cell.imageView.image=[[Model.category objectAtIndex:indexPath.row]categoryImage];
//cell.detailTextLabel.text =@"Breve Descripción de la categoria";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if ([self.tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark) {
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType =UITableViewCellAccessoryNone;
[self.cellSelected removeObject:indexPath];
}else {
[tableView cellForRowAtIndexPath:indexPath].accessoryType=UITableViewCellAccessoryCheckmark;
[self.cellSelected addObject:indexPath];
}
[self checkMark];
[tableView reloadData];
}
- (void)checkMark{
for (NSIndexPath * indexPath in self.cellSelected) {
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType=UITableViewCellAccessoryCheckmark;
}
}
</code></pre> | 23,727,615 | 2 | 0 | null | 2014-05-18 21:53:59.767 UTC | 11 | 2015-08-10 09:22:17.133 UTC | 2014-05-18 22:15:55.39 UTC | null | 235,700 | null | 3,476,711 | null | 1 | 15 | ios|objective-c|uitableview|didselectrowatindexpath | 24,317 | <p><code>[self.tableView cellForRowAtIndexPath:indexPath]</code> call in the <code>didSelectRowAtIndexPath</code> will not return the exact cell. It can be same cell, new cell or reused cell. If it is a reused cell at its accessory view has a checkmark, you will end up having two cells with checkmark.</p>
<p>Its better to store in the array and use it accordingly. If you are planning to have multiple selections, Use the code example below.</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.cellSelected = [NSMutableArray array];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Cell Initialisation here
if ([self.cellSelected containsObject:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//if you want only one cell to be selected use a local NSIndexPath property instead of array. and use the code below
//self.selectedIndexPath = indexPath;
//the below code will allow multiple selection
if ([self.cellSelected containsObject:indexPath])
{
[self.cellSelected removeObject:indexPath];
}
else
{
[self.cellSelected addObject:indexPath];
}
[tableView reloadData];
}
</code></pre> |
45,696,685 | Search input with an icon Bootstrap | <p>No clue how I can do this, since BS 4 doesn't support glyphicons. Do I set it up as a background or do I apply different positioning to a font-awesome icon? </p>
<p>This is my code so far:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<div class="form-group col-md-4">
<input class="form-control rounded-0 py-2" type="search" value="search" id="example-search-input">
</div>
<!-- /.form-group --></code></pre>
</div>
</div>
</p>
<p>I want to use this <a href="http://fontawesome.io/icon/search/" rel="noreferrer">font-awesome icon</a>. And I've tried adding it as a <code>background-image</code> too, as in:</p>
<pre><code>.form-control {
background-image: url('https://res.cloudinary.com/dt9b7pad3/image/upload/v1502810110/angle-down-dark_dkyopo.png');
background-position: right center 5px;
}
</code></pre>
<p>But that doesn't do anything. The only way I can think of is to add font-awesome icon and then set the positioning to absolute, right? But I'm not sure if that's the 'clean' and correct way to do it? Do I need to take a different approach to this? Someone help! Thank you!</p> | 45,696,757 | 6 | 0 | null | 2017-08-15 15:57:42.497 UTC | 25 | 2021-05-21 14:54:46.243 UTC | 2021-04-30 11:45:53.5 UTC | null | 171,456 | null | 6,753,772 | null | 1 | 54 | css|twitter-bootstrap|bootstrap-4|font-awesome | 200,939 | <p><strong>Bootstrap 5 Beta - (update 2021)</strong></p>
<pre><code> <div class="input-group">
<input class="form-control border-end-0 border rounded-pill" type="text" value="search" id="example-search-input">
<span class="input-group-append">
<button class="btn btn-outline-secondary bg-white border-start-0 border rounded-pill ms-n3" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</code></pre>
<p><a href="https://codeply.com/p/jYwDonANZl" rel="noreferrer">Demo</a></p>
<p><strong>Bootstrap 4 (original answer)</strong></p>
<p>Why not use an <strong>input-group</strong>?</p>
<pre><code><div class="input-group col-md-4">
<input class="form-control py-2" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<button class="btn btn-outline-secondary" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</code></pre>
<p><strong>And</strong>, you can make it appear <em>inside</em> the input using the border utils...</p>
<pre><code> <div class="input-group col-md-4">
<input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<button class="btn btn-outline-secondary border-left-0 border" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</code></pre>
<p><strong>Or</strong>, using a <code>input-group-text</code> w/o the gray background so the icon appears inside the input...</p>
<pre><code> <div class="input-group">
<input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div>
</span>
</div>
</code></pre>
<p><strong>Alternately</strong>, you can use the grid (<code>row</code>><code>col-</code>) with no gutter spacing:</p>
<pre><code><div class="row no-gutters">
<div class="col">
<input class="form-control border-secondary border-right-0 rounded-0" type="search" value="search" id="example-search-input4">
</div>
<div class="col-auto">
<button class="btn btn-outline-secondary border-left-0 rounded-0 rounded-right" type="button">
<i class="fa fa-search"></i>
</button>
</div>
</div>
</code></pre>
<p><strong>Or, prepend</strong> the icon like this...</p>
<pre><code><div class="input-group">
<span class="input-group-prepend">
<div class="input-group-text bg-transparent border-right-0">
<i class="fa fa-search"></i>
</div>
</span>
<input class="form-control py-2 border-left-0 border" type="search" value="..." id="example-search-input" />
<span class="input-group-append">
<button class="btn btn-outline-secondary border-left-0 border" type="button">
Search
</button>
</span>
</div>
</code></pre>
<p><a href="https://www.codeply.com/go/ioPsDfyCBc" rel="noreferrer">Demo of all Bootstrap 4 <strong>icon input options</strong></a></p>
<hr />
<p><a href="https://i.stack.imgur.com/rxtxd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rxtxd.png" alt="enter image description here" /></a></p>
<hr>
<p><a href="https://www.codeply.com/go/w7E80lxnMD" rel="noreferrer">Example with validation icons</a></p> |
10,375,858 | How to "slice" an std_logic_vector in VHDL? | <p>I'm developing a little thing in VHDL and am quite new to it. I'm having trouble figuring out how to slice a bigger std_logic_vector into a smaller one. </p>
<p>For instance I have 3 signals:</p>
<pre><code>signal allparts: std_logic_vector(15 downto 0);
signal firstpart: std_logic_vector(7 downto 0);
signal secondpart: std_logic_vector(7 downto 0);
</code></pre>
<p>Basically, what I want is to assign bits 15 through 8 to <code>secondpart</code> and bits 7 through 0 to <code>firstpart</code>. How exactly would I "slice" a vector like this without assigning individual bits</p> | 10,376,420 | 1 | 0 | null | 2012-04-29 20:48:12.33 UTC | 3 | 2012-04-29 22:05:56.54 UTC | null | null | null | null | 69,742 | null | 1 | 24 | syntax|vhdl | 54,829 | <p>You can directly assign them:</p>
<pre><code>firstpart <= allparts(15 downto 8);
secondpart <= allparts(7 downto 0);
</code></pre>
<p>...or if firstpart and secondpart are simply alternate ways to refer to part of the allparts signal, you may want to use an alias:</p>
<pre><code>alias firstpart is allparts(15 downto 8);
alias secondpart is allparts(7 downto 0);
</code></pre> |
10,501,358 | Objective C - getting line number or full stack trace from debugger error? | <p>Is it possible to get a line number for the source code (or anything that helps debug where the problem is) from the debugger, that shows where the problem is originating?</p>
<p>I am getting an error:</p>
<pre><code>-[NSCFArray objectAtIndex:]: index (-1 (or possibly larger)) beyond bounds (9)
</code></pre>
<p>which obviously means that I am going out of bounds at some point, however if it possible I would like to get some more information to help me solve the problem.</p>
<p>I am placing a breakpoint and trying to go through the program line by line but it is a tedious process. Thanks!</p> | 10,501,532 | 2 | 0 | null | 2012-05-08 15:09:16.277 UTC | 20 | 2014-08-28 14:20:43.027 UTC | 2013-04-11 10:40:07.297 UTC | null | 49,658 | null | 1,214,040 | null | 1 | 25 | objective-c|xcode|cocoa | 20,965 | <p>When the debugger stops, go to the "Debug Navigator" and make sure the slider on the bottom is all the way to the right.</p>
<p>Scan your eye down from the point at which the exception is thrown and you should eventually come to your own code. Click on the appropriate method/function name and the code will be opened in the editor.</p>
<p><img src="https://i.stack.imgur.com/zSqKv.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/gSXn5.png" alt="enter image description here"></p>
<p>If you don't see any of your own methods in the stack trace, the exception may have been passed through a <code>performSelector</code>-style call in which case the stack trace is gone. If this is the case, you may get better information by adding an "On Throw" exception break point. First switch to the "Breakpoint navigator":</p>
<p><img src="https://i.stack.imgur.com/L7328.png" alt="enter image description here"></p>
<p>Then click on the plus and choose "Add Exception breakpoint..."</p>
<p><img src="https://i.stack.imgur.com/KeWGR.png" alt="enter image description here"></p>
<p>Create an "On Throw" break point:</p>
<p><img src="https://i.stack.imgur.com/677CI.png" alt="enter image description here"></p>
<p>This will stop the debugger at the exact point the exception is thrown, and you get a better stack trace. It's a good idea to have an exception break point like this enabled all the time, although you will occasionally get internal exceptions from Apple code (e.g. when using QLPreviewController, MPMoviePlayerController).</p> |
23,047,978 | How is arctan implemented? | <p>Many implementation of the library goes deep down to FPATAN instuction for all arc-functions. How is FPATAN implemented? Assuming that we have 1 bit sign, M bits mantissa and N bits exponent, what is the algorithm to get the arctangent of this number? There should be such algorithm, since the FPU does it.</p> | 23,048,159 | 3 | 0 | null | 2014-04-13 20:20:52.587 UTC | 8 | 2022-09-10 23:27:35.22 UTC | 2019-10-12 06:33:24.867 UTC | null | 527,702 | null | 1,058,670 | null | 1 | 19 | algorithm|floating-point|trigonometry|bit|processor | 19,569 | <p>Trigonometric functions do have pretty ugly implementations that are hacky and do lots of bit fiddling. I think it will be pretty hard to find someone here that is able to explain an algorithm that is actually used.</p>
<p>Here is an atan2 implementation: <a href="https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/dbl-64/e_atan2.c;h=a287ca6656b210c77367eec3c46d72f18476d61d;hb=HEAD" rel="noreferrer">https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/dbl-64/e_atan2.c;h=a287ca6656b210c77367eec3c46d72f18476d61d;hb=HEAD</a></p>
<p>Edit: Actually I found this one: <a href="http://www.netlib.org/fdlibm/e_atan2.c" rel="noreferrer">http://www.netlib.org/fdlibm/e_atan2.c</a> which is a lot easier to follow, but probably slower because of that (?).</p>
<p>The FPU does all this in some circuits so the CPU doesn't have to do all this work.</p> |
41,053,280 | How to write mock for structs in Go | <p>I want to write a unit test for the <code>Transport</code> function which will require mocking <code>CarFactory</code> and <code>Car</code> structs. See the following code:</p>
<pre><code>package main
type Car struct {
Name string
}
func (h Car) Run() { ... }
type CarFactory struct {}
func (e CarFactory) MakeCar() Car {
return Car{}
}
func Transport(cf CarFactory) {
...
car := cf.MakeCar()
car.Run()
...
}
</code></pre>
<p>In other OOP languages like Java, C# or C++, I can just define <code>CarFactoryMock</code> and <code>CarMock</code> that extend <code>CarFactory</code> and <code>Car</code> then override <code>MakeCar()</code> method to return a <code>CarMock</code> object</p>
<pre><code>class CarMock extends Car {
public Run() {...}
}
class CarFactoryMock extends CarFactory {
public Car MakeCar() { return new CarMock(); }
}
Transport(new CarFactoryMock())
</code></pre>
<p>How do I achieve this in Go?</p>
<p><strong>Note that I can change prototype and source code of <code>Transport</code> function, but must keep <code>CarFactory</code> and <code>Car</code> the same since they are taken from a 3rd package</strong></p>
<hr>
<p>The last code snippet was about Human and Employee, which lead to confusion`.</p> | 41,054,865 | 2 | 0 | null | 2016-12-09 04:45:55.897 UTC | 7 | 2020-09-17 19:42:37.407 UTC | 2020-01-04 16:28:35.083 UTC | null | 1,013,701 | null | 2,646,539 | null | 1 | 28 | unit-testing|go|mocking | 37,364 | <p>It takes more code to mock a struct in Go than other OOP languages that support full late binding.</p>
<p>This code must remain untouched since its taken from a 3rd party:</p>
<pre><code>type Car struct {
Name string
}
func (c Car) Run() {
fmt.Println("Real car " + c.Name + " is running")
}
type CarFactory struct {}
func (cf CarFactory) MakeCar(name string) Car {
return Car{name}
}
</code></pre>
<p>Since Go only supports late binding on interface, I had to make <code>Transport</code> receive an interface as a parameter instead of a struct:</p>
<pre><code>type ICar interface {
Run()
}
type ICarFactory interface {
MakeCar(name string) ICar
}
func Transport(cf ICarFactory) {
...
car := cf.MakeCar("lamborghini")
car.Run()
...
}
</code></pre>
<p>And here are the mocks:</p>
<pre><code>type CarMock struct {
Name string
}
func (cm CarMock) Run() {
fmt.Println("Mocking car " + cm.Name + " is running")
}
type CarFactoryMock struct {}
func (cf CarFactoryMock) MakeCar(name string) ICar {
return CarMock{name}
}
</code></pre>
<p>Now I can easily use the mock <code>Transport(CarFactoryMock{})</code>. But when I try to call the real method <code>Transport(CarFactory{})</code>, the go compiler shows me the following errors:</p>
<pre><code>cannot use CarFactory literal (type CarFactory) as type ICarFactory in argument to Transport:
CarFactory does not implement ICarFactory (wrong type for MakeCar method)
have MakeCar(string) Car
want MakeCar(string) ICar
</code></pre>
<p>As the message says, <code>MakeCar</code> function from the interface returns an <code>ICar</code>, but the real <code>MakeCar</code> returns a <code>Car</code>. Go doesn't allow that. To walk around this problem I had to define a wrapper to manually convert <code>Car</code> to <code>ICar</code>.</p>
<pre><code>type CarFactoryWrapper struct {
CarFactory
}
func (cf CarFactoryWrapper) MakeCar(name string) ICar {
return cf.CarFactory.MakeCar(name)
}
</code></pre>
<p>Now you can call the <code>Transport</code> function like this: <code>Transport(CarFactoryWrapper{CarFactory{}})</code>.</p>
<p>Here is the working code <a href="https://play.golang.org/p/6YyeZP4tcC" rel="noreferrer">https://play.golang.org/p/6YyeZP4tcC</a>.</p> |
32,410,299 | How to copy file from a Vagrant machine to localhost | <p>I want to copy a local file from a Vagrant machine to my <code>localhost</code>, but I am getting an error message:</p>
<blockquote>
<p>ssh: connect to host <code>127.0.0.1</code> port <code>22</code>: Connection refused.</p>
</blockquote>
<pre><code>[user@localhost ceil]$ scp -p 2222 [email protected]:/home/vagrant/devstack/local.conf .
cp: cannot stat ‘2222’: No such file or directory
ssh: connect to host 127.0.0.1 port 22: Connection refused
</code></pre>
<p>I also tried using using <code>localhost</code> but still got the same error.</p> | 32,410,420 | 7 | 0 | null | 2015-09-05 06:43:52.577 UTC | 16 | 2020-08-06 20:14:50.147 UTC | 2020-01-14 14:32:18.313 UTC | null | 806,202 | null | 4,884,941 | null | 1 | 42 | linux|vagrant|scp | 41,913 | <p>You should read the manual page for <code>scp</code>. The correct syntax is:</p>
<pre><code>scp -P 2222 [email protected]:/home/vagrant/devstack/local.conf .
</code></pre>
<p>The uppercase <kbd>P</kbd> is for "port". Lowercase is used to preserve modification times.</p> |
34,410,707 | Enabling remote access to Keycloak | <p>I'm using the Keycloak authorization server in order to manage my application permissions. However, I've found out the standalone server can be accessed locally only.</p>
<p><code>http://localhost:8080/auth</code> works, but not it does <code>http://myhostname:8080/auth</code>. This issue doesn't permit accessing the server from the internal network.</p> | 34,410,749 | 4 | 0 | null | 2015-12-22 07:38:35.53 UTC | 10 | 2021-10-13 15:57:47.723 UTC | null | null | null | null | 1,199,132 | null | 1 | 43 | keycloak | 40,943 | <p>The standalone Keycloak server runs on the top of a JBoss Wildfly instance and this server doesn't allow accessing it externally by default, for security reasons (it should be only for the administration console, but seems to affect every url in case of Keycloak). It has to be booted with the <code>-b=0.0.0.0</code> option to enable it.</p>
<blockquote>
<p>However, if your Wildfly is running on a remote machine and you try to
access your administrative page through the network by it’s IP address
or hostname, let’s say, at <a href="http://54.94.240.170:8080/" rel="noreferrer">http://54.94.240.170:8080/</a>, you will
probably see a graceful This webpage is not available error, in
another words, Wildfly said “No, thanks, I’m not allowing requests
from another guys than the ones at my local machine”.</p>
</blockquote>
<p><strong>See also:</strong></p>
<ul>
<li><a href="http://bgasparotto.com/enable-wildfly-remote-access/" rel="noreferrer">Enable Wildfly remote access</a></li>
<li><a href="https://stackoverflow.com/questions/29150643/wildfly-remotely-access-administration-console-doesnt-work">Wildfly remotely access administration console doesnt work</a></li>
</ul> |
33,031,596 | PostgreSQL DELETE FROM (SELECT * FROM table FETCH FIRST 10 ROWS ONLY) | <p>How do I delete only a few rows in postgreSQL?
I want to fetch 10 rows to delete in a subquery.</p>
<p>My table</p>
<p><a href="https://i.stack.imgur.com/u1alL.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/u1alL.jpg" alt="enter image description here"></a></p> | 33,031,643 | 2 | 0 | null | 2015-10-09 06:45:01.143 UTC | 4 | 2015-10-09 07:20:41.43 UTC | 2015-10-09 07:20:41.43 UTC | null | 3,682,599 | null | 4,389,509 | null | 1 | 19 | postgresql|subquery|sql-delete | 48,793 | <p>You need to use a where condition as per your requirement like this:</p>
<pre><code>delete from mytable where id in(1,2,3,4,5,6,7,8,9,10)
</code></pre>
<p>or</p>
<pre><code>delete from mytable where id in(select id from mytable where someconditon)
</code></pre>
<p>or you can try like this if you want to delete top 10 using <a href="http://www.postgresql.org/docs/current/static/ddl-system-columns.html" rel="noreferrer">ctid</a>:</p>
<pre><code>DELETE FROM mytable
WHERE ctid IN (
SELECT ctid
FROM mytable
GROUP BY s.serialId, s.valuetimestamp
ORDER BY s.serialId
LIMIT 10
)
</code></pre>
<p>If you are looking to remove the duplicates from your table then try this:</p>
<pre><code>DELETE FROM mytable
WHERE ctid NOT IN
(SELECT MAX(s.ctid)
FROM table s
GROUP BY s.serialId, s.valuetimestamp);
</code></pre> |
32,795,712 | Clean Architecture: How to reflect the data layer's changes in the UI | <p>I'm trying to make a design based on the <a href="https://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html" rel="noreferrer">Uncle Bob's Clean Architecture</a> in Android. </p>
<p><strong>The problem:</strong></p>
<p>I'd like to solve is how to make the changes generated in one repository to be reflected in other parts of the app, like other repositories or Views.</p>
<p><strong>The example</strong></p>
<p>I've designed a VERY simplified example for this example. Please notice that boundary interfaces has been removed to keep the diagrams small.</p>
<p>Imagine an app that shows a list of videos (with title, thumnail and like count), clicking a video you can see the detail (there you can like/dislike the video).</p>
<p>Additionally the app has an statistics system that counts the number of videos the user liked or disliked.</p>
<p>The main classes for this app could be:</p>
<p><strong>For the Videos part/module:</strong>
<a href="https://i.stack.imgur.com/MPqTe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MPqTe.png" alt="enter image description here"></a></p>
<p><strong>For the Stats part/module:</strong>
<a href="https://i.stack.imgur.com/uuxOc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uuxOc.png" alt="enter image description here"></a></p>
<p><strong>The target</strong></p>
<p>Now imagine you check your stats, then navigate the list of videos, open the detail of one, and click the like button.</p>
<p>After the like is sent to the server, there are several elements of the apps that should be aware of the change:</p>
<ul>
<li>Of course the detail view, should be updated with the changes (this can be made through callbacks so no problem)</li>
<li>The list of videos should update the "likes" count for the given video</li>
<li>The <code>StatsRepository</code> may want to update/invalidate the caches after voting a new video</li>
<li>If the list of stats is visible (imagine a split screen) it should also show the updated stats (or at least receive the event for re-query the data)</li>
</ul>
<p><strong>The Question</strong></p>
<p>What are the common patterns to solve this kind of communication?
Please make your answer as complete as you can, specifying where the events are generated, how they get propagated though the app, etc.</p>
<p><strong>Note:</strong> Bounties will be given to complete answers</p> | 32,822,506 | 2 | 0 | null | 2015-09-26 09:37:31.137 UTC | 8 | 2019-01-22 13:56:08.45 UTC | 2019-01-22 13:56:08.45 UTC | null | 9,298,517 | null | 853,836 | null | 1 | 25 | java|android|architecture|coding-style | 3,814 | <h3>Publish / Subscribe</h3>
<p>Typically, for n:m communication (n senders may send a message to m receivers, while all senders and receivers do not know each other) you'll use a <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish/subscribe pattern</a>.
There are lots of libraries implementing such a communication style, for Java there is for example an <a href="https://github.com/google/guava/wiki/EventBusExplained">EventBus implementation in the Guava library</a>.
For in-app communication these libraries are typically called EventBus or EventManager and send/receive <em>events</em>.</p>
<h3>Domain Events</h3>
<p>Suppose you now created an event <code>VideoRatedEvent</code>, which signals that a user has either liked or disliked a video.
These type of events are referred to as <a href="http://martinfowler.com/eaaDev/DomainEvent.html">Domain Events</a>. The event class is a simple POJO and might look like this:</p>
<pre><code>class VideoRatedEvent {
/** The video that was rated */
public Video video;
/** The user that triggered this event */
public User user;
/** True if the user liked the video, false if the user disliked the video */
public boolean liked;
}
</code></pre>
<h3>Dispatch events</h3>
<p>Now each time your users like or dislike a video, you'll need to dispatch a <code>VideoRatedEvent</code>.
With Guava, you'll simply pass an instantiated event object to object to <code>EventBus.post(myVideoRatedEvent)</code>.
Ideally the events are generated in your domain objects and are dispatched within the persisting transaction (see <a href="https://lostechies.com/jimmybogard/2014/05/13/a-better-domain-events-pattern/">this blog post</a> for details).
That means that as your domain model state is persisted, the events are dispatched.</p>
<h3>Event Listeners</h3>
<p>In your application, all components affected by an event can now listen to the domain events.
In your particular example, the <code>VideoDetailView</code> or <code>StatsRepository</code> might be event listeners for the <code>VideoRatedEvent</code>.
Of course, you will need to register those to the Guava EventBus with <code>EventBus.register(Object)</code>.</p> |
20,921,862 | Android Studio, Gradle, OpenCV and NDK | <p>I am trying to test OpenCV Android, on Android Studio, I am confused about how to include the NDK.</p>
<p>What I want to do is run the samples which come with OpenCV. Of the 6 samples provided I managed to run 4 successfully. The exceptions were face-detection and native-activity. </p>
<p>I suspect the reason is I have not set up my NDK correctly.</p>
<p>Googling I found a bunch of discussions but do not really understand them. This is my first time I am trying to work with both the NDK and OpenCV, and my Gradle understanding is limited.</p>
<p>I set an environment variable in my .bash_profile</p>
<p>export ANDROID_NDK=pathTo/android-ndk-r9</p>
<p>I do not understand how to get this to studio.</p>
<p>I see reference to jniFolder but do not understand what these are and should I care right now.
<a href="https://stackoverflow.com/questions/20704812/android-studio-0-4-could-not-find-method-jnidir">Stackoverflow.com/questions/17767557</a></p>
<pre><code>tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
pkgTask.jniFolders = new HashSet<File>()
pkgTask.jniFolders.add(new File(projectDir, 'native-libs'))
</code></pre>
<p>}</p>
<p>What am I supposed to do with this paste at the end of my build.gradle file ?</p>
<p>In summation, my questions are.</p>
<ol>
<li>How do I get Android Studio to read the NDK variable ?</li>
<li>What exactly are the jniFolders ?</li>
<li>Is it enough just to paste at the end of my build.gradle file ?</li>
</ol>
<p><a href="https://groups.google.com/forum/#!topic/adt-dev/xj51eCWwhFw" rel="nofollow noreferrer">Google Group Discussions on Gradle and NDK</a></p>
<hr>
<p>For anyone coming across this this is how I resolved it apart from Xaviers anwser.
First I read OVERVIEW.html which comes with the NDK, in the docs directory.
I then compiled the .mk and .cpp files into an .so file. I did this inplace in the sample jni directory
This created the .so file in the libs folder which I copied to the destination as given by Xavier.</p> | 20,926,595 | 1 | 1 | null | 2014-01-04 13:52:36.803 UTC | 9 | 2014-01-05 19:36:42.983 UTC | 2017-05-23 12:17:38.603 UTC | null | -1 | null | 1,463,518 | null | 1 | 11 | android|opencv|android-ndk|gradle|android-studio | 8,895 | <p>If you have libraries that you build with the ndk and want to put them in a gradle-enabled android project (using version 0.7.+ of the plugin), you can just put them in</p>
<pre><code>src/main/jniLibs/<abi>/libfoo.so
</code></pre>
<p>for example:</p>
<pre><code>src/main/jniLibs/armeabi-v7a/libfoo.so
src/main/jniLibs/x86/libfoo.so
</code></pre>
<p>and they'll get packaged automatically.</p>
<p>If you want to keep them in the native-libs folder you can put the following in your gradle file:</p>
<pre><code>android {
sourceSets.main {
jniLibs.srcDirs = ['native-libs']
}
}
</code></pre>
<p>All this does really is tell gradle where the jniLibs folder for the main source set is (relative to the project root.)</p>
<p>The snippet you showed is doing something different. It's telling the package task to also include some native libraries. This was a hack that used to work in a previous version using undocumented API of the task that are no longer supported.</p> |
21,591,536 | Resize and crop image and keeping aspect ratio NodeJS & gm | <p>I've been trying to create some thumbnails using the <code>gm</code> package from NodeJS, but I'm out of lucky. I need to resize images bigger than 600x600 (could be any width/height, starting from the given one) but when I pass the size to gm, it creates an image that doesn't have the same size I requested. </p>
<p>For example, given this code, I assume that running <code>node app /path/to/image.png</code> I'll receive an image with size of 200x100, but instead I got, say, an image of 180x100 or 200x90...</p>
<pre><code>gm(fileLocation)
.thumb(200, 100, 'processed.' + process.argv[2].split('.').pop(), function() {
console.log("Done!");
});
</code></pre>
<p>I've also tried with the resize option. There's even an option to force the size, but the aspect ratio of the output goes horrible...</p>
<pre><code>gm('/path/to/image.jpg')
.resize(353, 257)
.write(writeStream, function (err) {
if (!err) console.log(' hooray! ');
});
</code></pre> | 21,591,725 | 5 | 0 | null | 2014-02-06 00:20:50.047 UTC | 13 | 2019-01-09 02:18:19.147 UTC | null | null | null | null | 3,277,539 | null | 1 | 29 | node.js|graphicsmagick | 39,305 | <p>Try with <code>imagemagick</code> package for NodeJS: <a href="https://github.com/yourdeveloper/node-imagemagick" rel="nofollow noreferrer">https://github.com/yourdeveloper/node-imagemagick</a></p>
<pre><code>im.crop({
srcPath: process.argv[2],
dstPath: 'cropped.' + process.argv[2].split('.').pop(),
width: 200,
height: 200,
quality: 1,
gravity: 'Center'
}, function(err, stdout, stderr){
if (err) throw err;
console.log('resized ' + process.argv[2].split('/').pop() + ' to fit within 200x200px');
});
</code></pre>
<hr>
<p><strong>Update:</strong> Please note that the <a href="https://github.com/yourdeveloper/node-imagemagick" rel="nofollow noreferrer">node-imagemagick</a> package hasn't been updated in quite a long time. Please consider <a href="https://stackoverflow.com/a/25083756/1012139">Freyday's answer</a> since it's most up-to-date.</p> |
46,933,722 | How to get a list of all Jenkins nodes assigned with label including master node? | <p>I'm creating a Jenkins pipeline job and I need to run a job on all nodes labelled with a certain label.</p>
<p>Therefore I'm trying to get a list of node names assigned with a certain label. (With a node I can get the labels with <code>getAssignedLabels()</code>)</p>
<p>The <code>nodes</code>-list in <code>jenkins.model.Jenkins.instance.nodes</code> seems not contain the master-node which I need to include in my search.</p>
<p>My current solution is to iterate over the <code>jenkins.model.Jenkins.instance.computers</code> and use the <code>getNode()</code>-method to get the node. This works, but in the javadoc of Jenkins I'm reading the this list might not be up-to-date.</p>
<p>In the long-run I will add (dynamically) cloud-nodes and I'm afraid that I won't be able to use <code>computers</code> then.</p>
<p>What is the right way to get the list of all current nodes?</p>
<p>This is what I'm doing right now:</p>
<pre><code>@NonCPS
def nodeNames(label) {
def nodes = []
jenkins.model.Jenkins.instance.computers.each { c ->
if (c.node.labelString.contains(label)) {
nodes.add(c.node.selfLabel.name)
}
}
return nodes
}
</code></pre> | 49,625,621 | 10 | 0 | null | 2017-10-25 13:26:49.593 UTC | 2 | 2022-05-10 10:03:39.957 UTC | 2022-01-28 10:15:35.48 UTC | null | 1,795,027 | null | 880,584 | null | 1 | 24 | jenkins|jenkins-pipeline|jenkins-groovy | 39,146 | <p>This is the way I'm doing it right now. I haven't found anything else:</p>
<pre><code>@NonCPS
def hostNames(label) {
def nodes = []
jenkins.model.Jenkins.get().computers.each { c ->
if (c.node.labelString.contains(label)) {
nodes.add(c.node.selfLabel.name)
}
}
return nodes
}
</code></pre>
<p><code>jenkins.model.Jenkins.get.computers</code> contains the master-node and all the slaves.</p> |
51,849,600 | antd - ant design table with pagination control supporting a widget to choose rows per page? | <p>Does the Ant Design Table controller take a Pagination component, instead of a plain object of properties. I need to add a switcher, to switch between rows per page.</p>
<p>Currently it is implemented in the Pagination component.</p> | 53,327,888 | 2 | 0 | null | 2018-08-14 20:51:22.937 UTC | 2 | 2020-09-21 16:12:23.863 UTC | 2019-12-12 19:57:22.253 UTC | null | 4,816,922 | null | 2,588,622 | null | 1 | 17 | javascript|reactjs|antd | 40,358 | <p>If what you need is only the ability to select the number of rows per page, then the following code should work for you:</p>
<pre><code><Table
dataSource={...}
pagination={{ defaultPageSize: 10, showSizeChanger: true, pageSizeOptions: ['10', '20', '30']}}
>
</code></pre>
<p>Basically wrapping the <a href="https://ant.design/components/pagination/#API" rel="noreferrer">Pagination props</a> into a pagination object, and pass it into your Table component.</p>
<p>If you need more customization you might want to consider turning the default Table pagination off and hook up your custom pagination component. Sample code:</p>
<p><a href="https://codesandbox.io/s/brave-pike-8yiwu?fontsize=14&hidenavigation=1&theme=dark" rel="noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit nervous-jennings-iw5l6" /></a></p> |
27,292,918 | Swift KVO - Observing enum properties | <p>I'm assembling a class which has several states, as defined by an enum, and a read-only property "state" which returns the instance's current state. I was hoping to use KVO techniques to observe changes in state but this doesn't seem possible:</p>
<p><code>dynamic var state:ItemState // Generates compile-time error: Property cannot be marked dynamic because its type cannot be represented in Objective-C</code> </p>
<p>I guess I could represent each state as an Int or String, etc. but is there a simple alternative workaround that would preserve the type safety that the enum would otherwise provide?</p>
<p>Vince.</p> | 27,293,599 | 2 | 1 | null | 2014-12-04 11:29:49.41 UTC | 8 | 2015-08-11 16:33:48.203 UTC | null | null | null | null | 2,215,831 | null | 1 | 8 | swift|enums|key-value-observing | 7,705 | <p>I came across the same problem a while ago.
In the end I used an enum for the state and added an additional 'raw' property which is set by a property observer on the main state property.</p>
<p>You can KVO the 'raw' property but then reference the real enum property when it changes.</p>
<p>It's obviously a bit of a hack but for me it was better than ditching the enum altogether and losing all the benefits.</p>
<p>eg.</p>
<pre><code>class Model : NSObject {
enum AnEnumType : String {
case STATE_A = "A"
case STATE_B = "B"
}
dynamic private(set) var enumTypeStateRaw : String?
var enumTypeState : AnEnumType? {
didSet {
enumTypeStateRaw = enumTypeState?.rawValue
}
}
}
</code></pre>
<p>ADDITIONAL:</p>
<p>If you are writing the classes that are doing the observing in Swift here's a handy utility class to take some of the pain away.
The benefits are:</p>
<ol>
<li>no need for your observer to subclass NSObject.</li>
<li>observation callback code as a closure rather than having to implement
observeValueForKeyPath:BlahBlah...</li>
<li>no need to make sure you removeObserver, it's taken care of for you.</li>
</ol>
<p>The utility class is called <code>KVOObserver</code> and an example usage is:</p>
<pre><code>class ExampleObserver {
let model : Model
private var modelStateKvoObserver : KVOObserver?
init(model : Model) {
self.model = model
modelStateKvoObserver = KVOObserver.observe(model, keyPath: "enumTypeStateRaw") { [unowned self] in
println("new state = \(self.model.enumTypeState)")
}
}
}
</code></pre>
<p>Note <code>[unowned self]</code> in the capture list to avoid reference cycle.</p>
<p>Here's <code>KVOObserver</code>...</p>
<pre><code>class KVOObserver: NSObject {
private let callback: ()->Void
private let observee: NSObject
private let keyPath: String
private init(observee: NSObject, keyPath : String, callback: ()->Void) {
self.callback = callback
self.observee = observee
self.keyPath = keyPath;
}
deinit {
println("KVOObserver deinit")
observee.removeObserver(self, forKeyPath: keyPath)
}
override func observeValueForKeyPath(keyPath: String,
ofObject object: AnyObject,
change: [NSObject : AnyObject],
context: UnsafeMutablePointer<()>) {
println("KVOObserver: observeValueForKey: \(keyPath), \(object)")
self.callback()
}
class func observe(object: NSObject, keyPath : String, callback: ()->Void) -> KVOObserver {
let kvoObserver = KVOObserver(observee: object, keyPath: keyPath, callback: callback)
object.addObserver(kvoObserver, forKeyPath: keyPath, options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, context: nil)
return kvoObserver
}
}
</code></pre> |
27,003,907 | How do I connect to the server socket using the ip address and port number? (client is running on a different machine than server) | <p>Client program</p>
<pre><code>public class client implements Runnable {
protected static String server_IP = "141.117.57.42";
private static final int server_Port = 5555 ;
protected static String client_IP ;
public static void main(String[] args) throws IOException{
final String host = "localhost";
int init = 0 ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
client_IP = iAddress.getHostAddress();
System.out.println("Current IP address : " +client_IP);
} catch (UnknownHostException e) {
}
try {System.out.println("hello1");
Socket socket = new Socket(server_IP,server_Port);
System.out.println("hello3");
init = initialize(socket);
}catch (SocketException e) {
System.out.println("Error: Unable to connect to server port ");
}
if (init == 0 ){
System.out.println("error: Failed to initialize ");
System.exit(0);
}
//Thread init_Thread = new Thread();
}
private static int initialize(Socket socket ) throws IOException{
System.out.println("hello");
int rt_value = 0 ;
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(os, true);
System.out.println("server: " + br.readLine());
pw.println("192.343.34.321");
// BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
//String userInput = userInputBR.readLine();
//out.println(userInput);
socket.close();
return rt_value = 1 ;
}
public void run(){
}
}
</code></pre>
<p>server side program</p>
<pre><code>public class server {
protected static String server_IP ;
public static void main(String[] args) throws IOException {
int server_Port = 5555 ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
server_IP = iAddress.getHostAddress();
System.out.println("Server IP address : " +server_IP);
} catch (UnknownHostException e) {
}
ServerSocket serverSocket = new ServerSocket(server_Port);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
pw.println("Connection confirmed ");
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
pw.println("your ip address is " + str);
pw.close();
//socket.close();
//System.out.println("Just said hello to:" + str);
}
</code></pre>
<p>How do I connect to the server socket using the ip address and port number (client is running on a different machine than server).</p>
<p>When I change the server_IP in client to "local host", it works perfectly.</p> | 27,004,094 | 2 | 2 | null | 2014-11-18 20:59:51.363 UTC | 3 | 2020-12-23 00:53:16.313 UTC | 2020-12-23 00:53:16.313 UTC | null | 1,783,163 | null | 4,250,127 | null | 1 | 3 | java|sockets|serversocket | 63,025 | <p>To connect in your code you use:</p>
<pre><code>Socket socket = new Socket(server_IP,server_Port);
</code></pre>
<p>So you could use:</p>
<pre><code>Socket socket = new Socket("192.168.1.4", 5555);
</code></pre>
<p>It looks like you have this in your code so I'm not sure what problem you're having.</p>
<p>Don't forget that you have to setup your router to forward ports if it is located outside of your local network.</p>
<p><a href="http://www.wikihow.com/Set-Up-Port-Forwarding-on-a-Router" rel="noreferrer">http://www.wikihow.com/Set-Up-Port-Forwarding-on-a-Router</a></p>
<p>Don't forget that if you are running a firewall, this can also interfere with the connection.</p> |
30,713,121 | Disable Swipe for position in RecyclerView using ItemTouchHelper.SimpleCallback | <p>I am using recyclerview 22.2.0 and the helper class ItemTouchHelper.SimpleCallback to enable <em>swipe-to-dismiss</em> option to my list. But as I have a type of header on it, I need to disable the swipe behavior for the first position of the adapter. As <strong>RecyclerView.Adapter</strong> doesn't have a <strong>isEnabled()</strong> method, I tried to disable the view interaction through the methods <strong>isEnabled()</strong> and <strong>isFocusable()</strong> in the ViewHolder creation itself, but had no success. I tried to adjust the swipe threshold to a full value, like <strong>0f</strong> ot <strong>1f</strong> in the SimpleCallback's method <strong>getSwipeThreshold()</strong>, but no success too.</p>
<p>Some fragments of my code to help you to help me.</p>
<p><strong>My Activity:</strong></p>
<pre><code>@Override
protected void onCreate(Bundle bundle) {
//... initialization
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
return false;
}
@Override
public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
if (viewHolder instanceof CartAdapter.MyViewHolder) return 1f;
return super.getSwipeThreshold(viewHolder);
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
</code></pre>
<p>And I have a common adapter with <em>two</em> view types. In the <em>ViewHolder</em> that I want to disable swiping, I did:</p>
<pre><code>public static class MyViewHolder extends RecyclerView.ViewHolder {
public ViewGroup mContainer;
public MyViewHolder(View v) {
super(v);
v.setFocusable(false);
v.setEnabled(false);
mContainer = (ViewGroup) v.findViewById(R.id.container);
}
}
</code></pre> | 30,713,364 | 7 | 0 | null | 2015-06-08 15:22:43.103 UTC | 24 | 2020-05-18 08:37:35.453 UTC | null | null | null | null | 1,267,425 | null | 1 | 113 | android|android-recyclerview | 49,357 | <p>After playing a bit, I managed that <strong>SimpleCallback</strong> has a method called <strong>getSwipeDirs()</strong>. As I have a specific ViewHolder for the <em>not swipable</em> position, I can make use of <strong>instanceof</strong> to avoid the swipe. If that's not your case, you can perform this control using the position of ViewHolder in the Adapter.</p>
<p><strong>Java</strong></p>
<pre><code>@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
if (viewHolder instanceof CartAdapter.MyViewHolder) return 0;
return super.getSwipeDirs(recyclerView, viewHolder);
}
</code></pre>
<p><strong>Kotlin</strong></p>
<pre><code>override fun getSwipeDirs (recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
if (viewHolder is CartAdapter.MyViewHolder) return 0
return super.getSwipeDirs(recyclerView, viewHolder)
}
</code></pre> |
308,258 | Vim Keyword Completion | <p>How do I tell the Vim editor about my include files path so that it can auto complete the function names when I press <kbd>CTRL</kbd>+<kbd>N</kbd>?</p>
<p>For example, I have a C program like below:</p>
<pre><code>#include<stdio.h>
int main()
{
sca // here I press control+N, it does not complete to scanf
}
</code></pre> | 308,274 | 3 | 0 | null | 2008-11-21 09:28:49.33 UTC | 12 | 2017-05-01 06:50:03.043 UTC | 2017-05-01 06:50:03.043 UTC | Rob Wells | 530,168 | chappar | 39,615 | null | 1 | 12 | c|vim | 5,325 | <p>In your <code>.vimrc</code>, add the paths to your <code>.vimrc</code>:</p>
<pre><code>set path+=/usr/include/**
set path+=/my_include_dir/include
set path+=/my_include_dir/srclib/apr/**
set path+=/my_other_include_dir/srclib/apr-util/**
** means all sub-directories.
* means all contained directories
. means all files in the directory of the found file
+= means prepend to existing path (iirc)
</code></pre>
<p>You can check the paths as well by opening your file and then entering</p>
<pre><code>:checkpath
</code></pre>
<p>This will give you a list of all included files that are missing. N.B. It doesn't seem to handle preprocessor directives, so you will get some false positives. Entering</p>
<pre><code>:checkpath!
</code></pre>
<p>Will give a complete list of found and missing include files.</p> |
359,331 | Access x86 COM from x64 .NET | <p>I have an x64 server which, since my libraries are compiled to AnyCPU, run under x64. We are needing to access a COM component which is registered under x86. I don't know enough about COM and my google searches are leading me nowhere.</p>
<p>Question: Can I use a symbolic registry link from x64 back to x86 for the COM component? Do I need to register the COM component under x64 as well? Can I (any statement here...) ?</p>
<p>Thanks.</p> | 359,389 | 3 | 0 | null | 2008-12-11 13:25:43.15 UTC | 30 | 2022-05-29 08:49:31.12 UTC | 2022-05-29 08:49:31.12 UTC | Craig Wilson | 224,132 | Craig Wilson | 25,333 | null | 1 | 27 | .net|com|x86-64|interop|32bit-64bit | 24,382 | <p>If a component is running x64-native, it can't load a 32-bit COM server in-process, because it's the wrong sort of process. There are a couple of solutions possible:</p>
<ol>
<li><p>If you can, build a 64-bit version of the COM code (which would of course register itself in the 64-bit registry). This is the cleanest solution, but may not be possible if you don't have the code for the COM server.</p></li>
<li><p>Run your .NET component as 32-bit x86, instead of x64. I assume you've already considered and rejected this one for some reason.</p></li>
<li><p>Host the COM component out-of-process using the <a href="http://msdn.microsoft.com/en-us/library/ms684044(VS.85).aspx" rel="noreferrer">COM surrogate</a> DLLhost.exe. This will make calls to the COM server much, much slower (they will now be interprocess Windows messages instead of native function calls), but is otherwise transparent (you don't have to do anything special). </p>
<p>This probably won't be an option if the server requires a custom proxy-stub instead of using the normal oleaut32 one (very rare, though), since there won't be a 64-bit version of the proxy available. As long as it can use the ordinary OLE marshalling, you can just <a href="http://msdn.microsoft.com/en-us/library/ms686606(VS.85).aspx" rel="noreferrer">register it for surrogate activation</a>.</p></li>
</ol> |
1,318,224 | MySQL Fire Trigger for both Insert and Update | <p>Is it possible to fire a mysql trigger for both the insert and update events of a table?</p>
<p>I know I can do the following</p>
<pre><code>CREATE TRIGGER my_trigger
AFTER INSERT ON `table`
FOR EACH ROW
BEGIN
.....
END //
CREATE TRIGGER my_trigger
AFTER UPDATE ON `table`
FOR EACH ROW
BEGIN
.....
END //
</code></pre>
<p>But how can I do</p>
<pre><code>CREATE TRIGGER my_trigger
AFTER INSERT ON `table` AND
AFTER UPDATE ON `table`
FOR EACH ROW
BEGIN
.....
</code></pre>
<p>Is it possible, or do I have to use 2 triggers? The code is the same for both and I don't want to repeat it.</p> | 1,318,231 | 3 | 0 | null | 2009-08-23 10:17:15.383 UTC | 16 | 2014-08-30 18:47:12.567 UTC | null | null | null | null | 161,529 | null | 1 | 132 | mysql|triggers | 120,162 | <p>You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.</p> |
539,302 | Significance of bool IsReusable in http handler interface | <p>When writing a http handler/module, there is an interface member to implement called - <a href="https://docs.microsoft.com/en-us/dotnet/api/system.web.ihttphandler.isreusable" rel="noreferrer">bool IsReusable</a>.</p>
<p>What is the significance of this member? If I set it to false (or true), what does this mean for the rest of the web app?</p> | 539,321 | 3 | 1 | null | 2009-02-11 23:14:16.873 UTC | 23 | 2018-09-18 09:38:24.563 UTC | 2018-09-18 09:38:24.563 UTC | null | 5,407,188 | GSS | 32,484 | null | 1 | 133 | asp.net|httphandler|ihttphandler | 24,729 | <p>The normal entry point for a handler is the ProcessRequest method. However you may have code in the class constructor which puts together some instance values which are expensive to build.</p>
<p>If you specify Reusable to be true the application can cache the instance and reuse it in another request by simply calling its ProcessRequest method again and again, without having to reconstruct it each time.</p>
<p>The application will instantiate as many of these handlers as are need to handle the current load.</p>
<p>The downside is that if the number of instances needed is larger than the instances currently present, they cause more memory to be used. Conversely they can also reduce apparent memory uses since their instance value will survive GC cycles and do not need to be frequently re-allocated.</p>
<p>Another caveat is you need to be sure that at the end of the ProcessRequest execution the object state is as you would want for another request to reuse the object.</p> |
22,081,209 | Find the root of the git repository where the file lives | <p>When working in Python (e.g. running a script), how can I find the path of the root of the git repository where the script lives?</p>
<p>So far I know I can get the current path with:</p>
<pre><code>path_to_containing_folder = os.path.dirname(os.path.realpath(__file__))
</code></pre>
<p>How can I then find out where the git repository lives?</p> | 41,920,796 | 8 | 0 | null | 2014-02-27 21:47:41.933 UTC | 12 | 2021-05-13 08:23:34.277 UTC | null | null | null | null | 283,296 | null | 1 | 39 | python|git | 37,544 | <p>Use the GitPython module <a href="http://gitpython.readthedocs.io/en/stable/" rel="noreferrer">http://gitpython.readthedocs.io/en/stable/</a>.</p>
<pre><code>pip install gitpython
</code></pre>
<p>Assume you have a local Git repo at <code>/path/to/.git</code>. The below example receives <code>/path/to/your/file</code> as input, it correctly returns the Git root as <code>/path/to/</code>.</p>
<pre><code>import git
def get_git_root(path):
git_repo = git.Repo(path, search_parent_directories=True)
git_root = git_repo.git.rev_parse("--show-toplevel")
print git_root
if __name__ == "__main__":
get_git_root("/path/to/your/file")
</code></pre> |
35,029,277 | How to modify environment variables passed to custom CMake target? | <p>Perhaps I am missing something obvious, but I can't seem to figure out how to explicitly set environment variables that can be seen by processes launched through <a href="https://cmake.org/cmake/help/v3.0/command/add_custom_target.html"><code>add_custom_target()</code></a>.</p>
<p>I tried the following:</p>
<pre><code>set(ENV{PATH} "C:/Some/Path;$ENV{PATH}")
add_custom_target(newtarget somecommand)
</code></pre>
<p>Unfortunately, the <code>%PATH%</code> environment variable appears unchanged to <code>somecommand</code>. (I have set up a Gist that reproduces the problem <a href="https://gist.github.com/nathan-osman/785152e6452559852fc8">here</a>.)</p>
<p>What am I doing wrong?</p> | 35,042,808 | 3 | 1 | null | 2016-01-27 05:05:56.017 UTC | 7 | 2020-08-26 14:43:07.637 UTC | null | null | null | null | 193,619 | null | 1 | 50 | cmake|environment-variables | 37,057 | <p>A portable way of setting environment variables for a custom target is to use CMake's command-line tool mode command <code>env</code>:</p>
<blockquote>
<pre><code>env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...
</code></pre>
<p>Run command in a modified environment.</p>
</blockquote>
<p>E.g.:</p>
<pre><code>add_custom_target(newtarget ${CMAKE_COMMAND} -E env NAME=VALUE somecommand)
</code></pre>
<p>Also see <a href="https://cmake.org/cmake/help/latest/manual/cmake.1.html#run-a-command-line-tool" rel="noreferrer">Command Line Tool Mode</a>.</p> |
20,173,101 | Copy the content of a div into another div | <p>I have two divs on my website. They both share the same css properties, but one of them holds 24 other divs. I want all of these 24 divs to be copied into the other div.
This is how it looks like:</p>
<pre><code><div id="mydiv1">
<div id="div1">
</div>
</div id="div2>
</div>
//and all the way up to div 24.
</div>
<div id="mydiv2">
</div>
</code></pre>
<p>I want all of the 24 divs within mydiv1 to be copied into mydiv2 when the page loads.</p>
<p>Thanks in advance</p> | 20,173,115 | 5 | 0 | null | 2013-11-24 09:37:29.823 UTC | 7 | 2022-07-16 17:26:51.517 UTC | 2018-04-23 19:36:46.71 UTC | null | 2,934,005 | null | 2,934,005 | null | 1 | 16 | javascript|html | 73,885 | <p>Firstly we are assigning divs into variables (optional)</p>
<pre><code>var firstDivContent = document.getElementById('mydiv1');
var secondDivContent = document.getElementById('mydiv2');
</code></pre>
<p>Now just assign mydiv1's content to mydiv2.</p>
<pre><code>secondDivContent.innerHTML = firstDivContent.innerHTML;
</code></pre>
<p><strong>DEMO</strong>
<a href="http://jsfiddle.net/GCn8j/">http://jsfiddle.net/GCn8j/</a></p>
<p><strong>COMPLETE CODE</strong></p>
<pre><code><html>
<head>
<script type="text/javascript">
function copyDiv(){
var firstDivContent = document.getElementById('mydiv1');
var secondDivContent = document.getElementById('mydiv2');
secondDivContent.innerHTML = firstDivContent.innerHTML;
}
</script>
</head>
<body onload="copyDiv();">
<div id="mydiv1">
<div id="div1">
</div>
<div id="div2">
</div>
</div>
<div id="mydiv2">
</div>
</body>
</html>
</code></pre> |
20,030,716 | Change default primary key in Eloquent | <p>Can I change Eloquent model primary key. </p>
<p>I want to set primary key for example <code>admin_id</code> instead of 'id'?</p>
<p>I know I can change table name for model like </p>
<pre><code>protected $table = "admin";
</code></pre>
<p>Is there something similar for primary key?</p> | 20,030,835 | 6 | 0 | null | 2013-11-17 12:35:41.347 UTC | 13 | 2021-02-14 14:04:19.297 UTC | null | null | null | null | 1,291,189 | null | 1 | 103 | laravel-4|eloquent | 114,594 | <p>Yes </p>
<pre><code>class User extends Eloquent {
protected $primaryKey = 'admin_id';
}
</code></pre> |
6,233,610 | PHP Code Deployment Tips | <p>In the past, I have been developing in a very amateurish fashion, meaning I had a local machine where I developed and tested code and a production machine to which I copied the code when I was done. Recently I modified this slightly to where I developed locally, checked the code into SVN and then updated the production machine through SVN.</p>
<p>Now I would like to start a new project and improve my workflow. Ideally I had the following in mind:</p>
<ul>
<li>Have one or more local dev environments</li>
<li>Develop and test on local machine(s)</li>
<li>Use SVN (or Git) as code repository</li>
<li>Use a build tool to set up new environments (either dev, staging or production) and deploy code</li>
</ul>
<p>Since I am not very familiar with this process, I am looking for suggestions on how to best set this idea up and the tools to use, especially when it comes to the build tools. I was looking into Ant and Phing (possibly make), but I am so new to this that I would really like to get some guidance. Are there any good tutorials or books about PHP deployment, especially for beginners? What I am especially interested in are the following topics:</p>
<ul>
<li>Deployment to different types of servers with different settings (e.g. dev uses different db, db passwords, PHP error reporting than production or staging).</li>
<li>Deployment that automatically pulls code from SVN.</li>
<li>Deployment that temporarily sets a "Maintenance" page for production environment.</li>
<li>Once I mastered the above, maybe even do some testing in the build process.</li>
</ul>
<p>I know my question might sound quite confused... I admit, I am new to this and might be a little off the target in what I really need. That's why any help is greatly appreciated.</p> | 6,233,936 | 3 | 4 | null | 2011-06-03 23:30:00.787 UTC | 12 | 2011-08-25 06:41:55.23 UTC | 2011-08-25 06:41:55.23 UTC | null | 282,601 | null | 783,488 | null | 1 | 25 | php|svn|deployment|build-process | 2,049 | <p>I would suggest making your testing deployment strategy a production-ready install-script -- since you're going to need one of those anyway eventually.</p>
<p>A few tips that may seem obvious to some, but are worth pointing out:</p>
<ul>
<li>Your config file saved in your VCS should be a template, and should be named differently from the file that will eventually contain the actual settings. E.g. <code>config-dist.php</code> or <code>config-sample.conf</code> or <code>sample/config-mysql.php</code> or something along those lines. Otherwise you will end up accidentally checking in a server-specific configuration file over your template.</li>
<li>For PHP deployment, anticipate that some users will not be able to run server-side scripts through any mechanism other than the web server itself. A PHP-based installer is almost non-negotiable.</li>
<li>You should include a consumer-friendly update mechanism, and for that, wordpress is a great example of a project to emulate. A PHP script can (a) download the latest build, (b) use the <a href="http://php.net/manual/en/book.ftp.php" rel="nofollow noreferrer">ftp</a> functions to update your application's files, and (c) execute an update script which makes the appropriate changes to the database, etc.</li>
<li>For heaven's sake don't do like [<em>redacted</em>] and make your users download and install separate patches for each point release. Have them download the latest (final) release which contains all the updates to date, and applies the correct <code>ALTER TABLE</code> functions in sequence.</li>
</ul>
<p>Whether the files are deployed via SVN or through FTP, the install/update mechanism should be the same: get the latest files, run the update script. The updater uses the version listed in the PHP script and the version listed in the DB, and uses that knowledge to apply the appropriate DB patches in order. As for how to generate those patches, there are <a href="https://stackoverflow.com/questions/218499/mysql-diff-tool">other questions</a> here that you can refer to for more info.</p>
<p>As for the "Maintenance" page, just use the version trick mentioned above to trigger it (compare the version in the DB against the version in the PHP code). It's also useful to be able to mark a site as "down" to the public but make it visible to admins (like Joomla does), which you can trigger through database or filesystem flags. </p>
<p>As for automatically pulling code from SVN, I'd say you're better off with either a cron script or with commit triggers than working that into your application, since it wouldn't be relevant to end users.</p> |
5,615,916 | jQuery: count array elements by value | <p>I have an array of elements assembled by:</p>
<pre><code>timeArray = [];
$('.time_select').each(function(i, selected) {
timeArray[i] = $(selected).val();
});
</code></pre>
<p>where <code>.time_select</code> is a class on a group of different HTML select tags.</p>
<p>What I'd like to do is count the number of times a specific value occurs in <code>timeArray</code>. Strangely enough, I haven't found any concise solution... surely there's a simple way to do this?</p> | 5,615,959 | 4 | 0 | null | 2011-04-11 01:17:43.893 UTC | 1 | 2011-04-11 03:52:05.137 UTC | 2011-04-11 01:44:08.437 UTC | null | 405,143 | null | 346,977 | null | 1 | 3 | jquery|arrays | 38,516 | <pre><code>timeArray = [];
occurs = {};
$('.time_select').each(function(i, selected) {
timeArray[i] = $(selected).val();
if (occurs[timeArray[i]] != null ) { occurs[timeArray[i]]++; }
else {occurs[timeArray[i]] = 1; }
});
</code></pre> |
6,263,009 | Backbone.js REST URL with ASP.NET MVC 3 | <p>I have been looking into <a href="http://documentcloud.github.com/backbone/">Backbone.js</a> lately and i am now trying to hook it up with my server-side asp.net mvc 3.</p>
<p>This is when i discovered a issue. ASP.NET listens to different Actions, Ex: <code>POST /Users/Create</code> and not just <code>POST /users/</code>. Because of that, the <code>Model.Save()</code> method in backbone.js will not work.</p>
<p>How should we tackle this problem? Do i have to rewrite the <code>Backbone.Sync</code>?</p> | 6,273,280 | 4 | 3 | null | 2011-06-07 09:09:00.233 UTC | 15 | 2012-05-24 14:50:53.707 UTC | null | null | null | null | 526,696 | null | 1 | 13 | asp.net-mvc-3|rest|backbone.js | 7,000 | <p>The answer is not to override Backbone.sync. You rarely would want to do this. Instead, you need only take advantage of the model's url property where you can assign a function which returns the url you want. For instance, </p>
<pre><code>Forum = Backbone.Model.extend({
url: function() {
return this.isNew() ? '/Users/Create' : '/Users/' + this.get('id');
}
});
</code></pre>
<p>where the url used for a model varies based upon whether the model is new. If I read your question correctly, this is all you need to do. </p> |
5,640,721 | Visual Studio Key Strokes: Swapping lines | <p>Is there a keystroke in visual studio similar to Eclipse's <kbd>Alt</kbd> + <kbd>↑</kbd>/<kbd>↓</kbd>?</p>
<p>For example:</p>
<pre><code>int x = 0; // Cursor is anywhere on this line.
int y = 1;
</code></pre>
<p>and <kbd>Alt</kbd> + <kbd>Down</kbd> were pressed, then:</p>
<pre><code>int y = 1;
int x = 0; // Cursor is anywhere on this line.
</code></pre> | 5,641,152 | 4 | 0 | null | 2011-04-12 19:46:54.36 UTC | 3 | 2019-07-15 07:04:10.427 UTC | 2011-09-16 09:26:48.717 UTC | null | 321,366 | null | 391,618 | null | 1 | 47 | visual-studio|keyboard-shortcuts|shortcut | 23,917 | <p>VS 2013 and later:</p>
<p><kbd>Alt</kbd> + <kbd>↑</kbd> (<code>Edit.MoveSelectedLinesUp</code>)</p>
<p><kbd>Alt</kbd> + <kbd>↓</kbd> (<code>Edit.MoveSelectedLinesDown</code>)</p>
<hr>
<p>VS 2012:</p>
<p><kbd>Shift</kbd>+<kbd>Alt</kbd>+ <kbd>T</kbd>
(<code>Edit.LineTranspose</code>) </p>
<p>but this only swaps between the current and the next line (move down only).</p>
<p>VS 2012 does not support macros but there is the <a href="http://visualstudiogallery.msdn.microsoft.com/3a96a4dc-ba9c-4589-92c5-640e07332afd" rel="noreferrer">Productivity Power Tools 2012</a> extension that adds (besides some other nice features) commands to move a line up or down with <kbd>Alt</kbd> + <kbd>↑</kbd> and <kbd>Alt</kbd> + <kbd>↓</kbd>.</p>
<hr>
<p>VS 2010 and earlier:</p>
<p>Line transpose works (<kbd>Shift</kbd>+<kbd>Alt</kbd>+ <kbd>T</kbd>) but still no move up.</p>
<p>You could write a macro for those commands, I think this question may help you: <a href="https://stackoverflow.com/q/313462/303427">Visual Studio: hotkeys to move line up/down and move through recent changes</a></p> |
1,819,341 | How to read XML file from web using powershell | <p>When I connect to my HP ILO using the URL, <a href="http://ilo-ip/xmldata?item=All" rel="noreferrer">http://ilo-ip/xmldata?item=All</a> it is returning a XML file in below format.</p>
<pre><code> <?xml version="1.0" ?>
- <RIMP>
- <HSI>
<SPN>ProLiant DL385 G1</SPN>
<SBSN>ABCDEFG</SBSN>
<UUID>123456789</UUID>
</HSI>
- <MP>
<ST>1</ST>
<PN>Integrated Lights-Out (iLO)</PN>
<FWRI>1.82</FWRI>
<HWRI>ASIC: 2</HWRI>
<SN>ILOABCDEFG</SN>
<UUID>ILO1234545</UUID>
</MP>
</RIMP>
</code></pre>
<p>Is there any powershell command/script to read XML data from web URL?</p> | 1,819,936 | 2 | 0 | null | 2009-11-30 11:49:31.84 UTC | 2 | 2018-11-06 20:21:26.937 UTC | null | null | null | null | 209,355 | null | 1 | 8 | xml|powershell | 40,158 | <p>PowerShell uses the .Net framework XmlDocument so you could call the load method to load the xml into an XmlDocument object like this:</p>
<pre><code>#Option 1
$doc = New-Object System.Xml.XmlDocument
$doc.Load("http://ilo-ip/xmldata?item=All")
#Option 2
[xml]$doc = (New-Object System.Net.WebClient).DownloadString("http://ilo-ip/xmldata?item=All")
# Your XML will then be in the $doc and the names of the XML nodes can be used as
# properties to access the values they hold. This short example shows how you would
# access the value held in the SPN nodes from your sample XML
Write-Host $doc.RIMP.HSI.SPN
</code></pre>
<p>If your looking for more information on working with the XML once it has been loaded check out <a href="http://powershell.com/cs/blogs/ebook/" rel="noreferrer">Dr. Tobias Weltner's eBook</a> at PowerShell.com, <a href="http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-14-xml.aspx" rel="noreferrer">chapter 14</a> covers XML.</p> |
1,617,857 | SoapFault exception: [HTTP] Unsupported Media Type when accessing Java web-service from PHP | <p>I'm trying to connect to a Java web-service using the <code>Zend_Soap_Client</code> from the Zend Framework v1.9.0:</p>
<pre><code><?php
include( 'Zend/Loader/Autoloader.php');
$autoloader = Zend_Loader_Autoloader::getInstance();
$client = new Zend_Soap_Client('https://webservice.com/webservice-war/webservice?wsdl'
, array('encoding'=> 'UTF-8'));
try{
$result = $client->find_customer(array('username' => 'user',
'password' => '123'), array('city' => 'some city'));
} catch(Exception $e){
echo $e;
}
echo '<pre>' . $client->getLastRequestHeaders() . '</pre>';
?>
</code></pre>
<p>Outputs:</p>
<pre><code>SoapFault exception: [HTTP] Unsupported Media Type in
/Library/ZendFramework-1.9.0/library/Zend/Soap/Client.php:937
Stack trace:
#0 [internal function]:
SoapClient->__doRequest('_doRequest(Object(Zend_Soap_Client_Common),
'__doRequest('__soapCall('find_customer', Array, NULL, NULL, Array)
#6 [internal function]:
Zend_Soap_Client->__call('find_customer', Array)
#7 /Users/webservicetest/index.php(8):
Zend_Soap_Client->find_customer(Array, Array)
#8 {main}
POST /webservice-war/webservice HTTP/1.1
Host: webservice.com
Connection: Keep-Alive
User-Agent: PHP-SOAP/5.2.6
Content-Type: application/soap+xml; charset=utf-8; action=""
Content-Length: 315
</code></pre>
<p>Any idea what could be wrong? The url is correct, since I get the availible functions when calling</p>
<pre><code>$client->getFunctions()
</code></pre> | 1,624,442 | 2 | 0 | null | 2009-10-24 12:17:09.387 UTC | 2 | 2015-06-11 09:48:48.433 UTC | null | null | null | null | 76,799 | null | 1 | 9 | java|php|zend-framework|soap|web-services | 64,864 | <p>According to <a href="http://www.w3.org/TR/soap12-part2/#tabreqstatereqtrans" rel="noreferrer">this listing</a>, the exception indicates that the server hosting the web-service is not happy with your requests encoding:</p>
<blockquote>
<p>Indicates that the peer HTTP server
does not support the Content-type used
to encode the request message. The
message exchange is regarded as having
completed unsuccessfully.</p>
</blockquote>
<p>So you should check with the web-service provider concerning the content-type/encoding they expect.</p>
<p>A possible solution if you are using <code>SOAP_1_2</code>is to change to <code>SOAP_1_1</code> since that will alter the requests made.</p> |
1,417,727 | Can someone please explain what these ApacheBench results mean? | <p>i'm trying to figure out how to use ApacheBench and benchmark my website. I installed the default site project (it's ASP.NET MVC but please don't put stop reading if u're not a .NET person).</p>
<p>I didn't change anything. Add new project. Set confuration to RELEASE. Run without Debug. (so it's in LIVE mode). Yes, this is with the built in webserver, not the production grade IIS or Apache or whatever.</p>
<p>So here's the results :-</p>
<pre><code>C:\Temp>ab -n 1000 -c 1 http://localhost:50035/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software: ASP.NET
Server Hostname: localhost
Server Port: 50035
Document Path: /
Document Length: 1204 bytes
Concurrency Level: 1
Time taken for tests: 2.371 seconds
Complete requests: 1000
Failed requests: 0
Write errors: 0
Total transferred: 1504000 bytes
HTML transferred: 1204000 bytes
Requests per second: 421.73 [#/sec] (mean)
Time per request: 2.371 [ms] (mean)
Time per request: 2.371 [ms] (mean, across all concurrent requests)
Transfer rate: 619.41 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 1.1 0 16
Processing: 0 2 5.5 0 16
Waiting: 0 2 5.1 0 16
Total: 0 2 5.6 0 16
Percentage of the requests served within a certain time (ms)
50% 0
66% 0
75% 0
80% 0
90% 16
95% 16
98% 16
99% 16
100% 16 (longest request)
C:\Temp>
</code></pre>
<p>Now, i'm not sure exactly what I should be looking at. </p>
<p>Firstly, I after the number of requests a second. So if we have a requirement to handle 300 reqs/sec, then is this saying it handles and average of 421 req's a sec?</p>
<p>Secondly, what is the reason for adding more concurrent? As in, if i have 1000 hits on 1 concurrent, how does that differ to 500 on 2 concurrent? Is it to test if there's any code that blocks other requests?</p>
<p>Lastly, is there anything important I've missed from the results which I should take note of?</p>
<p>Thanks :)</p> | 1,417,745 | 2 | 0 | null | 2009-09-13 13:19:26.673 UTC | 11 | 2009-09-13 23:18:46.237 UTC | null | null | null | null | 30,674 | null | 1 | 16 | performance|benchmarking|apachebench | 13,705 | <blockquote>
<p>what is the reason for adding more
concurrent? As in, if i have 1000 hits
on 1 concurrent, how does that differ
to 500 on 2 concurrent? Is it to test
if there's any code that blocks other
requests?</p>
</blockquote>
<p>It's a bit about that, yes : your application is probably doing things where concurrency can bring troubles.</p>
<p>A couple of examples :</p>
<ul>
<li>a page is trying to access a file -- locking it in the process ; it means if another page has to access the same file, it'll have to wait until the first page has finished working with it.</li>
<li>quite the same for database access : if one page is writing to a database, there is some kind of locking mecanisms <em>(be it table-based, or row-based, or whatever, depending on your DBMS)</em></li>
</ul>
<p>Testing with a concurrency of one is OK... As long as your website will never have more than one user at the same time ; which is quite not realistic, I hope for you.</p>
<p><br>
You have to think about how many users will be on site at the same time, when it's in production -- and adjust the concurrency ; just remember that 5 users at the same time on your site doesn't mean you have to test with a concurrency of 5 with ab :</p>
<ul>
<li>real users will wait a couple of seconds between each request (time to read the page, click on a link, ...)</li>
<li>ab doesn't wait at all : each time a page is loaded (ie, a request is finished), it launches another request !</li>
</ul>
<p><br>
Also, two other things :</p>
<ul>
<li>ab only tests for one page -- real users will navigate on the whole website, which could cause concurrency problems you would not have while testing only one page</li>
<li>ab only loads one page : it doesn't request external resources (think CSS, images, JS, ...) ; which means you'll have lots of other requests, even if not realy costly, when your site is in production.</li>
</ul>
<p>As a sidenote : you might want to take a look at other tools, which can do far more complete tests, like <a href="http://www.joedog.org/index/siege-home" rel="noreferrer">siege</a>, <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">Jmeter</a>, or <a href="http://www.opensta.org/" rel="noreferrer">OpenSTA</a> : ab is really nice when you want to measure if something you did is optimizing your page or not ; but if you want to simulate "real" usage of your site, those are far more adapted.</p> |
2,139,274 | Grabbing the output sent to Console.Out from within a unit test? | <p>I am building a unit test in C# with NUnit, and I'd like to test that the main program actually outputs the right output depending on the command line arguments.</p>
<p>Is there a way from an NUnit test method that calls <code>Program.Main(...)</code> to grab everything written to <a href="https://docs.microsoft.com/en-us/dotnet/api/system.console.out" rel="noreferrer"><code>Console.Out</code></a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.console.error" rel="noreferrer"><code>Console.Error</code></a> so that I can verify against it?</p> | 2,139,303 | 2 | 3 | null | 2010-01-26 12:19:09.213 UTC | 13 | 2020-05-18 08:14:08.663 UTC | 2020-05-18 08:11:22.15 UTC | null | 1,364,007 | null | 267 | null | 1 | 57 | c#|unit-testing|console|nunit | 22,622 | <p>You can redirect <a href="https://docs.microsoft.com/en-us/dotnet/api/system.console.in" rel="noreferrer"><code>Console.In</code></a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/system.console.out" rel="noreferrer"><code>Console.Out</code></a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.console.error" rel="noreferrer"><code>Console.Error</code></a> to custom StringWriters, like this</p>
<pre><code>[TestMethod]
public void ValidateConsoleOutput()
{
using (StringWriter sw = new StringWriter())
{
Console.SetOut(sw);
ConsoleUser cu = new ConsoleUser();
cu.DoWork();
string expected = string.Format("Ploeh{0}", Environment.NewLine);
Assert.AreEqual<string>(expected, sw.ToString());
}
}
</code></pre>
<p>See <a href="https://docs.microsoft.com/en-us/archive/blogs/ploeh/console-unit-testing" rel="noreferrer">this blog post</a> for full details.</p> |
6,194,041 | Scrapy image download how to use custom filename | <p>For my <a href="http://doc.scrapy.org/index.html" rel="noreferrer">scrapy</a> project I'm currently using the <a href="http://doc.scrapy.org/topics/images.html#scrapy.contrib.pipeline.images.ImagesPipeline" rel="noreferrer">ImagesPipeline</a>. The downloaded images are <a href="http://doc.scrapy.org/topics/images.html#file-system-storage" rel="noreferrer">stored with a SHA1 hash</a> of their URLs as the file names.</p>
<p><strong>How can I store the files using my own custom file names instead?</strong> </p>
<p>What if my custom file name needs to contain another scraped field from the same item? e.g. use the <code>item['desc']</code> and the filename for the image with <code>item['image_url']</code>. If I understand correctly, that would involve somehow accessing the other item fields from the Image Pipeline. </p>
<p>Any help will be appreciated.</p> | 6,196,180 | 6 | 0 | null | 2011-05-31 21:57:05.043 UTC | 15 | 2021-02-23 12:05:27.323 UTC | 2014-02-21 16:28:03.61 UTC | null | 1,797,098 | null | 773,694 | null | 1 | 14 | python|scrapy | 14,077 | <p>This was the way I solved the problem in Scrapy 0.10 .
Check the method persist_image of FSImagesStoreChangeableDirectory. The filename of the downloaded image is key</p>
<pre><code>class FSImagesStoreChangeableDirectory(FSImagesStore):
def persist_image(self, key, image, buf, info,append_path):
absolute_path = self._get_filesystem_path(append_path+'/'+key)
self._mkdir(os.path.dirname(absolute_path), info)
image.save(absolute_path)
class ProjectPipeline(ImagesPipeline):
def __init__(self):
super(ImagesPipeline, self).__init__()
store_uri = settings.IMAGES_STORE
if not store_uri:
raise NotConfigured
self.store = FSImagesStoreChangeableDirectory(store_uri)
</code></pre> |
5,959,788 | Google Maps API V3 : How show the direction from a point A to point B (Blue line)? | <p>I have latitude and longitude for 2 points on database, I want my Google Map to display a route from point A to point B...</p>
<p>Just like we see <a href="https://www.google.com/maps/dir/Pushpanjali,+Pitampura,+New+Delhi,+Delhi,+India/Rithala+Metro+Station,+Rithala+Rd,+Sector+12,+Rohini,+New+Delhi,+Delhi,+India/@28.7067137,77.1029945,14z/data=!4m13!4m12!1m5!1m1!1s0x390d03fa8f749ecf:0x92cd7d17df1b6531!2m2!1d77.1102088!2d28.694143!1m5!1m1!1s0x390d014c11fcbee5:0x48f0136e99ecc5e2!2m2!1d77.107165!2d28.720783?hl=en" rel="noreferrer">here</a> (Google Maps Directions)</p>
<p><a href="https://i.stack.imgur.com/C5wEC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/C5wEC.png" alt="Image from the link"></a></p>
<p>How to draw that direction line on map ?</p> | 5,962,203 | 6 | 0 | null | 2011-05-11 05:45:09.59 UTC | 27 | 2022-04-16 09:03:41.407 UTC | 2022-04-16 09:03:41.407 UTC | null | 2,314,737 | null | 731,963 | null | 1 | 73 | javascript|google-maps|google-maps-api-3 | 206,034 | <p>Use <a href="http://code.google.com/apis/maps/documentation/javascript/services.html#Directions" rel="noreferrer">directions service</a> of Google Maps API v3. It's basically the same as directions API, but nicely packed in Google Maps API which also provides convenient way to easily render the route on the map. </p>
<p>Information and examples about rendering the directions route on the map can be found in <a href="http://code.google.com/apis/maps/documentation/javascript/services.html#RenderingDirections" rel="noreferrer">rendering directions section</a> of Google Maps API v3 documentation.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.