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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24,766,665 | No implementation was bound - Java Guice | <p>Novice here trying to use a dummy Java Facebook app that uses Guice to inject a database dependency into the Facebook factory but continue to have Guice error out telling me:</p>
<blockquote>
<p>### No implementation for com.example.storage.Db annotated with @com.example.storage.annotations.SystemDb() was bound while locating com.example.storage.Db annotated with @com.example.storage.annotations.SystemDb() for parameter 0 at com.example.facebook.client.exceptions.FacebookExceptionHandlerDb at com.example.facebook.client.guice.FacebookClientModule.configure</p>
<p>### Could not find a suitable constructor in com.example.facebook.statsd.StatsdClient. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private. at com.example.facebook.statsd.StatsdClient.class while locating com.example.facebook.statsd.StatsdClient for parameter 1 at com.example.facebook.client.exceptions.FacebookExceptionHandlerDb. com.example.facebook.client.guice.FacebookClientModule.configure</p>
</blockquote>
<p>Code for app:</p>
<h2>app.java</h2>
<pre><code>package com.example.facebook;
import com.google.inject.Guice;
import com.restfb.Connection;
import com.restfb.types.Post;
import com.example.facebook.client.FacebookClientFactory;
import com.example.facebook.client.RobustFacebookClient;
import com.example.facebook.client.guice.FacebookClientModule;
import com.example.facebook.statsd.StatsdClient;
public class App {
public static void main ( String[] args ) {
final FacebookClientFactory facebookClientFactory =
Guice.createInjector(new FacebookClientModule()).getInstance(FacebookClientFactory.class);
//error from line above
final RobustFacebookClient robustFacebookClient =
facebookClientFactory.create("accessToken");
//more ...
}
</code></pre>
<p>The resulting error points me to the <code>FacebookClientModule</code> binding:</p>
<h2>FacebookClientModule.java</h2>
<pre><code>public class FacebookClientModule extends AbstractModule {
bind(FacebookExceptionHandler.class).to(FacebookExceptionHandlerDb.class);
//error resulting from the failed binding on the FacebookExceptionHandlerDB class
install(new FactoryModuleBuilder()
.implement(FacebookClient.class, RobustFacebookClient.class)
.build(FacebookClientFactory.class));
}
</code></pre>
<p>}</p>
<p>Where inside the <code>FacebookExceptionHandleDB</code> class the constructor has the injection:</p>
<h2>FacebookExceptionHandlerDB.java</h2>
<pre><code>public class FacebookExceptionHandlerDb implements FacebookExceptionHandler {
// list of class String variables ...
private final FacebookErrorParser parser;
private final Db db;
private StatsdClient statsd;
@Inject
public FacebookExceptionHandlerDb(@SystemDb Db db, StatsdClient statsd, FacebookErrorParser parser) {
this.db = db;
this.statsd = statsd;
this.parser = parser;
}
}
</code></pre>
<p>From what I can gleam, the dependency injection for parameters zero and one, <code>db</code> and <code>statsD</code> respectively, is failing. Could someone point out where or what in the app code is missing?</p> | 24,767,043 | 2 | 0 | null | 2014-07-15 19:33:01.9 UTC | 4 | 2017-11-26 04:17:12.857 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 3,011,436 | null | 1 | 22 | java|dependency-injection|annotations|guice | 78,116 | <p>At first glance it seems like your missing the bindings for the Db annotated dependency and the StatsdClient.</p>
<p>You'll need to provide the missing bindings to your module like so</p>
<pre><code>bind(Db.class).annotatedWith(SystemDb.class).to(DbImplOfSomeSort.class);
bind(StatsdClient.class).to(StatsdClientImplOfSomeSort.class);
</code></pre>
<p>Guice is able to automatically inject Concrete Class with either a public no argument constructor or a constructor with @Inject without any specific defined binding in your module but when it comes to Interfaces you have to define the necessary bindings.</p>
<p>Here Db.class and StatsdClient.class are interfaces which you need to bind to specific implementation.</p> |
37,734,150 | How to update meta tags in React.js? | <p>I was working on a single page application in react.js, so what is the best way to update meta tags on page transitions or browser back/forward?</p> | 37,734,302 | 11 | 0 | null | 2016-06-09 18:59:48.173 UTC | 18 | 2022-09-16 05:51:58.873 UTC | null | null | null | null | 2,485,624 | null | 1 | 74 | reactjs | 148,347 | <p>I've used <a href="https://www.npmjs.com/package/react-document-meta" rel="noreferrer">react-document-meta</a> in an older project.</p>
<p>Just define your meta values</p>
<pre><code>const meta = {
title: 'Some Meta Title',
description: 'I am a description, and I can create multiple tags',
canonical: 'http://example.com/path/to/page',
meta: {
charset: 'utf-8',
name: {
keywords: 'react,meta,document,html,tags'
}
}
</code></pre>
<p>and place a</p>
<pre><code><DocumentMeta {...meta} />
</code></pre>
<p>in the return</p> |
35,405,618 | ngFor with index as value in attribute | <p>I have a simple <code>ngFor</code> loop which also keeps track of the current <code>index</code>. I want to store that <code>index</code> value in an attribute so I can print it. But I can't figure out how this works.</p>
<p>I basically have this:</p>
<pre><code><ul *ngFor="#item of items; #i = index" data-index="#i">
<li>{{item}}</li>
</ul>
</code></pre>
<p>I want to store the value of <code>#i</code> in the attribute <code>data-index</code>. I tried several methods but none of them worked.</p>
<p>I have a demo here: <a href="http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview" rel="noreferrer">http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview</a></p>
<p>How can I store the <code>index</code> value in the <code>data-index</code> attribute?</p> | 35,405,648 | 9 | 0 | null | 2016-02-15 09:27:57.367 UTC | 81 | 2022-08-19 04:14:27.46 UTC | 2018-01-19 15:44:41.57 UTC | null | 5,658,060 | null | 1,175,327 | null | 1 | 828 | angular|ngfor | 1,383,754 | <p>I would use this syntax to set the index value into an attribute of the HTML element:</p>
<h3>Angular >= 2</h3>
<p>You have to use <code>let</code> to declare the value rather than <code>#</code>.</p>
<pre class="lang-html prettyprint-override"><code><ul>
<li *ngFor="let item of items; let i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
</code></pre>
<h3>Angular = 1</h3>
<pre class="lang-html prettyprint-override"><code><ul>
<li *ngFor="#item of items; #i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
</code></pre>
<p>Here is the updated plunkr: <a href="http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview" rel="noreferrer">http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview</a>.</p> |
23,546,255 | How to use UrlFetchApp with credentials? Google Scripts | <p>I am trying to use Google Scripts UrlFetchApp to access a website with a basic username and password. As soon as I connect to the site a popup appears that requires authentication. I know the Login and Password, however I do not know how to pass them within the UrlFetchApp.</p>
<pre class="lang-js prettyprint-override"><code>var response = UrlFetchApp.fetch("htp://00.000.000.000:0000/");
Logger.log(response.getContentText("UTF-8"));
</code></pre>
<p>Currently running that code returns "Access Denied". The above code does not contain the actual address I am connecting to for security reasons. A "t" is missing from all the "http" in the code examples because they are being detected as links and Stackoverflow does not allow me to submit more than two links.</p>
<p>How can I pass the Login and Password along with my request? Also is there anyway I can continue my session once I have logged in? Or will my next UrlFetchApp request be sent from another Google server requiring me to login again? </p>
<p>The goal here is to login to the website behind Googles network infrastructure so it can act as a proxy then I need to issue another UrlFetchApp request to the same address that would look something like this: </p>
<pre class="lang-js prettyprint-override"><code>var response = UrlFetchApp.fetch("htp://00.000.000.000:0000/vuze/rpc?json={"method":"torrent-add","arguments":{"filename":"htp://vodo.net/media/torrents/anything.torrent","download-dir":"C:\\temp"}}");
Logger.log(response.getContentText("UTF-8"));
</code></pre> | 23,718,759 | 2 | 0 | null | 2014-05-08 15:34:25.953 UTC | 19 | 2020-02-21 23:46:08.207 UTC | 2020-02-21 23:46:08.207 UTC | null | 9,724,138 | null | 3,586,062 | null | 1 | 46 | authentication|google-apps-script|basic-authentication|credentials|urlfetch | 43,788 | <p>This question has been answered on another else where.
Here is the summary:</p>
<p><strong>Bruce Mcpherson</strong></p>
<blockquote>
<pre><code>basic authentication looks like this...
var options = {};
options.headers = {"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)};
</code></pre>
</blockquote>
<p><strong>Lenny Cunningham</strong></p>
<blockquote>
<pre><code>//Added Basic Authorization//////////////////////////////////////////////////////////////////////////////////////////
var USERNAME = PropertiesService.getScriptProperties().getProperty('username');
var PASSWORD = PropertiesService.getScriptProperties().getProperty('password');
var url = PropertiesService.getScriptProperties().getProperty('url');//////////////////////////Forwarded
</code></pre>
<p>Ports to WebRelay</p>
<pre><code> var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
var params = {
"method":"GET",
"headers":headers
};
var reponse = UrlFetchApp.fetch(url, params);
</code></pre>
</blockquote> |
43,458,971 | React Dev tools show my Component as Unknown | <p>I have the following simple component:</p>
<pre><code>import React from 'react'
import '../css.scss'
export default (props) => {
let activeClass = props.out ? 'is-active' : ''
return (
<div className='hamburgerWrapper'>
<button className={'hamburger hamburger--htla ' + activeClass}>
<span />
</button>
</div>
)
}
</code></pre>
<p>When I look for it in the react dev tools, I see:</p>
<p><a href="https://i.stack.imgur.com/dplzh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dplzh.png" alt="enter image description here"></a></p>
<p>Is this because I need to extend React component? Do I need to create this as a variable and do so?</p> | 43,459,021 | 3 | 0 | null | 2017-04-17 20:19:02.933 UTC | 12 | 2020-02-13 10:24:01.53 UTC | 2017-04-17 20:30:00.267 UTC | null | 6,465,572 | null | 6,465,572 | null | 1 | 42 | reactjs|google-chrome-devtools | 16,972 | <p>This happens when you export an anonymous function as your component. If you name the function (component) and then export it, it will show up in the React Dev Tools properly.</p>
<pre><code>const MyComponent = (props) => {}
export default MyComponent;
</code></pre> |
21,381,943 | How to configure Spring without persistence.xml? | <p>I'm trying to set up spring xml configuration without having to create a futher <code>persistence.xml</code>. But I'm constantly getting the following exception, even though I included the database properties in the <code>spring.xml</code></p>
<pre><code> Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\Users\me\workspace\app\src\main\webapp\WEB-INF\applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: No persistence units parsed from {classpath*:META-INF/persistence.xml}
</code></pre>
<p>spring.xml:</p>
<pre><code> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
</bean>
</code></pre>
<p>What am I missing here?</p> | 21,382,512 | 4 | 0 | null | 2014-01-27 13:17:36.917 UTC | 13 | 2021-01-10 14:11:32.757 UTC | 2016-09-20 13:24:46.743 UTC | null | 1,025,118 | null | 1,194,415 | null | 1 | 31 | java|spring|hibernate|jpa|configuration | 54,663 | <p>Specify the "packagesToScan" & "persistenceUnitName" properties in the entityManagerFactory bean definition.</p>
<pre><code><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="myPersistenceUnit" />
<property name="packagesToScan" >
<list>
<value>org.mypackage.*.model</value>
</list>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
</bean>
</code></pre>
<p>Note that this is for Spring version > 3.1</p> |
26,054,512 | React img tag issue with url and class | <p>I have the following simple react code in my JSX file:</p>
<pre><code>/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div><img src='http://placehold.it/400x20&text=slide1' alt={event.title} class="img-responsive"/><span>Hello {this.props.name}</span></div>;
}
});
React.renderComponent(<Hello name="World" />, document.body);
</code></pre>
<p>The output in the DOM is as follows:</p>
<pre><code><div data-reactid=".0">
<img src="http://placehold.it/400x20undefined1" data-reactid=".0.0">
<span data-reactid=".0.1">
<span data-reactid=".0.1.0">Hello </span>
<span data-reactid=".0.1.1">World</span>
</span>
</div>
</code></pre>
<p>I have two issues with it:</p>
<ul>
<li>The image URL is rendered incorrectly, it is rendered as '<a href="http://placehold.it/400x20undefined1">http://placehold.it/400x20undefined1</a>'</li>
<li>The class on my image disappears</li>
</ul>
<p>Any ideas?</p> | 26,065,890 | 2 | 0 | null | 2014-09-26 07:43:31.243 UTC | 7 | 2017-08-20 21:03:10.56 UTC | 2014-10-12 18:47:59.403 UTC | null | 2,445,990 | null | 48,050 | null | 1 | 43 | javascript|css|reactjs | 183,453 | <p>Remember that your img is not really a DOM element but a javascript expression. </p>
<ol>
<li><p>This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See <a href="http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions">http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions</a></p></li>
<li><p>In javascript, the class attribute is reference using className. See the note in this section: <a href="http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components">http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components</a></p>
<pre><code>/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
}
});
React.renderComponent(<Hello name="World" />, document.body);
</code></pre></li>
</ol> |
22,652,543 | Does new ASP.NET MVC identity framework work without Entity Framework and SQL Server? | <p>I am new to ASP.NET MVC 5 and so I am trying to use it as much as possible to learn it by practice. </p>
<p>So I am thinking of using the new OWIN implementation of ASP.NET MVC to implement the authentication and authorization of my project. That said, I am building the project in a way that it can work with various types of databases. </p>
<p>So far I have used generic ADO.NET elements (e.g. <code>DbDataReader</code> etc) and I have refused to use any ORM. So I am wondering if I can go ahead with using the new identity system of ASP.NET or will I be bound to Entity Framework and SQL Server if I do so?</p> | 22,677,441 | 4 | 0 | null | 2014-03-26 05:50:25.927 UTC | 24 | 2020-10-08 21:08:29.18 UTC | 2014-03-26 06:06:59.123 UTC | null | 13,302 | null | 1,063,345 | null | 1 | 41 | sql-server|entity-framework|asp.net-mvc-5|owin | 27,572 | <p>Not that simple. Not that hard either.</p>
<p>You'll have to write your custom implementation of:</p>
<ol>
<li><code>IUserStore<TUser></code></li>
<li><code>IUserPasswordStore<TUser></code></li>
<li><code>IUserTwoFactorStore<TUser></code></li>
<li><code>IUserClaimStore<TUser></code></li>
<li><code>IRoleStore<TRole></code></li>
<li><code>IUserSecurityStampStore<TUser, string></code></li>
<li><code>IUserRoleStore<TUser, string></code></li>
<li><code>UserManager<TUser></code></li>
</ol>
<p>Then create your own user implementation, from <code>IUser<TKey></code>, like:</p>
<pre><code>public class MyUser : IUser<string>
{
public string Id { get; set; }
public string UserName { get; set; }
}
</code></pre>
<p>Finally, from NuGet, remove AspNet.Identity.EntityFramework, which will remove EntityFramework too if you're not using it elsewhere.</p>
<p>Wherever your code breaks, rewrite it to use your custom implementations.</p>
<h2>Tip</h2>
<p>Create a MyUserRepository which implements items from 1 to 7.</p>
<p>Then, create a MyUserManager which implements item 8.</p>
<p>It will be damn easy to wire that up in place of default AspNet.Identity.EntityFramework classes.</p> |
24,522,793 | How can I add N milliseconds to a datetime in Python | <p>I'm setting a datetime var as such:</p>
<pre><code>fulldate = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S.%f")
</code></pre>
<p>where date and time are string of the appropriate nature for datetime. How can I increment this datetime by N milliseconds?</p> | 24,522,827 | 2 | 0 | null | 2014-07-02 04:18:47.59 UTC | 3 | 2016-06-10 05:47:37.443 UTC | null | null | null | null | 968,233 | null | 1 | 34 | python|datetime | 43,476 | <p>Use <code>timedelta</code></p>
<p>To increment by 500 ms:</p>
<pre><code>fulldate = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S.%f")
fulldate = fulldate + datetime.timedelta(milliseconds=500)
</code></pre>
<p>You can use it to increment minutes, hours, days etc. Documentation:</p>
<p><a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="noreferrer">https://docs.python.org/2/library/datetime.html#timedelta-objects</a></p> |
2,734,301 | Given a set of points, find if any of the three points are collinear | <p>What is the best algorithm to find if any three points are collinear in a set of points say n. Please also explain the complexity if it is not trivial.</p>
<p>Thanks<br>
Bala</p> | 2,786,316 | 3 | 6 | null | 2010-04-29 01:50:02.717 UTC | 13 | 2018-05-07 05:49:13.7 UTC | 2010-04-29 09:46:03.92 UTC | null | 249,460 | null | 207,335 | null | 1 | 16 | algorithm|graphics|data-structures|complexity-theory | 16,933 | <p>If you can come up with a better than O(N^2) algorithm, you can publish it!</p>
<p>This problem is <a href="http://maven.smith.edu/~orourke/TOPP/P11.html" rel="noreferrer">3-SUM Hard</a>, and whether there is a sub-quadratic algorithm (i.e. better than O(N^2)) for it is an open problem. Many common computational geometry problems (including yours) have been shown to be 3SUM hard and this class of problems is growing. Like NP-Hardness, the concept of 3SUM-Hardness has proven useful in proving 'toughness' of some problems.</p>
<p>For a proof that your problem is 3SUM hard, refer to the excellent surver paper here: <a href="http://www.cs.mcgill.ca/~jking/papers/3sumhard.pdf" rel="noreferrer">http://www.cs.mcgill.ca/~jking/papers/3sumhard.pdf</a></p>
<p>Your problem appears on page 3 (conveniently called 3-POINTS-ON-LINE) in the above mentioned paper.</p>
<p>So, the currently best known algorithm is O(N^2) and you already have it :-)</p> |
2,628,159 | SQL - Add up all row-values of one column in a singletable | <p>I've got a question regarding a SQL-select-query:
The table contains several columns, one of which is an Integer-column called "size" - the task I'm trying to perform is query the table for the sum of all rows (their values), or to be more exact get a artifical column in my ResultSet called "overallSize" which contains the sum of all "size"-values in the table. Preferable it would be possible to use a WHERE-clause to add only certain values ("WHERE bla = 5" or something similar).</p>
<p>The DB-engine is HSQLDB (HyperSQL), which is compliant to SQL2008.</p>
<p>Thank you in advance :)</p> | 2,628,173 | 3 | 0 | null | 2010-04-13 08:49:35.823 UTC | 1 | 2010-04-13 09:24:20.6 UTC | 2010-04-13 09:24:20.6 UTC | null | 17,343 | null | 315,274 | null | 1 | 17 | sql|sum|hsqldb | 72,762 | <pre><code>SELECT SUM(size) AS overallSize FROM table WHERE bla = 5;
</code></pre> |
2,724,820 | Tomcat - How to limit the maximum memory Tomcat will use | <p>I am running Tomcat on a small VPS (256MB/512MB) and I want to explicitly limit the amount of memory Tomcat uses. </p>
<p>I understand that I can configure this somehow by passing in the java maximum heap and initial heap size arguments;</p>
<pre><code>-Xmx256m
-Xms128m
</code></pre>
<p>But I can't find where to put this in the configuration of Tomcat 6 on Ubuntu.</p>
<p>Thanks in advance,</p>
<p>Gav</p> | 2,724,866 | 3 | 0 | null | 2010-04-27 20:26:11.977 UTC | 5 | 2016-12-01 21:47:58.503 UTC | null | null | null | null | 111,734 | null | 1 | 23 | memory|configuration|tomcat | 73,877 | <p>Set JAVA_OPTS in your init script,</p>
<pre><code> export JAVA_OPTS="-Djava.awt.headless=true -server -Xms48m -Xmx1024M -XX:MaxPermSize=512m"
</code></pre> |
3,074,938 | Django m2m form save " through " table | <p>I'm having trouble in saving a m2m data, containing a 'through' class table.
I want to save all selected members (selected in the form) in the through table.
But i don't know how to initialise the 'through' table in the view.</p>
<p>my code:</p>
<pre><code>class Classroom(models.Model):
user = models.ForeignKey(User, related_name = 'classroom_creator')
classname = models.CharField(max_length=140, unique = True)
date = models.DateTimeField(auto_now=True)
open_class = models.BooleanField(default=True)
members = models.ManyToManyField(User,related_name="list of invited members", through = 'Membership')
class Membership(models.Model):
accept = models.BooleanField(User)
date = models.DateTimeField(auto_now = True)
classroom = models.ForeignKey(Classroom, related_name = 'classroom_membership')
member = models.ForeignKey(User, related_name = 'user_membership')
</code></pre>
<p>and in the view:</p>
<pre><code>def save_classroom(request):
classroom_instance = Classroom()
if request.method == 'POST':
form = ClassroomForm(request.POST, request.FILES, user = request.user)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.user = request.user
new_obj.save()
membership = Membership(member = HERE SELECTED ITEMS FROM FORM,classroom=new_obj)
membership.save()
</code></pre>
<p>How should I initialise the membership for the Membership table to be populated right?</p> | 3,125,398 | 4 | 0 | null | 2010-06-19 08:45:41.48 UTC | 12 | 2019-01-14 15:47:25.77 UTC | 2013-12-17 20:25:44.63 UTC | null | 321,731 | null | 342,279 | null | 1 | 17 | django|forms|m2m | 11,212 | <p>In case of using normal m2m relation (not through intermediary table) you could replace:</p>
<pre><code>membership = Membership(member = HERE SELECTED ITEMS FROM FORM,classroom=new_obj)
membership.save()
</code></pre>
<p>with</p>
<pre><code>form.save_m2m()
</code></pre>
<p>But in case of using intermediary tables you need to manually handle POST data and create Membership objects with all required fields (<a href="http://groups.google.com/group/django-users/browse_thread/thread/e1b6a4d856aed6af" rel="noreferrer">similar problem</a>). The most basic solution is to change your view to something like:</p>
<pre><code>def save_classroom(request):
if request.method == 'POST':
form = ClassroomForm(request.POST, request.FILES)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.user = request.user
new_obj.save()
for member_id in request.POST.getlist('members'):
membership = Membership.objects.create(member_id = int(member_id), classroom = new_obj)
return HttpResponseRedirect('/')
else:
form = ClassroomForm()
return render_to_response('save_classroom.html', locals())
</code></pre>
<p>Note how request.POST is manipulated (.getlist). This is because post and get are <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects" rel="noreferrer">QueryDict</a> objects which has some implications (request.POST['members'] will return always one object!).</p>
<p>You can modify this code to get it more reliable (error handling etc.), and more verbose, eg:</p>
<pre><code>member = get_object_or_404(User, pk = member_id)
membership = Membership.objects.create(member = member , classroom = new_obj)
</code></pre>
<p>But note that you are performing some db queries in a loop which is not a good idea in general (in terms of performance).</p> |
2,531,837 | How can I get the PID of the parent process of my application | <p>My winform application is launched by another application (the parent), I need determine the pid of the application which launch my application using C#.</p> | 2,533,287 | 4 | 1 | null | 2010-03-28 03:53:11.327 UTC | 10 | 2020-07-26 00:16:38.633 UTC | 2020-07-26 00:16:38.633 UTC | null | 214,143 | null | 167,454 | null | 1 | 31 | c#|.net|winforms|process|pid | 29,930 | <p>WMI is the easier way to do this in C#. The Win32_Process class has the ParentProcessId property. Here's an example:</p>
<pre><code>using System;
using System.Management; // <=== Add Reference required!!
using System.Diagnostics;
class Program {
public static void Main() {
var myId = Process.GetCurrentProcess().Id;
var query = string.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId);
var search = new ManagementObjectSearcher("root\\CIMV2", query);
var results = search.Get().GetEnumerator();
results.MoveNext();
var queryObj = results.Current;
var parentId = (uint)queryObj["ParentProcessId"];
var parent = Process.GetProcessById((int)parentId);
Console.WriteLine("I was started by {0}", parent.ProcessName);
Console.ReadLine();
}
}
</code></pre>
<p>Output when run from Visual Studio:<br/></p>
<blockquote>
<p>I was started by devenv</p>
</blockquote> |
38,027,877 | Spark Transformation - Why is it lazy and what is the advantage? | <p><code>Spark Transformations</code> are lazily evaluated - when we call the action it executes all the transformations based on lineage graph.</p>
<p>What is the advantage of having the Transformations Lazily evaluated?</p>
<p>Will it improve the <code>performance</code> and less amount of <code>memory consumption</code> compare to eagerly evaluated?</p>
<p>Is there any disadvantage of having the Transformation lazily evaluated?</p> | 38,028,390 | 4 | 0 | null | 2016-06-25 11:14:43.263 UTC | 10 | 2022-03-24 11:42:50.943 UTC | 2021-02-18 16:57:22.617 UTC | null | 72,351 | null | 1,907,755 | null | 1 | 23 | apache-spark|transformation|lazy-evaluation | 29,839 | <p>For transformations, Spark adds them to a DAG of computation and only when driver requests some data, does this DAG actually gets executed. </p>
<p>One advantage of this is that Spark can make many optimization decisions after it had a chance to look at the DAG in entirety. This would not be possible if it executed everything as soon as it got it.</p>
<p>For example -- if you executed every transformation eagerly, what does that mean? Well, it means you will have to materialize that many intermediate datasets in memory. This is evidently not efficient -- for one, it will increase your GC costs. (Because you're really not interested in those intermediate results as such. Those are just convnient abstractions for you while writing the program.) So, what you do instead is -- you tell Spark what is the eventual answer you're interested and it figures out best way to get there.</p> |
52,625,979 | Confused about useBuiltIns option of @babel/preset-env (using Browserslist Integration) | <p>I'm working on a web project using Babel 7 with Webpack 4. I've never used Babel before and can't really understand some parts of it. Based on the <a href="https://babeljs.io/docs/en/babel-preset-env" rel="noreferrer">documentation</a> I'm using <code>@babel/preset-env</code> because it seems the recommended way (especially for beginners). Also using Browserslist integration via my <code>.browserslistrc</code> file.</p>
<p>Webpack does the compilation well (<code>babel-loader</code> version <code>8.0.2</code>), I have no errors but I'm confused about this <code>useBuiltIns: "entry"</code> <a href="https://babeljs.io/docs/en/babel-preset-env#browserslist-integration" rel="noreferrer">option mentioned here</a> and how <code>polyfill</code> system is working in Babel. </p>
<p><strong>.babelrc.js</strong></p>
<pre><code>module.exports = {
presets: [
['@babel/preset-env', {
"useBuiltIns": "entry" // do I need this?
}]
],
plugins: [
'@babel/plugin-syntax-dynamic-import'
]
};
</code></pre>
<p><strong>.browserslistrc</strong><br>
Copied from <a href="https://github.com/twbs/bootstrap/blob/v4.1.3/.browserslistrc" rel="noreferrer">here</a> (thought reasonable because my project is using Bootstrap).</p>
<pre><code>>= 1%
last 1 major version
not dead
Chrome >= 45
Firefox >= 38
Edge >= 12
Explorer >= 10
iOS >= 9
Safari >= 9
Android >= 4.4
Opera >= 30
</code></pre>
<p><strong>So my questions are:</strong></p>
<p>1) Do I need to use that <code>useBuiltIns: "entry"</code> option?</p>
<p>2) Do I need to install <code>@babel/polyfill</code> package and start my <code>vendors.js</code> with <code>require("@babel/polyfill");</code> ? </p>
<p>3) What if I omit both?</p>
<p>If I do 1 and 2, my <code>vendors.js</code> grows up to <code>411 KB</code><br>
If I ommit both it's just <code>341 KB</code><br>
after a production build.</p>
<p>I thought <code>@babel/preset-env</code> handles all the rewrites and polyfills by default without any extra <code>import/require</code> needed on my side...</p>
<p>Thanks!</p>
<p><strong>-- EDIT --</strong></p>
<p><em>Babel's team has just <a href="https://github.com/babel/website/pull/1858" rel="noreferrer">updated</a> the <a href="https://babeljs.io/docs/en/babel-polyfill#usage-in-node-browserify-webpack" rel="noreferrer">docs of <code>@babel/polyfill</code></a> based on some GitHub issues (including mine) complaining about unclear/misleading documentation. Now it's obvious how to use it. (...and after that my original question seems stupid :)</em></p> | 56,505,264 | 2 | 0 | null | 2018-10-03 11:23:28.593 UTC | 27 | 2019-06-08 09:52:25.267 UTC | 2018-10-08 08:13:03.373 UTC | null | 5,263,363 | null | 5,263,363 | null | 1 | 85 | javascript|webpack|babeljs|babel-preset-env | 33,943 | <blockquote>
<p>1) Do I need to use that useBuiltIns: "entry" option?</p>
</blockquote>
<p>Yes, if you want to include polyfills based on your target environment.</p>
<p>TL;DR</p>
<p>There're basically 3 options for <code>useBuiltIns</code>:</p>
<p><strong>"entry"</strong>: when using this option, <code>@babel/preset-env</code> replaces direct imports of <code>core-js</code> to imports of only the specific modules required for a target environment.</p>
<p>That means you need to add</p>
<pre><code>import "core-js/stable";
import "regenerator-runtime/runtime";
</code></pre>
<p>to your entry point and these lines will be replaced by only required polyfills. When targeting chrome 72, it will be transformed by <code>@babel/preset-env</code> to</p>
<pre><code>import "core-js/modules/es.array.unscopables.flat";
import "core-js/modules/es.array.unscopables.flat-map";
import "core-js/modules/es.object.from-entries";
import "core-js/modules/web.immediate";
</code></pre>
<hr>
<p><strong>"usage"</strong>: in this case polyfills will be added automatically when the usage of some feature is unsupported in target environment. So:</p>
<pre><code>const set = new Set([1, 2, 3]);
[1, 2, 3].includes(2);
</code></pre>
<p>in browsers like <code>ie11</code> will be replaced with </p>
<pre><code>import "core-js/modules/es.array.includes";
import "core-js/modules/es.array.iterator";
import "core-js/modules/es.object.to-string";
import "core-js/modules/es.set";
const set = new Set([1, 2, 3]);
[1, 2, 3].includes(2);
</code></pre>
<p>In case target browser is latest chrome, no transformations will apply.</p>
<p>That's personally my chosen weapon as there's no need to include anything (core-js or regenerator) in source code as only required polyfills will be added automatically based on target environment set in browserlist.</p>
<hr>
<p><strong>false</strong>: that's the default value when no polyfills are added automatically.</p>
<hr>
<blockquote>
<p>2) Do I need to install @babel/polyfill package and start my
vendors.js with require("@babel/polyfill"); ?</p>
</blockquote>
<p>Yes for environment prior to <code>babel v7.4</code> and <code>core-js v3</code>.</p>
<p>TL;DR</p>
<p>No. Starting from <code>babel v7.4</code> and <code>core-js v3</code> (which is used for polyfilling under the hood) <code>@babel/preset-env</code> will add the polyfills only when it know which of them required and in the recommended order.</p>
<p>Moreover <code>@babel/polyfill</code> is considered as deprecated in favor of separate <code>core-js</code> and <code>regenerator-runtime</code> inclusions.</p>
<p>So using of <code>useBuiltIns</code> with options other than false should solve the issue.</p>
<p>Don't forget to add <code>core-js</code> as a dependency to your project and set its version in <code>@babel/preset-env</code> under <code>corejs</code> property. </p>
<hr>
<blockquote>
<p>3) What if I omit both?</p>
</blockquote>
<p>As @PlayMa256 already answered, there will be no polyfills.</p>
<hr>
<p>More detailed and whole info con be found at <code>core-js</code> <a href="https://github.com/zloirock/core-js/blob/master/docs/2019-03-19-core-js-3-babel-and-a-look-into-the-future.md#babel" rel="noreferrer">creator's page</a> </p>
<p>Also please feel free to play with <a href="https://github.com/elitvinchuk/babel-sandbox" rel="noreferrer">babel sandbox</a></p> |
672,836 | Question about Repositories and their Save methods for domain objects | <p>I have a somewhat ridiculous question regarding DDD, Repository Patterns and ORM. In this example, I have 3 classes: <strong>Address</strong>, <strong>Company</strong> and <strong>Person</strong>. A Person is a member of a Company and has an Address. A Company also has an Address. </p>
<p>These classes reflect a database model. I removed any dependencies of my Models, so they are not tied to a particular ORM library such as NHibernate or LinqToSql. These dependencies are dealt with inside the Repositories.</p>
<p>Inside one of <strong>Repositories</strong> there is a <strong>SavePerson(Person person)</strong> method which <strong>inserts/updates</strong> a Person depending on whether it already exists in the database.</p>
<p>Since a Person object has a Company, I currently save/update the values of the Company property too when making that SavePerson call. I insert / update all of the Company's data - Name and Address - during this procedure. </p>
<p>However, I really have a hard time thinking of a case where a Company's data can change while dealing with a Person - I only want to be able to assign a Company to a Person, or to move a Person to another Company. I don't think I ever want to create a new Company alongside a new Person. So the SaveCompany calls introduce unnecessary database calls. When saving a Person I should just be able to update the CompanyId column.</p>
<p>But since the Person class has a Company property, I'm somewhat inclined to update / insert it with it. From a strict/pure point of view, the SavePerson method should save the entire Person.</p>
<p>What would the preferred way be? Just inserting/updating the CompanyId of the Company property when saving a Person or saving all of its data? Or would you create two distinct methods for both scenarios (What would you name them?)</p>
<p>Also, another question, I currently have distinct methods for saving a Person, an Address and a Company, so when I save a Company, I also call SaveAddress. Let's assume I use LinqToSql - this means that I don't insert/update the Company and the Address in the same Linq query. I guess there are 2 Select Calls (checking whether a company exists, checking whether an address exists). And then two Insert/Update calls for both. Even more if more compound model classes are introduced. Is there a way for LinqToSql to optimize these calls?</p>
<pre><code>public class Address
{
public int AddressId { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Company Company { get; set; }
public Address Address { get; set; }
}
</code></pre>
<p><strong>Edit</strong></p>
<p>Also see <a href="https://stackoverflow.com/questions/679005/how-are-value-objects-stored-in-the-database">this follow up question</a>. How are Value Objects stored in a Database?</p> | 675,416 | 2 | 2 | null | 2009-03-23 10:18:31.387 UTC | 10 | 2009-03-24 20:12:09.313 UTC | 2017-05-23 11:55:43.04 UTC | kitsune | -1 | kitsune | 13,466 | null | 1 | 9 | nhibernate|linq-to-sql|orm|domain-driven-design|ddd-repositories | 1,240 | <p>I myself have used the IRepository approach lately that Keith suggests. But, you should not be focusing on that pattern here. Instead, there are a few more pieces in the DDD playbook that can be applied here.</p>
<h2>Use <i>Value Objects</i> for your Addresses</h2>
<p>First, there is the concept of Value Objects (VO) you can apply here. In you case, it would be the Address. The difference between a Value Object and an Entity Object is that Entities have an identity; VOs do not. The VO's identity really is the sum of it's properties, not a unique identity. In the book <a href="https://rads.stackoverflow.com/amzn/click/com/1411609255" rel="noreferrer" rel="nofollow noreferrer">Domain-Drive Design Quickly</a> (it's also a free PDF download), he explains this very well by stating that an address is really just a point on Earth and does not need a separate SocialSecurity-like identity like a person. That point on Earth is the combination of the street, number, city, zip, and country. It can have latitude and longitude values, but still those are even VOs by definition because it's a combination of two points.</p>
<h2>Use <em>Services</em> for combining your entities into a single entity to act upon.</h2>
<p>Also, do not forget about the Services concept in the DDD playbook. In your example, that service would be:</p>
<pre><code>public class PersonCompanyService
{
void SavePersonCompany(IPersonCompany personCompany)
{
personRepository.SavePerson();
// do some work for a new company, etc.
companyRepository.SaveCompany();
}
}
</code></pre>
<p>There is a need for a service when you have two entities that need both need a similar action to coordinate a combination of other actions. In your case, saving a Person() and creating a blank Company() at the same time.</p>
<h2>ORMs usualyl require an identity, period.</h2>
<p>Now, how would you go about saving the Address VO in the database? You would use an IAddressRepository obviously. But since most ORMs (i.e. LingToSql) require all objects have an Identity, here's the trick: Mark the identity as internal in your model, so it is not exposed outside of your Model layer. This is Steven Sanderson's own advice.</p>
<pre><code>public class Address
{
// make your identity internal
[Column(IsPrimaryKey = true
, IsDbGenerated = true
, AutoSync = AutoSync.OnInsert)]
internal int AddressID { get; set; }
// everything else public
[Column]
public string StreetNumber { get; set; }
[Column]
public string Street { get; set; }
[Column]
public string City { get; set; }
...
}
</code></pre> |
1,311,578 | Opening multiple files (OpenFileDialog, C#) | <p>I'm trying to open multiple files at once with the <code>OpenFileDialog</code>, using <code>FileNames</code> instead of <code>FileName</code>. But I cannot see any examples anywhere on how to accomplish this, not even on MSDN. As far as I can tell - there's no documentation on it either. Has anybody done this before?</p> | 1,311,594 | 2 | 0 | null | 2009-08-21 12:09:56.373 UTC | 9 | 2020-05-11 11:03:57.793 UTC | 2014-08-06 16:50:20.24 UTC | null | 152,598 | null | 152,598 | null | 1 | 37 | c#|winforms|file|openfiledialog | 79,924 | <p>You must set the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.multiselect.aspx" rel="noreferrer"><code>OpenFileDialog.Multiselect</code></a> Property value to true, and then access the <code>OpenFileDialog.FileNames</code> property.</p>
<p>Check this sample</p>
<pre><code>private void Form1_Load(object sender, EventArgs e)
{
InitializeOpenFileDialog();
}
private void InitializeOpenFileDialog()
{
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
// ^ ^ ^ ^ ^ ^ ^
this.openFileDialog1.Title = "My Image Browser";
}
private void selectFilesButton_Click(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
try
{
PictureBox pb = new PictureBox();
Image loadedImage = Image.FromFile(file);
pb.Height = loadedImage.Height;
pb.Width = loadedImage.Width;
pb.Image = loadedImage;
flowLayoutPanel1.Controls.Add(pb);
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n" +
"Details (send to Support):\n\n" + ex.StackTrace
);
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
+ ". You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
}
}
</code></pre> |
2,552,371 | Setting java.awt.headless=true programmatically | <p>I'm trying to set <code>java.awt.headless=true</code> during the application startup but it appears like I'm too late and the non-headless mode has already started:</p>
<pre><code>static {
System.setProperty("java.awt.headless", "true");
/* java.awt.GraphicsEnvironment.isHeadless() returns false */
}
</code></pre>
<p>Is there another way set headless to true beside <code>-Djava.awt.headless=true</code>? I would prefer not configure anything on the console.</p> | 2,552,470 | 5 | 1 | null | 2010-03-31 11:17:03.753 UTC | 8 | 2019-12-19 11:49:16.3 UTC | 2017-11-10 06:29:19.693 UTC | null | 5,105,305 | null | 102,200 | null | 1 | 35 | java|awt|headless | 65,603 | <p>I was working with a <code>main()</code> in a class which statically loads different parts of JFreeChart in Constants (and other static code).</p>
<p>Moving the static loading block to the top of the class solved my problem.</p>
<p><strong>This doesn't work:</strong></p>
<pre><code> public class Foo() {
private static final Color COLOR_BACKGROUND = Color.WHITE;
static { /* too late ! */
System.setProperty("java.awt.headless", "true");
System.out.println(java.awt.GraphicsEnvironment.isHeadless());
/* ---> prints false */
}
public static void main() {}
}
</code></pre>
<p><strong>Have java execute the static block as early as possible by moving it to the top of the class!</strong></p>
<pre><code> public class Foo() {
static { /* works fine! ! */
System.setProperty("java.awt.headless", "true");
System.out.println(java.awt.GraphicsEnvironment.isHeadless());
/* ---> prints true */
}
private static final Color COLOR_BACKGROUND = Color.WHITE;
public static void main() {}
}
</code></pre>
<p>When thinking about it this makes perfectly sense :). Juhu!</p> |
3,203,286 | How to create a read-only class property in Python? | <p>Essentially I want to do something like this:</p>
<pre><code>class foo:
x = 4
@property
@classmethod
def number(cls):
return x
</code></pre>
<p>Then I would like the following to work: </p>
<pre><code>>>> foo.number
4
</code></pre>
<p>Unfortunately, the above doesn't work. Instead of given me <code>4</code> it gives me <code><property object at 0x101786c58></code>. Is there any way to achieve the above?</p> | 3,203,659 | 5 | 0 | null | 2010-07-08 12:00:12.16 UTC | 31 | 2020-05-21 17:45:37.88 UTC | null | null | null | null | 160,206 | null | 1 | 79 | python|class|properties | 41,009 | <p>The <code>property</code> descriptor always returns itself when accessed from a class (ie. when <code>instance</code> is <code>None</code> in its <code>__get__</code> method).</p>
<p>If that's not what you want, you can write a new descriptor that always uses the class object (<code>owner</code>) instead of the instance:</p>
<pre><code>>>> class classproperty(object):
... def __init__(self, getter):
... self.getter= getter
... def __get__(self, instance, owner):
... return self.getter(owner)
...
>>> class Foo(object):
... x= 4
... @classproperty
... def number(cls):
... return cls.x
...
>>> Foo().number
4
>>> Foo.number
4
</code></pre> |
2,375,372 | Is there a way to get all the querystring name/value pairs into a collection? | <p>Is there a way to get all the querystring name/value pairs into a collection?</p>
<p>I'm looking for a built in way in .net, if not I can just split on the & and load a collection.</p> | 2,375,380 | 6 | 0 | null | 2010-03-03 22:07:23.433 UTC | 7 | 2022-09-09 04:16:38.563 UTC | null | null | null | null | 39,677 | null | 1 | 58 | c#|asp.net|collections|query-string | 80,569 | <p>Yes, use the <a href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring.aspx" rel="noreferrer"><code>HttpRequest.QueryString</code></a> collection:</p>
<blockquote>
<p>Gets the collection of HTTP query string variables.</p>
</blockquote>
<p>You can use it like this:</p>
<pre><code>foreach (String key in Request.QueryString.AllKeys)
{
Response.Write("Key: " + key + " Value: " + Request.QueryString[key]);
}
</code></pre> |
2,792,819 | R dates "origin" must be supplied | <p>My code:</p>
<pre><code>axis.Date(1,sites$date, origin="1970-01-01")
</code></pre>
<p>Error:</p>
<blockquote>
<p>Error in as.Date.numeric(x) : 'origin' must be supplied</p>
</blockquote>
<p>Why is it asking me for the origin when I supplied it in the above code?</p> | 2,792,839 | 6 | 0 | null | 2010-05-08 03:18:59.59 UTC | 10 | 2022-02-11 12:38:12.877 UTC | 2022-02-11 12:38:12.877 UTC | null | 6,123,824 | null | 335,939 | null | 1 | 64 | r|date | 225,443 | <p>I suspect you meant:</p>
<pre><code>axis.Date(1, as.Date(sites$date, origin = "1970-01-01"))
</code></pre>
<p>as the 'x' argument to <code>as.Date()</code> has to be of type <code>Date</code>.</p>
<p>As an aside, this would have been appropriate as a follow-up or edit of your previous question.</p> |
2,531,952 | How to use a custom comparison function in Python 3? | <p>In <strong>Python 2.x</strong>, I could pass custom function to sorted and .sort functions</p>
<pre><code>>>> x=['kar','htar','har','ar']
>>>
>>> sorted(x)
['ar', 'har', 'htar', 'kar']
>>>
>>> sorted(x,cmp=customsort)
['kar', 'htar', 'har', 'ar']
</code></pre>
<p>Because, in <em>My</em> language, consonents are comes with this order</p>
<pre><code>"k","kh",....,"ht",..."h",...,"a"
</code></pre>
<p>But In <strong>Python 3.x</strong>, looks like I could not pass <code>cmp</code> keyword</p>
<pre><code>>>> sorted(x,cmp=customsort)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'cmp' is an invalid keyword argument for this function
</code></pre>
<p>Is there any alternatives or should I write my own sorted function too?</p>
<p><sub>Note: I simplified by using "k", "kh", etc. Actual characters are Unicodes and even more complicated, sometimes there is vowels comes before and after consonents, I've done custom comparison function, So that part is ok. Only the problem is I could not pass my custom comparison function to sorted or .sort</sub></p> | 2,531,971 | 6 | 4 | null | 2010-03-28 05:04:35.18 UTC | 20 | 2020-01-18 04:31:34.03 UTC | 2016-10-17 07:09:54.253 UTC | null | 355,230 | null | 213,464 | null | 1 | 124 | python|sorting|python-3.x | 88,512 | <p>Use the <code>key</code> argument (and follow the <a href="http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/" rel="noreferrer">recipe</a> on how to convert your old <code>cmp</code> function to a <code>key</code> function).</p>
<p><code>functools</code> has a function <code>cmp_to_key</code> mentioned at <a href="https://docs.python.org/3.6/library/functools.html#functools.cmp_to_key" rel="noreferrer">docs.python.org/3.6/library/functools.html#functools.cmp_to_key</a></p> |
3,041,441 | Should checkins be small steps or complete features? | <p>Two uses of version control seem to dictate different checkin styles.</p>
<ul>
<li><p><strong>distribution centric</strong>: changesets will generally reflect a complete feature. In general these checkins will be larger. This style is more user/maintainer friendly.</p></li>
<li><p><strong>rollback centric</strong>: changesets will be individual small steps so the history can function like an incredibly powerful undo. In general these checkins will be smaller. This style is more developer friendly.</p></li>
</ul>
<p>I like to use my version control as really powerful undo while while I banging away at some stubborn code/bug. In this way I'm not afraid to make drastic changes just to try out a possible solution. However, this seems to give me a fragmented file history with lots of "well that didn't work" checkins.</p>
<p>If instead I try to have my changeset reflect complete features I loose the use of my version control software for experimentation. However, it is much easier for user/maintainers to figure out how the code is evolving. Which has great advantages for code reviews, managing multiple branches, etc.</p>
<p>So what's a developer to do? Checkin small steps or complete features?</p> | 3,041,559 | 7 | 2 | null | 2010-06-14 22:41:08.847 UTC | 14 | 2010-06-15 01:16:40.443 UTC | 2010-06-14 22:58:04.797 UTC | null | 125,389 | null | 28,817 | null | 1 | 26 | git|mercurial|dvcs|bazaar | 1,074 | <p>The beauty of DVCS systems is that you can have <em>both</em>, because in a DVCS unlike a CVCS, <em>publishing</em> is orthogonal to <em>committing</em>. In a CVCS, every commit is automatically published, but it in a DVCS, commits are only published when they are <em>pushed</em>.</p>
<p>So, <em>commit</em> small steps, but only <em>publish</em> working features.</p>
<p>If you are worried about polluting your history, then you can rewrite it. You might have heard that rewriting history is evil, but that is not true: only rewriting <em>published</em> history is evil, but again, since publishing and committing are different, you can rewrite your unpublished history before publishing it.</p>
<p>This is how Linux development works, for example. Linus Torvalds is very concerned with keeping the history clean. In one of the very early e-mails about Git, he said that the published history should look not like you <em>actually</em> developed it, but how you <em>would have</em> developed it, if you were omniscient, could see into the future and never made any mistakes.</p>
<p>Now, Linux is a little bit special: it has commits going in at a rate of 1 commit every 11 minutes for 24 hours a day, 7 days a week, 365 days a year, including nights, weekends, holidays and natural disasters. And that rate is still increasing. Just imagine how much more commits there would be if every single typo and brainfart would result in a commit, too.</p>
<p>But the developers themselves in their private repositories commit however often they want.</p> |
3,091,010 | recv() socket function returning data with length as 0 | <p>I am having an application which established a socket connection on a port number 5005 with another device(hardware device with a web server). </p>
<p>Now if my hardware device disconnects then i loose connection with the device. </p>
<ol>
<li><p>Does this mean that the socket i was
using until now becomes invalid.</p></li>
<li><p>Do i get any special message like
null character or something when
this disconnect happens.</p></li>
<li>If the socket connection i was
having became invalid then why
doesnt the recv() socket function
throw and SOCKET_ERROR. Instead
why do i receive data of 0
length.</li>
</ol>
<p>Thanks</p> | 3,091,039 | 8 | 2 | null | 2010-06-22 07:14:31.23 UTC | 13 | 2020-07-29 20:24:09.737 UTC | 2018-06-27 02:28:46.203 UTC | null | 207,421 | null | 166,012 | null | 1 | 22 | c|sockets|tcp | 42,988 | <p>When <code>recv</code> returns a value of 0 that means the connection has been closed.</p>
<p>See the <a href="http://www.kernel.org/doc/man-pages/online/pages/man2/recv.2.html" rel="noreferrer"><code>recv</code> man page:</a></p>
<blockquote>
<p>These calls return the number of bytes received, or -1 if an error
occurred.
The return value will be 0 when the peer has performed an orderly
shutdown.</p>
</blockquote>
<p>In answer to question #1, yes the socket is now invalid. You must create a new socket and connection for further communications. </p>
<p><strong>Edit</strong></p>
<p>Now as valdo pointed out below, there is also the possibility of having a half-closed TCP connection in which you can't receive any more but you can keep writing to the socket until you've finished sending your data. See this article for more details: <a href="http://everything2.com/title/TCP+half-close" rel="noreferrer">TCP Half-Close</a>. It doesn't sound like you have this situation though.</p>
<p>In answer to question #2, there are basically two ways to detect a closed socket. This assumes that the socket went through an orderly shutdown, meaning the peer called either <code>shutdown</code> or <code>close</code>.</p>
<p>The first method is to read from the socket in which case you get a return value of 0. The other method is to write to the socket, which will cause the SIG_PIPE signal to be thrown indicating a broken pipe.</p>
<p>In order to avoid the signal, you can set the <code>MSG_NOSIGNAL</code> socket option in which case <a href="http://www.kernel.org/doc/man-pages/online/pages/man2/sendmsg.2.html" rel="noreferrer"><code>send</code></a> would return -1 and set <code>errno</code> to <code>EPIPE</code>. </p> |
33,531,334 | Convert directories with java files to java modules in intellij | <p>I recently switched to using IntelliJ. I manually imported some projects and I guess I didn't do it correctly. They are all supposed to be java modules but they are just regular directory folders. Is there a way to convert them to java modules so I can run the programs or will I have to manually recreate new modules?</p>
<p><a href="https://i.stack.imgur.com/zD2Re.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zD2Re.png" alt="enter image description here"></a></p> | 33,531,901 | 4 | 1 | null | 2015-11-04 20:25:37.273 UTC | 2 | 2021-07-07 12:14:46.097 UTC | 2018-11-21 21:33:00.073 UTC | null | 4,952,262 | null | 2,492,620 | null | 1 | 27 | java|intellij-idea | 38,865 | <p>There are a few ways to handle this. If your project has an existing build framework such as gradle, maven, etc, generally you can navigate to</p>
<p><code>File > New > Project From Existing Sources...</code></p>
<p>And then navigate to the gradle.build, pom.xml, or other framework specific build. When this project is created, all of the necessary source files should be properly identified.</p>
<p>Alternatively, you can also manually set the source directories by selecting the directory in the Project window, right clicking and selecting <code>Mark Directory As > Sources Root</code>.</p>
<p>See also:</p>
<ul>
<li><a href="https://www.jetbrains.com/idea/help/importing-project-from-maven-model.html" rel="noreferrer">Importing Project from Maven Model</a></li>
<li><a href="https://www.jetbrains.com/idea/help/importing-project-from-gradle-model.html" rel="noreferrer">Importing Project from Gradle Model</a></li>
<li><a href="https://www.jetbrains.com/idea/help/configuring-content-roots.html" rel="noreferrer">Configuring Content Roots</a></li>
</ul> |
13,947,472 | how to increment a value inside stored procedure | <p>How to increment a value of local variable in the loop inside a stored procedure</p>
<pre><code>ALTER PROC [dbo].[Usp_SelectQuestion]
@NoOfQuestion int
AS
BEGIN
Declare @CNT int
Declare @test int
Declare @x int
Declare @y int
set @x = 1;
set @y = 1;
Select @CNT=(Select Count(*) from (select Distinct(setno)from onlin) AS A)
select @test=@NoOfQuestion/@CNT
while @x <= @CNT do
while @y <= @test
select * from onlin where setno = @x
set @y = @y +1
set @x =@x + 1
END
</code></pre>
<p>the values like <code>@x</code> and <code>@y</code> is not incrementing and I am stuck in an infinite loop.</p> | 13,947,556 | 1 | 2 | null | 2012-12-19 07:28:34.62 UTC | null | 2012-12-19 07:35:41.33 UTC | 2012-12-19 07:33:21.713 UTC | null | 422,353 | null | 1,633,097 | null | 1 | 1 | sql|sql-server|stored-procedures | 44,449 | <p>you have to enclose the while-body in a begin-end block.</p>
<pre><code>while @x <= @CNT do begin
while @y <= @test begin
select * from onlin where setno = @x
set @y = @y + 1
end
set @x =@x + 1
end
</code></pre>
<p>I do not understand what you are trying to achive (besides the fact that you want to increase some variables)</p> |
10,418,404 | Create a DLL in C and link it from a C++ project | <p>As per title, I'm trying to build a DLL using C and link it from a C++ project. I read and followed different tutorials on internet but everytime there is something missing and I don't understand what. </p>
<p>Here's what I did, step by step: </p>
<p>I created a new Win32 project, named <code>testlib</code>, then, from the wizard, I chose "DLL" and "Empty project".</p>
<p>Added a header: </p>
<pre><code>//testlib.h
#include <stdio.h>
__declspec(dllexport) void hello();
</code></pre>
<p>Added a source; since I want it to be a C source I read I should simplly rename the .cpp file in .c, so</p>
<pre><code>//testlib.c
#include "testlib.h"
void hello() {
printf("DLL hello() called\n");
}
</code></pre>
<p>Build succeded. </p>
<p>Now I would like to use my useful dll in another project. </p>
<p>Then: new project (<code>testlibUse</code>). This time I selected "Empty project". <br>
No need to add an header, just created a cpp source</p>
<pre><code>//main.cpp
#include <testlib.h>
int main() {
hello();
}
</code></pre>
<p>Then:</p>
<ul>
<li><p>I added the path to the folder where is <code>testlib.dll</code> in Properties->VC++ directories->Executable directories</p></li>
<li><p>I added the path to the folder where is <code>testlib.h</code> in Properties->VC++ directories->Include directories</p></li>
<li><p>I added the path to <code>testlib.lib</code> (included extension) in Properties->Linker->Input->Additional dependencies</p></li>
</ul>
<p>I tried to build but I got a linker error:</p>
<blockquote>
<p>LINK : C:\path\testlibUse\Debug\testlibUse.exe not found or not built by the last incremental link; performing full link<br>
main.obj : error LNK2019: unresolved external symbol "void __cdecl hello(void)" (?hello@@YAXXZ) referenced in function _main<br>
C:\path\testlibUse\Debug\testlibUse.exe : fatal error LNK1120: 1 unresolved externals </p>
</blockquote>
<p>If I go back to <code>testlib</code>, rename back <code>testlib.c</code> in <code>testlib.cpp</code> and rebuild the dll, then I am able to build <code>testlibUse</code> but I get a "dll not found" error at runtime.</p>
<p>I tried also to change the configurations of both projects in "Release" (changing the path where needed), but nothing changed.</p>
<p>Sorry for the long post but I think it was necessary to write down exactly what I did.</p>
<p>Any suggestions?</p>
<p>Besides, are there any configuration parameters I need to change if I want to use my dll in a Qt project? </p> | 10,418,729 | 4 | 0 | null | 2012-05-02 17:03:01.767 UTC | 9 | 2012-05-02 17:26:46.097 UTC | null | null | null | null | 465,157 | null | 1 | 8 | c++|c|dll|linker | 10,513 | <p>You have several problems:</p>
<ol>
<li>The header file should mark the functions as exported when being compiled in the DLL but imported when being compiled by a library user.</li>
<li>The header file should wrap the function declarations in an <code>extern "C"</code> block when being compiled as C++ to ensure that the names do not get mangled</li>
<li>The DLL is not on your executable's library search path, so it can't be found at runtime.</li>
</ol>
<p>To fix (1) and (2), rewrite your header like this:</p>
<pre><code>#ifdef __cplusplus
extern "C" {
#endif
// Assume this symbol is only defined by your DLL project, so we can either
// export or import the symbols as appropriate
#if COMPILING_MY_TEST_DLL
#define TESTLIB_EXPORT __declspec(dllexport)
#else
#define TESTLIB_EXPORT __declspec(dllimport)
#endif
TESTLIB_EXPORT void hello();
// ... more function declarations, marked with TESTLIB_EXPORT
#ifdef __cplusplus
}
#endif
</code></pre>
<p>To fix (3), copy the DLL into the same folder as your executable file. The "executable directories" setting you're setting doesn't affect DLL searching -- see <a href="http://msdn.microsoft.com/en-us/library/7d83bc18%28v=vs.80%29.aspx">MSDN</a> for a detailed description of how DLLs are searched for. The best solution for you is to copy your DLL into the directory where your executable file lives. You can either do this manually, or add a post-build step to your project that does this for you.</p> |
5,641,427 | How to make preprocessor generate a string for __LINE__ keyword? | <p><code>__FILE__</code> is replaced with "MyFile.cpp" by C++ preprocessor.
I want <code>__LINE__</code> to be replaced with "256" string not with 256 integer.
Without using my own written functions like</p>
<pre><code>toString(__LINE__);
</code></pre>
<p>Is that possible? How can I do it?</p>
<p>VS 2008</p>
<p><strong>EDIT</strong> I'd like to automatically Find and Replace all <code>throw;</code> statements with </p>
<pre><code>throw std::runtime_error(std::string("exception at ") + __FILE__ + " "+__LINE__);
</code></pre>
<p>in my sources. If I use macro or function to convert <code>__LINE__</code> into a string I'll need to modify each source file manually.</p> | 5,641,470 | 2 | 2 | null | 2011-04-12 20:45:16.373 UTC | 7 | 2016-06-20 20:33:28.897 UTC | 2016-06-20 20:33:28.897 UTC | null | 4,370,109 | null | 490,529 | null | 1 | 32 | c++|visual-studio-2008|c-preprocessor | 10,153 | <p>You need the double expansion trick:</p>
<pre><code>#define S(x) #x
#define S_(x) S(x)
#define S__LINE__ S_(__LINE__)
/* use S__LINE__ instead of __LINE__ */
</code></pre>
<p>Addendum, years later: It is a good idea to go a little out of one's way to avoid operations that may allocate memory in exception-handling paths. Given the above, you should be able to write</p>
<pre><code>throw std::runtime_error("exception at " __FILE__ " " S__LINE__);
</code></pre>
<p>which will do the string concatenation at compile time instead of runtime. It will still construct a std::string (implicitly) at runtime, but that's unavoidable.</p> |
6,151,549 | How can I build a specific architecture using xcodebuild? | <p>I have legacy code that relies on pointers being <code>32-bit</code> and want to use <code>xCodeBuild</code> to build that code from <code>command line</code>. This doesn't work for some reason. Here's the command I use:</p>
<pre><code>xcodebuild -configuration Debug -arch i386
-workspace MyProject.xcworkspace -scheme MyLib
</code></pre>
<p>here's the output I get</p>
<pre><code>[BEROR]No architectures to compile for
(ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386).
</code></pre>
<p>Clearly it's trying to build <code>x86_64</code> code and failing miserably since I only enabled <code>i386</code> from <code>VALID_ARCHS</code> in xCode project settings.</p>
<p>Is there a way to make it understand I don't want a <code>64-bit</code> library?</p> | 6,154,460 | 2 | 0 | null | 2011-05-27 11:23:37.47 UTC | 11 | 2021-04-05 12:14:37.04 UTC | 2016-02-15 18:58:50.677 UTC | null | 299,674 | null | 686,184 | null | 1 | 35 | macos|command-line|xcode4|xcodebuild | 41,311 | <p>You have to set the <code>ONLY_ACTIVE_ARCH</code> to <code>NO</code> if you want <code>xcodebuild</code> to use the <code>ARCHS</code> parameters. By passing these parameters, you can force the proper architecture.</p>
<pre><code>xcodebuild ARCHS=i386 ONLY_ACTIVE_ARCH=NO -configuration Debug -workspace MyProject.xcworkspace -scheme MyLib
</code></pre>
<p>See <a href="http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html" rel="noreferrer">this reference</a> for details.</p> |
33,503,077 | Any difference between type assertions and the newer `as` operator in TypeScript? | <p>Is there any difference between what the TypeScript spec calls a type assertion:</p>
<pre><code>var circle = <Circle> createShape("circle");
</code></pre>
<p>And the <a href="https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#new-tsx-file-extension-and-as-operator" rel="noreferrer">newer</a> <code>as</code> operator:</p>
<pre><code>var circle = createShape("circle") as Circle;
</code></pre>
<p>Both of which are typically used for compile-time casting?</p> | 33,503,842 | 2 | 0 | null | 2015-11-03 15:35:16.48 UTC | 14 | 2019-11-27 19:41:44.077 UTC | null | null | null | null | 154,066 | null | 1 | 183 | casting|typescript | 57,007 | <p>The difference is that <code>as Circle</code> works in TSX files, but <code><Circle></code> conflicts with JSX syntax. <code>as</code> was introduced for this reason.</p>
<p>For example, the following code in a <code>.tsx</code> file:</p>
<pre><code>var circle = <Circle> createShape("circle");
</code></pre>
<p>Will result in the following error:</p>
<blockquote>
<p>error TS17002: Expected corresponding JSX closing tag for 'Circle'.</p>
</blockquote>
<p>However, <code>as Circle</code> will work just fine.</p>
<p>Use <code>as Circle</code> from now on. It's the <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-6.html#new-tsx-file-extension-and-as-operator" rel="noreferrer">recommended</a> syntax.</p> |
33,269,093 | How to add <canvas> support to my tests in Jest? | <p>In my <a href="https://facebook.github.io/jest/" rel="noreferrer">Jest</a> unit test I am rendering a component with a <a href="http://casesandberg.github.io/react-color/#usage-display" rel="noreferrer">ColorPicker</a>. The <code>ColorPicker</code> component creates a canvas object and 2d context but returns <code>'undefined'</code> which throws an error <code>"Cannot set property 'fillStyle' of undefined"</code></p>
<pre><code>if (typeof document == 'undefined') return null; // Dont Render On Server
var canvas = document.createElement('canvas');
canvas.width = canvas.height = size * 2;
var ctx = canvas.getContext('2d'); // returns 'undefined'
ctx.fillStyle = c1; // "Cannot set property 'fillStyle' of undefined"
</code></pre>
<p>I'm having troubles figuring out why I can't get a 2d context. Maybe there an issue with my test config?</p>
<pre><code>"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/node_modules/react-tools"
],
"moduleFileExtensions": [
"jsx",
"js",
"json",
"es6"
],
"testFileExtensions": [
"jsx"
],
"collectCoverage": true
}
</code></pre> | 33,278,679 | 11 | 0 | null | 2015-10-21 20:57:25.793 UTC | 3 | 2022-06-04 03:33:05.31 UTC | 2015-10-22 10:19:25.773 UTC | null | 115,493 | null | 448,967 | null | 1 | 43 | reactjs|html5-canvas|jsdom|jestjs | 40,921 | <p>It's because your test doesn't run in a real browser. Jest uses <code>jsdom</code> for mocking the necessary parts of the DOM to be able to run the tests in Node, thus avoiding style calculation and rendering that a browser would normally do. This is cool because this makes tests fast.</p>
<p>On the other hand, if you need browser APIs in your components, it's more difficult than in the browser. Luckily, <a href="https://github.com/jsdom/jsdom#canvas-support" rel="noreferrer"><code>jsdom</code> has support for canvas</a>. You just have to configure it:</p>
<blockquote>
<p>jsdom includes support for using the <a href="https://npmjs.org/package/canvas" rel="noreferrer">canvas</a> package to extend any <code><canvas></code> elements with the canvas API. To make this work, you need to include canvas as a dependency in your project, as a peer of jsdom. If jsdom can find the canvas package, it will use it, but if it's not present, then <code><canvas></code> elements will behave like <code><div></code>s.</p>
</blockquote>
<p>Alternatively, you could replace Jest with some browser-based test runner like <a href="http://karma-runner.github.io/" rel="noreferrer">Karma</a>. Jest is <a href="https://github.com/facebook/jest/issues/230#issuecomment-149841819" rel="noreferrer">pretty buggy</a> anyway.</p> |
33,076,495 | How can I fix this "Dropzone already attached" error? | <p>I have this sample:</p>
<p><a href="https://jsfiddle.net/rfv0afgf/3/" rel="noreferrer">link</a></p>
<p>I managed to create this form but unfortunately it does not work because I get error.</p>
<pre><code>Dropzone already attached.
</code></pre>
<p><strong>CODE HTML:</strong></p>
<pre><code><div class="dropzone dz-clickable" id="myDrop">
<div class="dz-default dz-message" data-dz-message="">
<span>Drop files here to upload</span>
</div>
</div>
</code></pre>
<p><strong>CODE JS:</strong></p>
<pre><code>Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#myDrop", { url: "/file/post"});
// If you use jQuery, you can use the jQuery plugin Dropzone ships with:
$("div#myDrop").dropzone({ url: "/file/post" });
</code></pre>
<p>I set up <code>Dropzone.autoDiscover = false;</code> but unfortunately still not working.</p>
<p>Can you please tell me what is causing this problem?</p> | 33,076,591 | 12 | 0 | null | 2015-10-12 08:28:43.427 UTC | 4 | 2021-04-26 04:24:42.81 UTC | 2019-05-20 03:25:44.067 UTC | null | 1,422,059 | null | 5,341,052 | null | 1 | 58 | javascript|jquery|html|dropzone.js | 100,095 | <p>You should use either </p>
<pre><code>var myDropzone = new Dropzone("div#myDrop", { url: "/file/post"});
</code></pre>
<p>or</p>
<pre><code>$("div#myDrop").dropzone({ url: "/file/post" });
</code></pre>
<p>not both. Basically what you are doing is calling the same thing twice.</p> |
23,218,929 | Check if selected dropdown value is empty using jQuery | <p>Here is the dropdown in question:</p>
<pre><code><select name="data" class="autotime" id="EventStartTimeMin">
<option value=""></option>
<option value="00">00</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</code></pre>
<p>What I want to do is check if the current value is empty:</p>
<pre><code>if ($("EventStartTimeMin").val() === "") {
// ...
}
</code></pre>
<p>But it does not work, even though the value is empty. Any help is much appreciated.</p> | 23,218,951 | 3 | 0 | null | 2014-04-22 12:01:51.203 UTC | 4 | 2019-08-09 09:47:47.647 UTC | 2016-04-21 20:57:31.143 UTC | null | 519,413 | null | 2,290,213 | null | 1 | 25 | jquery | 136,571 | <p>You forgot the <code>#</code> on the id selector:</p>
<pre><code>if ($("#EventStartTimeMin").val() === "") {
// ...
}
</code></pre> |
34,387,893 | Output matplotlib figure to SVG with text as text, not curves | <p>When I use <code>matplotlib.pyplot.savefig("test.svg", format="svg")</code> to export the figure as SVG, then the resulting SVG file is huge.</p>
<p>This is caused by the fact that there are a lot of text annotations in my figure, and each text ends up as paths in the SVG.</p>
<p>I want my text to end up as text strings in SVG, and not paths. It gets too hard to interpret the output too, if the text strings are exported this way.</p>
<p>Is there a way to force matplotlib to output text as text, not curves?</p>
<p>Currently, I see these code fragments in my SVG file: </p>
<pre><code><path d=" M9.8125 72.9062 L55.9062 72.9062 L55.9062 64.5938 L19.6719
64.5938 L19.6719 43.0156 L54.3906 43.0156 L54.3906 34.7188 L19.6719
34.7188 L19.6719 8.29688 L56.7812 8.29688 L56.7812 0 L9.8125 0 z "
id="DejaVuSans-45" />
</code></pre> | 35,734,729 | 1 | 0 | null | 2015-12-21 01:43:52.75 UTC | 15 | 2021-04-12 13:26:48.35 UTC | null | null | null | null | 301,166 | null | 1 | 43 | svg|matplotlib | 12,235 | <p>Matplotlibs SVG text rendering can be configured either in the matplotlibrc or in code.<br />
From <a href="https://matplotlib.org/stable/tutorials/introductory/customizing.html" rel="noreferrer">Customizing Matplotlib with style sheets and rcParams</a>:</p>
<pre class="lang-py prettyprint-override"><code>#svg.fonttype : 'path' # How to handle SVG fonts:
# 'none': Assume fonts are installed on the machine where the SVG will be viewed.
# 'path': Embed characters as paths -- supported by most SVG renderers
# 'svgfont': Embed characters as SVG fonts -- supported only by Chrome,
# Opera and Safari
</code></pre>
<p>This translates to the following code for neither embedding the font nor rendering the text as path:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
plt.rcParams['svg.fonttype'] = 'none'
</code></pre> |
21,503,588 | Bind HTML string with custom style | <p>I want to bind a HTML string with an custom style to the DOM. However <code>ngSanitize</code> removes the style from the string.</p>
<p>For example:</p>
<p><em>In the controller:</em></p>
<pre><code>$scope.htmlString = "<span style='color: #89a000'>123</span>!";
</code></pre>
<p><em>And in DOM:</em></p>
<pre><code><div data-ng-bind-html="htmlString"></div>
</code></pre>
<p>Will omit the style attribute. The result will look like:</p>
<pre><code><div data-ng-bind-html="htmlString"><span>123</span>!</div>
</code></pre>
<p>Instead of:</p>
<pre><code><div data-ng-bind-html="htmlString"><span style='color: #89a000'>123</span>!</div>
</code></pre>
<p><strong>Question:</strong> How can I achieve this?</p> | 28,502,961 | 5 | 0 | null | 2014-02-01 20:58:49.817 UTC | 10 | 2021-12-28 20:22:51.493 UTC | 2021-12-28 20:22:51.493 UTC | null | 1,127,428 | null | 1,717,562 | null | 1 | 47 | angularjs | 41,099 | <p>As already mentioned @Beyers, you have to use <code>$sce.trustAsHtml()</code>, to use it directly into the DOM, you could do it like this, JS/controller part:</p>
<pre><code>$scope.trustAsHtml = function(string) {
return $sce.trustAsHtml(string);
};
</code></pre>
<p>And in DOM/HTML part</p>
<pre><code><div data-ng-bind-html="trustAsHtml(htmlString)"></div>
</code></pre> |
53,260,312 | How SELECT ANY TABLE privilege work in Oracle? | <p>I would like to know how the privilege <code>SELECT ANY TABLE</code> works internally in Oracle.</p>
<p>Is it treated as a single privilege? Or is it equivalent to make a <code>GRANT SELECT ON MyTable TO MyUser</code> for each table?</p>
<p>As example, I would like to know if this work :</p>
<pre><code>GRANT SELECT ANY TABLE TO PUBLIC;
REVOKE ALL ON MY_TABLE FROM PUBLIC;
</code></pre>
<p>Would I still have access to <code>MY_TABLE</code> from any user after those queries?</p> | 53,260,699 | 1 | 1 | null | 2018-11-12 10:34:18.737 UTC | null | 2018-11-12 11:07:50.123 UTC | 2018-11-12 11:07:50.123 UTC | null | 7,147,233 | null | 4,730,196 | null | 1 | 3 | sql|oracle|privileges | 41,035 | <p>Yes, all users would still be able to query <code>MY_TABLE</code>.</p>
<p>You are looking at different <a href="https://docs.oracle.com/en/database/oracle/oracle-database/12.2/admqs/administering-user-accounts-and-security.html#GUID-289A4BF6-F703-4ED5-8357-89F651A6D1DE" rel="noreferrer">privilege types</a>:</p>
<blockquote>
<p>The main types of user privileges are as follows:</p>
<ul>
<li><strong>System privileges</strong>—A system privilege gives a user the ability to perform a particular action, or to perform an action on any schema objects of a particular type. For example, the system privilege <code>CREATE TABLE</code> permits a user to create tables in the schema associated with that user, and the system privilege <code>CREATE USER</code> permits a user to create database users.</li>
<li><strong>Object privileges</strong>—An objectprivilege gives a user the ability to perform a particular action on a specific schema object. Different object privileges are available for different types of schema objects. The privilege to select rows from the <code>EMPLOYEES</code> table or to delete rows from the <code>DEPARTMENTS</code> table are examples of object privileges.</li>
</ul>
</blockquote>
<p><a href="https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/GRANT.html#GUID-20B4E2C0-A7F8-4BC8-A5E8-BE61BDC41AC3__BABEFFEE" rel="noreferrer"><code>SELECT ANY TABLE</code></a> is a system privilege that allows the grantee to:</p>
<blockquote>
<p>Query tables, views, or materialized views in any schema except <code>SYS</code>. Obtain row locks using a <code>SELECT ... FOR UPDATE</code>. </p>
</blockquote>
<p>When you grant that it is a standalone single privilege, visible in <code>dba_sys_privs</code>. When Oracle decides if the user is allowed to access a table it can look first at system privleges, and only goes on to look for specific object privileges (visible in <code>dba_tab_privs</code>) if there isn't a system privilege that allows the action being performed.</p>
<p>System privileges are not translated into individual privileges on each object in the database - maintaining that would be horrible, as creating a new object would have to automatically figure out who should be granted privileges on it based on the system privilege; and it would mean that you couldn't tell the difference between that and individually granted privileges. So, for instance, if you explicitly granted select privs on a specific table, then the user was granted <code>SELECT ANY TABLE</code>, and then they had <code>SELECT ANY TABLE</code> revoked - what happens to the previous explicit grant?</p>
<p>Your scenario is basically the same, except you've specifed all privileges on the object to be revoked. If those are the only two commands involved then <code>PUBLIC</code> has no explicit privileges on <code>MY_TABLE</code> so revoking doesn't really do anything; but if any explicit privileges on that table had been granted then they would be revoked. That has no impact on the higher-level <code>SELECT ANY TABLE</code> system privileg though.</p>
<p>Privileges are cummulative; revoking a privilege on a specific object doesn't <em>block</em> access to that object, it just removes one possible access route.</p>
<p>Incidentally, hopefully you've used a contrived example, as such powerful system privileges should be granted sparingly and <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege" rel="noreferrer">only when really needed</a>. Letting any user query any table in your database potentially blows a big hole in the security model. Again <a href="https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/GRANT.html#GUID-20B4E2C0-A7F8-4BC8-A5E8-BE61BDC41AC3__I2062316" rel="noreferrer">from the docs</a>:</p>
<blockquote>
<p>Oracle recommends that you only grant the <code>ANY</code> privileges to trusted users</p>
</blockquote>
<p>and </p>
<blockquote>
<p>Oracle recommends against granting system privileges to <code>PUBLIC</code>.</p>
</blockquote>
<p>and read more in <a href="https://docs.oracle.com/en/database/oracle/oracle-database/12.2/dbseg/configuring-privilege-and-role-authorization.html#GUID-6F401301-B5EA-482E-9615-21FD840CAF60" rel="noreferrer">the database security guide</a>.</p> |
36,895,431 | Angular 2: pipes - How to format a phone number? | <p>I've searched here and there, and I am not able to find something specific about formatting a phone number.</p>
<p>Currently, I am retrieving phone numbers form a JSON in the following format: </p>
<p>25565115</p>
<p>However, I want to achieve this result:</p>
<p>02-55-65-115</p>
<p>For that, I believe that I need to use a custom pipe and I don't think that there is a built-in one that does it automatically.</p>
<p>Can you please give me some guidance on how to do so? </p> | 36,895,706 | 6 | 0 | null | 2016-04-27 16:17:13.61 UTC | 8 | 2022-06-07 19:29:31.577 UTC | 2020-03-16 19:57:09.327 UTC | null | 5,612,697 | null | 6,101,493 | null | 1 | 32 | angular|pipes-filters | 65,174 | <p><a href="https://stackblitz.com/edit/angular-g29gfr?file=src%2Fapp%2Fapp.component.ts" rel="noreferrer"><strong>StackBlitz</strong></a></p>
<p><code>pipe</code> implementation in <strong>TS</strong> would look like this</p>
<pre class="lang-ts prettyprint-override"><code>import { Pipe } from "@angular/core";
@Pipe({
name: "phone"
})
export class PhonePipe {
transform(rawNum) {
rawNum = rawNum.charAt(0) != 0 ? "0" + rawNum : "" + rawNum;
let newStr = "";
let i = 0;
for (; i < Math.floor(rawNum.length / 2) - 1; i++) {
newStr = newStr + rawNum.substr(i * 2, 2) + "-";
}
return newStr + rawNum.substr(i * 2);
}
}
</code></pre>
<hr>
<p>Declare the PhonePipe in your NgModule's declarations</p>
<hr>
<h2>Usage:</h2>
<pre class="lang-ts prettyprint-override"><code>import {Component} from 'angular/core';
@Component({
selector: "my-app",
template: `
Your Phone Number: <input [(ngModel)]="myNumber" />
<p>
Formatted Phone Number: <b>{{ myNumber | phone }}</b>
</p>
`
})
export class AppComponent {
myNumber = "25565115";
}
</code></pre>
<p>There are many things that can be improved, I just made it work for this particular case.</p> |
30,276,503 | Where to find a clear explanation about swift alert (UIAlertController)? | <p>Couldn't find a clear and informative explanation for this.</p> | 30,594,016 | 3 | 2 | null | 2015-05-16 13:51:12.737 UTC | 10 | 2018-03-12 00:43:38.153 UTC | 2016-01-26 12:26:09.59 UTC | null | 3,219,049 | null | 3,219,049 | null | 1 | 21 | ios|swift|dialog|uialertview|uialertcontroller | 28,774 | <p>After searching a while on a subject I didn't
find a clear explanation , even in it's class reference
<a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertController_class/index.html" rel="noreferrer">UIAlertController Reference</a></p>
<p>It is ok, but not clear enough for me.</p>
<p>So after collecting some peaces I decided to make my own explanation
(Hope it helps) </p>
<p>So here it goes:</p>
<ol>
<li><code>UIAlertView</code> is deprecated as pointed out :
<a href="https://stackoverflow.com/questions/24022479/how-would-i-create-a-uialertview-in-swift">UIAlertView in Swift</a></li>
<li><code>UIAlertController</code> should be used in iOS8+
so to create one first we need to instantiate it,
the Constructor(init) gets 3 parameters: </li>
</ol>
<p>2.1 title:String -> big-bold text to display on the top of alert's dialog box</p>
<p>2.2 message:String -> smaller text (pretty much explains it's self)</p>
<p>2.3 <code>prefferedStyle:UIAlertControllerStyle</code> -> define the dialog box style, in most cases: <code>UIAlertControllerStyle.Alert</code></p>
<ol start="3">
<li><p>Now to actually show it to the user, we can use <a href="https://developer.apple.com/reference/uikit/uiviewcontroller/1621377-show" rel="noreferrer"><code>showViewController</code></a> or <a href="https://developer.apple.com/reference/uikit/uiviewcontroller/1621380-present" rel="noreferrer"><code>presentViewController</code></a> and pass our alert as parameter</p></li>
<li><p>To add some interaction with a user we can use:</p></li>
</ol>
<p>4.1
<code>UIAlertController.addAction</code> to create buttons</p>
<p>4.2
<code>UIAlertController.addTextField</code> to create text fields</p>
<p><strong>Edit note:</strong> code examples below, updated for swift 3 syntax</p>
<p><strong>Example 1</strong>: Simple Dialog</p>
<pre><code>@IBAction func alert1(sender: UIButton) {
//simple alert dialog
let alert=UIAlertController(title: "Alert 1", message: "One has won", preferredStyle: UIAlertControllerStyle.alert);
//show it
show(alert, sender: self);
}
</code></pre>
<p><strong>Example 2</strong>: Dialog with one input textField & two buttons</p>
<pre><code>@IBAction func alert2(sender: UIButton) {
//Dialog with one input textField & two buttons
let alert=UIAlertController(title: "Alert 2", message: "Two will win too", preferredStyle: UIAlertControllerStyle.alert);
//default input textField (no configuration...)
alert.addTextField(configurationHandler: nil);
//no event handler (just close dialog box)
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil));
//event handler with closure
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in
let fields = alert.textFields!;
print("Yes we can: "+fields[0].text!);
}));
present(alert, animated: true, completion: nil);
}
</code></pre>
<p><strong>Example 3</strong>: One customized input textField & one button</p>
<pre><code>@IBAction func alert3(sender: UIButton) {
// one input & one button
let alert=UIAlertController(title: "Alert 3", message: "Three will set me free", preferredStyle: UIAlertControllerStyle.alert);
//configured input textField
var field:UITextField?;// operator ? because it's been initialized later
alert.addTextField(configurationHandler:{(input:UITextField)in
input.placeholder="I am displayed, when there is no value ;-)";
input.clearButtonMode=UITextFieldViewMode.whileEditing;
field=input;//assign to outside variable(for later reference)
});
//alert3 yesHandler -> defined in the same scope with alert, and passed as event handler later
func yesHandler(actionTarget: UIAlertAction){
print("YES -> !!");
//print text from 'field' which refer to relevant input now
print(field!.text!);//operator ! because it's Optional here
}
//event handler with predefined function
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: yesHandler));
present(alert, animated: true, completion: nil);
}
</code></pre>
<p><strong>Hope It helps, and good luck ;-)</strong></p> |
8,538,427 | How to delete all contents of a folder with Ruby-Rails? | <p>I have a <code>public/cache</code> folder which has files and folders. How can I completely empty that folder using a rake task?</p> | 8,538,489 | 3 | 0 | null | 2011-12-16 18:19:46.163 UTC | 8 | 2020-09-13 16:44:45.843 UTC | 2014-05-22 10:21:13.613 UTC | null | 3,279,009 | null | 1,041,669 | null | 1 | 74 | ruby|ruby-on-rails-3 | 41,932 | <p>Ruby has the *nix <code>rm -rf</code> equivalent in the <a href="http://ruby-doc.org/stdlib/libdoc/fileutils/rdoc/FileUtils.html" rel="noreferrer">FileUtils</a> module that you can use to delete both files and non-empty folders/directories:</p>
<pre><code>FileUtils.rm_rf('dir/to/remove')
</code></pre>
<p>To keep the directory itself and only remove its contents:</p>
<pre><code>FileUtils.rm_rf(Dir.glob('dir/to/remove/*'))
FileUtils.rm_rf(Dir['dir/to/remove/*']) # shorter version of above
</code></pre> |
8,556,604 | Is there a way to use two CSS3 box shadows on one element? | <p>I'm trying to replicate a button style in a Photoshop mock-up that has two shadows on it. The first shadow is an inner lighter box shadow (2px), and the second is a drop shadow outside the button (5px) itself.</p>
<p><a href="https://i.stack.imgur.com/GF895.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GF895.png" alt="enter image description here"></a></p>
<p>In Photoshop this is easy - Inner Shadow and Drop Shadow. In CSS I can apparently have one or the other, but not both at the same time.</p>
<p>If you try the code below in a browser, you'll see that the box-shadow overrides the inset box-shadow.</p>
<p>Here's the inset box shadow:</p>
<pre><code>box-shadow: inset 0 2px 0px #dcffa6;
</code></pre>
<p>And this is what I would like for the drop shadow on the button:</p>
<pre><code>box-shadow: 0 2px 5px #000;
</code></pre>
<p>For context, here's my full button code (with gradients and all):</p>
<pre><code>button {
outline: none;
position: relative;
width: 160px;
height: 40px;
font-family: 'Open Sans', sans-serif;
color: #fff;
font-weight: 800;
font-size: 12px;
text-shadow: 0px 1px 3px black;
border-radius: 3px;
background-color: #669900;
background: -webkit-gradient(linear, left top, left bottom, from(#97cb52), to(#669900));
background: -moz-linear-gradient(top, #97cb52, #669900);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#97cb52', endColorstr='#669900');
box-shadow: inset 0 2px 0px #dcffa6;
box-shadow: 0 2px 5px #000;
border: 1px solid #222;
cursor: pointer;
}
</code></pre> | 8,556,627 | 2 | 0 | null | 2011-12-19 02:41:50.54 UTC | 25 | 2017-06-18 07:46:42.307 UTC | 2017-06-18 07:46:42.307 UTC | null | 1,143,732 | null | 1,105,159 | null | 1 | 184 | css | 142,734 | <p>You can comma-separate shadows:</p>
<pre class="lang-css prettyprint-override"><code>box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
</code></pre> |
27,290,354 | ReactJS server-side rendering vs client-side rendering | <p>I just have began to study ReactJS and found that it gives you 2 ways to render pages: server-side and client-side. But, I can't understand how to use it together. Is it 2 separate ways to build the application, or can they be used together? </p>
<p>If we can use it together, how to do it - do we need to duplicate the same elements on the server side and client side? Or, can we just build the static parts of our application on the server, and the dynamic parts on the client side, without any connection to the server side that was already pre-rendered?</p> | 27,291,188 | 4 | 1 | null | 2014-12-04 09:25:38.62 UTC | 53 | 2022-08-20 09:03:27.41 UTC | 2016-03-26 18:07:34.197 UTC | null | 385,273 | null | 1,640,210 | null | 1 | 153 | javascript|node.js|client-server|reactjs | 80,590 | <p>For a given website / web-application, you can use react either <em>client-side</em>, <em>server-side</em> or <em>both</em>.</p>
<h3>Client-Side</h3>
<p>Over here, you are completely running ReactJS on the browser. This is the simplest setup and includes most examples (including the ones on <a href="http://reactjs.org" rel="noreferrer">http://reactjs.org</a>). The initial HTML rendered by the server is a placeholder and the entire UI is rendered in the browser once all your scripts load.</p>
<h3>Server-Side</h3>
<p>Think of ReactJS as a server-side templating engine here (like jade, handlebars, etc...). The HTML rendered by the server contains the UI as it should be and you do not wait for any scripts to load. Your page can be indexed by a search engine (if one does not execute any javascript).</p>
<p>Since the UI is rendered on the server, none of your event handlers would work and there's no interactivity (you have a static page).</p>
<h3>Both</h3>
<p>Here, the initial render is on the server. Hence, the HTML received by the browser has the UI as it should be. Once the scripts are loaded, the virtual DOM is re-rendered once again to set up your components' event handlers.</p>
<p>Over here, you need to make sure that you re-render the exact same virtual DOM (root ReactJS component) with the same <code>props</code> that you used to render on the server. Otherwise, ReactJS will complain that the server-side and client-side virtual DOMs don't match.</p>
<p>Since ReactJS diffs the virtual DOMs between re-renders, the real DOM is not mutated. Only the event handlers are bound to the real DOM elements.</p> |
1,307,512 | How to export an entire Access database to SQL Server? | <p>I've just got a lovely Access database, so the first thing I want to do is to move it over to a normal database management system (sqlexpress), but the <a href="http://hosting.intermedia.net/support/kb/default.asp?id=576" rel="nofollow noreferrer">only solution</a> I've found sounds like craziness. </p>
<p>Isn't there an "<em>export database to .sql</em>" button somewhere? I have around 50 tables and this export might run more than once so it would be great if I didn't have to export all the tables manually. Generating a .sql file (with tables creation and inserts) would also be great since it would allow me to keep that under version control.</p>
<p>I guess if it's not possible to do something simple like this I'd appreciate any pointers to do something similar.</p> | 1,307,541 | 3 | 0 | null | 2009-08-20 16:54:11.15 UTC | 4 | 2021-01-19 06:53:29.583 UTC | 2015-01-28 10:42:16.75 UTC | null | 4,116,112 | null | 90,691 | null | 1 | 12 | ms-access|export|sql-server-express | 55,856 | <p>Is there a reason you don't want to use Management Studio and specify Microsoft Access as the data source for your Import Data operation? (Database->Tasks->Import, Microsoft Access as data source, mdb file as parameter). Or is there a reason it must be done from within Microsoft Access?</p> |
638,361 | Nullable Method Arguments in C# | <p><strong>Duplicate Question</strong></p>
<p><a href="https://stackoverflow.com/questions/271588/passing-null-arguments-to-c-methods/271600">Passing null arguments to C# methods</a></p>
<p>Can I do this in c# for .Net 2.0?</p>
<pre><code>public void myMethod(string astring, int? anint)
{
//some code in which I may have an int to work with
//or I may not...
}
</code></pre>
<p>If not, is there something similar I can do?</p> | 638,369 | 3 | 1 | null | 2009-03-12 12:16:17.997 UTC | 2 | 2009-03-12 12:27:21.107 UTC | 2017-05-23 10:29:18.923 UTC | Longhorn213 | -1 | One Monkey | null | null | 1 | 22 | c#|arguments|nullable | 94,773 | <p>Yes, assuming you added the chevrons deliberately and you really meant:</p>
<pre><code>public void myMethod(string astring, int? anint)
</code></pre>
<p><code>anint</code> will now have a <code>HasValue</code> property.</p> |
1,269,506 | Selecting a UITableViewCell in Edit mode | <p>If I create a UITableViewController - drilling down works as expected. If a user selects a cell and I implement 'didSelectRowAtIndexPath', the cell flashes blue and the next view shows up.</p>
<p>But, if I include an 'edit' button (self.navigationItem.rightBarButtonItem = self.editButtonItem), when the user clicks 'Edit' - the mode correctly changes (all the cells indent and paint an appropriate editingAccessory), ... BUT, the cells are no long 'selectable'. </p>
<p>IE: while in edit mode, when a user selects a cell, nothing is happening. No blue flash. No invocation of 'didSelectRowAtIndexPath', nothing.</p>
<p>When I open the iPhone example 'iPhoneCoreDataRecipes' (as provided in the SDK docs), sure enough, they have a RecipeDetailViewController - that, when put into edit mode, still allows you to drill down. I've downloaded and built their example and it works just fine. I can't seem to find any trickery in their code to enable this 'selectable cell when in edit mode behavior' but I'm just not getting it when I do it.</p>
<p>Thoughts?</p>
<p>Thanks for any time,</p>
<p>-Luther</p> | 1,269,730 | 3 | 0 | null | 2009-08-13 00:51:08.18 UTC | 3 | 2014-09-02 12:11:06.067 UTC | null | null | null | null | 4,910 | null | 1 | 29 | iphone|uitableview | 11,325 | <p>UITableView has a property <a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UITableView_Class/Reference/Reference.html#//apple_ref/occ/instp/UITableView/allowsSelectionDuringEditing" rel="noreferrer">allowsSelectionDuringEditing</a> for this.</p>
<p>IMHO it should have been YES by default.</p> |
22,195,093 | Android how to get tomorrow's date | <p>In my android application. I need to display tomorrow's date, for example today is 5th March so I need to display as 6 March. I know the code for getting today's date, month and year.</p>
<p>date calculating</p>
<pre><code> GregorianCalendar gc = new GregorianCalendar();
yearat = gc.get(Calendar.YEAR);
yearstr = Integer.toString(yearat);
monthat = gc.get(Calendar.MONTH) + 1;
monthstr = Integer.toString(monthat);
dayat = gc.get(Calendar.DAY_OF_MONTH);
daystr = Integer.toString(dayat);
</code></pre>
<p>If I have the code</p>
<pre><code>dayat = gc.get(Calendar.DAY_OF_MONTH) + 1;
</code></pre>
<p>will it display tomorrow's date. or just add one to today's date? For example, if today is January 31. With the above code, will it display like 1 or 32? If it displays 32, what change I need to make?</p> | 22,195,142 | 16 | 0 | null | 2014-03-05 10:30:37.567 UTC | 12 | 2021-06-29 22:38:15.15 UTC | 2018-04-04 10:23:41.257 UTC | null | 9,209,546 | null | 3,180,759 | null | 1 | 36 | java|android|calendar | 56,448 | <ol>
<li><p>Get today's date as a <code>Calendar</code>.</p></li>
<li><p>Add 1 day to it.</p></li>
<li><p>Format for display purposes.</p></li>
</ol>
<p>For example,</p>
<pre><code>GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);
// now do something with the calendar
</code></pre> |
6,661,179 | VS Designer question. How to change parent control | <p>VS beginner question. How to change parent control of a control? Example. I have TabControl on form, aligned to fit the all form. I have double clicked of toolStrip control to create menu and instead of the form toolStrip was added to TabControl. How to move toolStrip from the TabControl to the Form. I can use copy/paste but that not always works. </p> | 6,664,636 | 1 | 0 | null | 2011-07-12 08:08:26.06 UTC | 3 | 2011-07-12 13:08:30.69 UTC | null | null | null | null | 281,014 | null | 1 | 30 | visual-studio-2010|user-controls | 8,738 | <p>In the menu select View -> Other Windows -> Document Outline. In that window you see the hierarchical view of your components. Drag the controls to their new parent.</p> |
42,043,611 | Could not load the default credentials? (Node.js Google Compute Engine tutorial) | <p><strong>SITUATION:</strong></p>
<p>I follow this tutorial: <a href="https://cloud.google.com/nodejs/tutorials/bookshelf-on-compute-engine" rel="noreferrer">https://cloud.google.com/nodejs/tutorials/bookshelf-on-compute-engine</a></p>
<p>Everything works fine until I do <code>npm start</code> and go to:</p>
<p><a href="http://localhost:8080" rel="noreferrer">http://localhost:8080</a></p>
<p>I am met with the following text on the blank page:</p>
<pre><code>Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.
</code></pre>
<p>Which makes no sense since I am using OAuth. I followed the link and read the page, but I have no <code>GOOGLE-APPLICATION-CREDENTIALS</code> field anywhere, and nothing about it in the tutorial.</p>
<hr>
<p><strong>QUESTION:</strong></p>
<p>Could you please reproduce the steps and tell me if you get the same result ?</p>
<p>(takes 5 minutes)</p>
<p>If not, what could I have done wrong ?</p> | 42,059,661 | 17 | 1 | null | 2017-02-04 17:56:05.53 UTC | 19 | 2021-11-04 15:49:13.573 UTC | 2017-02-04 18:02:46.803 UTC | null | 6,230,185 | null | 6,230,185 | null | 1 | 92 | javascript|node.js|google-cloud-platform|google-compute-engine | 105,375 | <p>Yes, I had the same error. It's annoying cause Google Cloud Platform docs for their "getting started" bookshelf tutorial does not mention this anywhere. Which means that any new developer who tries this tutorial will see this error.</p>
<p>Read this:
<a href="https://developers.google.com/identity/protocols/application-default-credentials" rel="noreferrer">https://developers.google.com/identity/protocols/application-default-credentials</a></p>
<p>I fixed this issue by running:
<code>gcloud auth application-default login</code></p>
<p>In order to run this<code>gcloud auth application-default login</code>
Visit: <a href="https://cloud.google.com/sdk/install" rel="noreferrer">https://cloud.google.com/sdk/install</a>
1) You have to install sdk into your computer
2) That will enable you to run the code
3) Log in to your associated gmail account then you are good to go! </p>
<p>This will make you login, and after that you code locally will use that authentication.</p> |
20,449,543 | Shell equality operators (=, ==, -eq) | <p>What is the difference between <code>=</code>, <code>==</code> and <code>-eq</code> in shell scripting?</p>
<p>Is there any difference between the following?</p>
<pre><code>[ $a = $b ]
[ $a == $b ]
[ $a -eq $b ]
</code></pre>
<p>Is it simply that <code>=</code> and <code>==</code> are only used when the variables contain numbers?</p> | 20,449,556 | 4 | 0 | null | 2013-12-08 03:29:58.933 UTC | 58 | 2022-05-28 23:34:46.73 UTC | 2021-11-26 23:56:12.473 UTC | null | 63,550 | null | 2,845,038 | null | 1 | 258 | bash|shell | 367,809 | <p><code>=</code> and <code>==</code> are for string comparisons<br />
<code>-eq</code> is for numeric comparisons<br />
<code>-eq</code> is in the same family as <code>-lt</code>, <code>-le</code>, <code>-gt</code>, <code>-ge</code>, and <code>-ne</code></p>
<p><code>==</code> is specific to bash (not present in sh (Bourne shell), ...). Using POSIX <code>=</code> is preferred for compatibility. In bash the two are equivalent, and in sh <code>=</code> is the only one that will work.</p>
<pre><code>$ a=foo
$ [ "$a" = foo ]; echo "$?" # POSIX sh
0
$ [ "$a" == foo ]; echo "$?" # bash-specific
0
$ [ "$a" -eq foo ]; echo "$?" # wrong
-bash: [: foo: integer expression expected
2
</code></pre>
<p>(Note: make sure to quote the variable expansions. Do not leave out the double-quotes above.)</p>
<p>If you're writing a <code>#!/bin/bash</code> script then I recommend <a href="https://stackoverflow.com/questions/3427872/whats-the-difference-between-and-in-bash">using <code>[[</code> instead</a>. The double square-brackets <code>[[...]]</code> form has more features, a more natural syntax, and fewer gotchas that will trip you up. For example, double quotes are no longer required around <code>$a</code>:</p>
<pre><code>$ [[ $a == foo ]]; echo "$?" # bash-specific
0
</code></pre>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/3427872/whats-the-difference-between-and-in-bash">What's the difference between [ and [[ in Bash?</a></li>
</ul> |
36,125,038 | Generate array of times (as strings) for every X minutes in JavaScript | <p>I'm trying to create an array of times (strings, not <code>Date</code> objects) for every X minutes throughout a full 24 hours. For example, for a 5 minute interval the array would be:</p>
<pre><code>['12:00 AM', '12:05 AM', '12:10 AM', '12:15 AM', ..., '11:55 PM']
</code></pre>
<p>My quick and dirty solution was to use 3 nested <code>for</code> loops:</p>
<pre><code>var times = []
, periods = ['AM', 'PM']
, hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
, prop = null
, hour = null
, min = null;
for (prop in periods) {
for (hour in hours) {
for (min = 0; min < 60; min += 5) {
times.push(('0' + hours[hour]).slice(-2) + ':' + ('0' + min).slice(-2) + " " + periods[prop]);
}
}
}
</code></pre>
<p>This outputs the desired result but I'm wondering if there's a more elegant solution. Is there a way to do this that's:</p>
<ul>
<li>more readable</li>
<li>less time complex</li>
</ul> | 36,126,706 | 15 | 2 | null | 2016-03-21 07:13:17.543 UTC | 14 | 2021-09-10 21:17:04.54 UTC | 2018-08-17 17:35:01.563 UTC | null | 438,581 | null | 438,581 | null | 1 | 46 | javascript|arrays | 61,822 | <p>If the interval is only to be set in minutes[0-60], then evaluate the below solution w/o creating the date object and in single loop:</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-js lang-js prettyprint-override"><code>var x = 5; //minutes interval
var times = []; // time array
var tt = 0; // start time
var ap = ['AM', 'PM']; // AM-PM
//loop to increment the time and push results in array
for (var i=0;tt<24*60; i++) {
var hh = Math.floor(tt/60); // getting hours of day in 0-24 format
var mm = (tt%60); // getting minutes of the hour in 0-55 format
times[i] = ("0" + (hh % 12)).slice(-2) + ':' + ("0" + mm).slice(-2) + ap[Math.floor(hh/12)]; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt = tt + x;
}
console.log(times);</code></pre>
</div>
</div>
</p> |
20,256,909 | Django: How to write query to sort using multiple columns, display via template | <p>I'm quite new to Django, and not too experienced with MVC, DB queries. </p>
<p>I have a Customer table which includes customer_name, city_name, as well as a state_name (pulled from a foreign key table). In the HTML, I'm trying to display the results in a list first sorted alphabetically by state_name, then by city_name, then by customer_name name. Like so..</p>
<pre><code>ARIZONA
PHOENIX
AAA, Inc.
BBB, LLC.
SCOTTSDALE
AAA, LLC.
DDD, Corp.
CALIFORNIA
ANAHEIM
...
</code></pre>
<p>My model.py is as follows:</p>
<pre><code>from django.db import models
class Customer(models.Model):
def __unicode__(self):
return self.customer_name
customer_name = models.CharField(max_length=60)
city_name = models.CharField(max_length=30)
state = models.ForeignKey('State')
class State(models.Model):
def __unicode__(self):
return self.state_name
state_name = models.CharField(max_length=20)
state_code = models.CharField(max_length=2)
</code></pre>
<p>In my urls.py, I have:</p>
<pre><code>url("^customers/$",
direct_to_template,
{'template': 'pages_fixed/customers.html',
'extra_context': {'customers': Customer.objects.all().order_by('state')}},
name='customers'),
</code></pre>
<p>And in my HTML, I have a working template as:</p>
<pre><code> <div class='customers'>
{% for customer in customers %}
<div class='block_customer'>
<p>{{ customer.state.state_name }}</p>
<p>{{ customer.city_name }}</p>
<p>{{ customer.customer_name }}</p>
</div>
{% endfor %}
</div>
</code></pre>
<p>It's all sort of working but obviously not sorting correctly and I'm not sure what's the best way to design it. I tried some inner loops with the templates, was hoping the templates would let me define some sorting rules but this doesn't seem to be supported/correct. I suspect that I need to query the data differently or pre-sort them in code ahead of time? I'm not sure if this would be done in the View (what is Django's form of Controller?).. If anyone could point me in the right direction, that would be MUCH appreciated! </p> | 20,257,999 | 3 | 0 | null | 2013-11-28 02:56:54.33 UTC | 6 | 2018-08-06 05:35:55.29 UTC | 2013-11-28 06:08:16.813 UTC | null | 952,112 | null | 2,316,803 | null | 1 | 37 | python|django|postgresql|sorting|django-queryset | 39,560 | <p>There are several levels for display ordered models objects in template, each one overwrite the previous level:</p>
<ol>
<li><strong>(MODEL LEVEL) Meta attribute <code>ordering</code></strong> as shows @Bithin in his answer (<em>more on <a href="https://docs.djangoproject.com/en/dev/ref/models/options/#django.db.models.Options.ordering" rel="noreferrer">django docs</a></em>)</li>
<li><p><strong>(VIEW LEVEL) QuerySet <code>order_by</code> method</strong> as you have tried in your view example, which would works
as you want if add other fields to sort:</p>
<p><code>Customer.objects.order_by('state', 'city_name', 'customer_name')</code></p>
<p>(<em>more on <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by" rel="noreferrer">django docs</a></em>). <em>Note that <code>.all()</code> is not needed here.</em></p></li>
<li><strong>(TEMPLATE LEVEL) <code>regroup</code> template tag</strong> need to use nested in your sample (<em>more on <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup" rel="noreferrer">django docs</a></em>)</li>
</ol> |
5,681,868 | Efficient BigDecimal round Up and down to two decimals | <p>In java am trying to find an efficient way to round a BigDecimal to two decimals, Up or Down based on a condition.</p>
<pre><code> IF condition true then:
12.390 ---> 12.39
12.391 ---> 12.40
12.395 ---> 12.40
12.399 ---> 12.40
If condition false then:
12.390 ---> 12.39
12.391 ---> 12.39
12.395 ---> 12.39
12.399 ---> 12.39
</code></pre>
<p>What is the most efficient way to accomplish this? </p> | 5,681,953 | 3 | 2 | null | 2011-04-15 20:12:01.993 UTC | 2 | 2011-04-15 23:17:10.063 UTC | null | null | null | null | 47,508 | null | 1 | 12 | java|rounding|bigdecimal | 53,897 | <pre><code>public static BigDecimal round(BigDecimal d, int scale, boolean roundUp) {
int mode = (roundUp) ? BigDecimal.ROUND_UP : BigDecimal.ROUND_DOWN;
return d.setScale(scale, mode);
}
round(new BigDecimal("12.390"), 2, true); // => 12.39
round(new BigDecimal("12.391"), 2, true); // => 12.40
round(new BigDecimal("12.391"), 2, false); // => 12.39
round(new BigDecimal("12.399"), 2, false); // => 12.39
</code></pre> |
5,981,162 | list of users and roles that have permissions to an object (table) in SQL | <p>You'd think I'd be able to Google such a simple question. But no matter what I try, I hit a brick wall.</p>
<p>What is the TSQL statement to find a list of roles that have permissions to a table?</p>
<p>The pseudo-code looks like this:</p>
<pre><code>SELECT role_name
FROM permissions
where object_name = 'the_table_i_need_to_know_about'
</code></pre> | 6,021,753 | 3 | 0 | null | 2011-05-12 16:20:27.4 UTC | 4 | 2016-06-06 20:55:05.567 UTC | 2013-02-21 16:42:42.08 UTC | null | 44,853 | null | 200,669 | null | 1 | 19 | sql|tsql|permissions|azure-sql-database | 71,615 | <p>It's a bit tricky. First, remember that the built-in roles have pre-defined access; these won't show up in the query below. The proposed query lists custom database roles and which access they were specifically granted or denied. Is this what you were looking for?</p>
<pre><code>select permission_name, state_desc, type_desc, U.name, OBJECT_NAME(major_id)
from sys.database_permissions P
JOIN sys.tables T ON P.major_id = T.object_id
JOIN sysusers U ON U.uid = P.grantee_principal_id
</code></pre> |
5,930,671 | Why use $HOME over ~ (tilde) in a shell script? | <p>Is there any reason to use the variable <code>$HOME</code> instead of a simple <code>~</code> (tilde) in a shell script?</p> | 5,930,680 | 3 | 0 | null | 2011-05-08 22:04:47.813 UTC | 7 | 2021-09-16 17:50:41.813 UTC | 2021-09-16 17:50:41.813 UTC | null | 967,621 | null | 480,993 | null | 1 | 38 | shell|scripting|environment-variables|home-directory|tilde-expansion | 7,099 | <p>Tilde expansion doesn't work in some situations, like in the middle of strings like <code>/foo/bar:~/baz</code></p> |
5,990,089 | Jquery - Select td value for all the tr with a class | <p>I have a table</p>
<pre><code><table>
<tr class="PO1"></tr>
<tr class="PO2"></tr>
<tr class="PO3"></tr>
</table>
</code></pre>
<p>How can I loop through all tr with class <code>"PO1"</code> and get the value of each <code>'td'</code> value?</p>
<pre><code>$("table#id tr .PO1").each(function(i)
{
// how to get the td values??
});
</code></pre> | 5,990,160 | 4 | 0 | null | 2011-05-13 09:47:27.933 UTC | 1 | 2014-01-07 10:50:54.173 UTC | 2014-01-07 10:50:54.173 UTC | null | 759,866 | null | 375,971 | null | 1 | 9 | jquery | 39,487 | <pre><code>var values = $('table tr.PO1 td').map(function(_, td) {
return $(td).text();
}).get();
</code></pre>
<p>This would just create an array with the text contents from each <code>td</code>. Probably a better idea to use a map/object instead:</p>
<pre><code>var values = $('table tr.PO1 td').map(function(index, td) {
var ret = { };
ret[ index ] = $(td).text();
return ret;
}).get();
</code></pre> |
6,028,981 | Using HttpClient and HttpPost in Android with post parameters | <p>I'm writing code for an Android application that is supposed to take data, package it as Json and post it to a web server, that in turn is supposed to respond with json.</p>
<p>Using a GET request works fine, but for some reason using POST all data seems to get stripped and the server does not receive anything.</p>
<p>Here's a snippet of the code:</p>
<pre><code>HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
BasicCookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);
String uri = JSON_ADDRESS;
String result = "";
String username = "user";
String apikey = "something";
String contentType = "application/json";
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
} catch (JSONException e) {
Log.e(TAG, "JSONException: " + e);
}
HttpPost httpPost = new HttpPost(uri);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));
HttpGet httpGet = null;
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", contentType);
httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "UnsupportedEncodingException: " + e);
}
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
InputStream is = httpEntity.getContent();
result = StringUtils.convertStreamToString(is);
Log.i(TAG, "Result: " + result);
}
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException: " + e);
} catch (IOException e) {
Log.e(TAG, "IOException: " + e);
}
return result;
</code></pre>
<p>I think I have followed the general guidelines on how to create the parameters and post them, but apparently not.</p>
<p>Any help or pointers to where I can find a solution, are very welcome at this point (after spending a few hours realizing no post data was ever sent). The real server is running Wicket on Tomcat, but I've also tested it out on a simple PHP page, with no difference.</p> | 6,029,205 | 4 | 2 | null | 2011-05-17 09:39:20.25 UTC | 15 | 2018-11-28 12:25:21.097 UTC | null | null | null | null | 74,012 | null | 1 | 34 | java|android|json|httpclient|http-post | 118,369 | <p>have you tried doing it without the JSON object and just passed two basicnamevaluepairs?
also, it might have something to do with your serversettings</p>
<p>Update:
this is a piece of code I use:</p>
<pre><code>InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("HTTP", "HTTP: OK");
} catch (Exception e) {
Log.e("HTTP", "Error in http connection " + e.toString());
}
</code></pre> |
2,310,062 | How to force an index on inner joined tables? | <p>How do I force indexes on a query similar to this. I need to force an index on foo and bar individually.</p>
<pre><code>SELECT foo.*, bar.*
FROM foo
INNER JOIN bar ON foo.rel_id = bar.rel_id
WHERE foo.status = 1
AND bar.status = 1
</code></pre> | 2,310,125 | 2 | 1 | null | 2010-02-22 09:59:08.71 UTC | 6 | 2011-02-07 13:07:12.107 UTC | 2010-02-22 10:00:45.563 UTC | null | 17,343 | null | 175,562 | null | 1 | 22 | mysql|inner-join | 42,220 | <p>Assuming index <strong>a</strong> exists on foo and index <strong>b</strong> on bar:</p>
<pre><code>SELECT foo.*, bar.*
FROM foo FORCE INDEX (a)
INNER JOIN bar FORCE INDEX (b) ON foo.rel_id = bar.rel_id
WHERE foo.status = 1
AND bar.status = 1
</code></pre>
<p>would force index selection on MySql</p> |
59,494,037 | How to detect the device on React SSR App with Next.js? | <p>on a web application I want to display two different Menu, one for the Mobile, one for the Desktop browser.
I use Next.js application with server-side rendering and the library <a href="https://www.npmjs.com/package/react-device-detect" rel="noreferrer">react-device-detect</a>.</p>
<p>Here is the <a href="https://codesandbox.io/embed/affectionate-meadow-9uhez?fontsize=14&hidenavigation=1&theme=dark" rel="noreferrer">CodeSandox link</a>.</p>
<pre><code>import Link from "next/link";
import { BrowserView, MobileView } from "react-device-detect";
export default () => (
<div>
Hello World.{" "}
<Link href="/about">
<a>About</a>
</Link>
<BrowserView>
<h1> This is rendered only in browser </h1>
</BrowserView>
<MobileView>
<h1> This is rendered only on mobile </h1>
</MobileView>
</div>
);
</code></pre>
<p>If you open this in a browser and <strong>switch to mobile</strong> view and look the console you get this error:</p>
<blockquote>
<p>Warning: Text content did not match. Server: " This is rendered only
in browser " Client: " This is rendered only on mobile "</p>
</blockquote>
<p>This happen because the rendering by the server detects a browser and on the client, he is a mobile device. The only workaround I found is to generate both and use the CSS like this:</p>
<pre><code>.activeOnMobile {
@media screen and (min-width: 800px) {
display: none;
}
}
.activeOnDesktop {
@media screen and (max-width: 800px) {
display: none;
}
}
</code></pre>
<p>Instead of the library but I don't really like this method. Does someone know the good practice to handle devices type on an SSR app directly in the react code?</p> | 61,519,537 | 10 | 1 | null | 2019-12-26 22:19:24.797 UTC | 8 | 2022-09-20 10:02:09.12 UTC | null | null | null | null | 8,562,168 | null | 1 | 32 | reactjs|next.js|server-side-rendering|device-detection | 55,823 | <p><strong>LATEST UPDATE:</strong></p>
<p>So if you don't mind doing it client side you can use the dynamic importing as suggested by a few people below. This will be for use cases where you use static page generation.</p>
<p>i created a component which passes all the <code>react-device-detect</code> exports as props (it would be wise to filter out only the needed exports because then does not treeshake)</p>
<pre class="lang-js prettyprint-override"><code>// Device/Device.tsx
import { ReactNode } from 'react'
import * as rdd from 'react-device-detect'
interface DeviceProps {
children: (props: typeof rdd) => ReactNode
}
export default function Device(props: DeviceProps) {
return <div className="device-layout-component">{props.children(rdd)}</div>
}
</code></pre>
<pre class="lang-js prettyprint-override"><code>// Device/index.ts
import dynamic from 'next/dynamic'
const Device = dynamic(() => import('./Device'), { ssr: false })
export default Device
</code></pre>
<p>and then when you want to make use of the component you can just do</p>
<pre><code>const Example = () => {
return (
<Device>
{({ isMobile }) => {
if (isMobile) return <div>My Mobile View</div>
return <div>My Desktop View</div>
}}
</Device>
)
}
</code></pre>
<hr />
<p>Personally I just use a hook to do this, although the initial props method is better.</p>
<pre class="lang-js prettyprint-override"><code>import { useEffect } from 'react'
const getMobileDetect = (userAgent: NavigatorID['userAgent']) => {
const isAndroid = () => Boolean(userAgent.match(/Android/i))
const isIos = () => Boolean(userAgent.match(/iPhone|iPad|iPod/i))
const isOpera = () => Boolean(userAgent.match(/Opera Mini/i))
const isWindows = () => Boolean(userAgent.match(/IEMobile/i))
const isSSR = () => Boolean(userAgent.match(/SSR/i))
const isMobile = () => Boolean(isAndroid() || isIos() || isOpera() || isWindows())
const isDesktop = () => Boolean(!isMobile() && !isSSR())
return {
isMobile,
isDesktop,
isAndroid,
isIos,
isSSR,
}
}
const useMobileDetect = () => {
useEffect(() => {}, [])
const userAgent = typeof navigator === 'undefined' ? 'SSR' : navigator.userAgent
return getMobileDetect(userAgent)
}
export default useMobileDetect
</code></pre>
<p>I had the problem that scroll animation was annoying on mobile devices so I made a device based enabled scroll animation component;</p>
<pre><code>import React, { ReactNode } from 'react'
import ScrollAnimation, { ScrollAnimationProps } from 'react-animate-on-scroll'
import useMobileDetect from 'src/utils/useMobileDetect'
interface DeviceScrollAnimation extends ScrollAnimationProps {
device: 'mobile' | 'desktop'
children: ReactNode
}
export default function DeviceScrollAnimation({ device, animateIn, animateOut, initiallyVisible, ...props }: DeviceScrollAnimation) {
const currentDevice = useMobileDetect()
const flag = device === 'mobile' ? currentDevice.isMobile() : device === 'desktop' ? currentDevice.isDesktop() : true
return (
<ScrollAnimation
animateIn={flag ? animateIn : 'none'}
animateOut={flag ? animateOut : 'none'}
initiallyVisible={flag ? initiallyVisible : true}
{...props}
/>
)
}
</code></pre>
<br />
UPDATE:
<p>so after further going down the rabbit hole, the best solution i came up with is using the react-device-detect in a useEffect, if you further inspect the device detect you will notice that it exports const's that are set via the <code>ua-parser-js</code> lib</p>
<pre class="lang-js prettyprint-override"><code>export const UA = new UAParser();
export const browser = UA.getBrowser();
export const cpu = UA.getCPU();
export const device = UA.getDevice();
export const engine = UA.getEngine();
export const os = UA.getOS();
export const ua = UA.getUA();
export const setUA = (uaStr) => UA.setUA(uaStr);
</code></pre>
<p>This results in the initial device being the server which causes false detection.</p>
<p>I forked the repo and created and added a <a href="https://github.com/PaulPCIO/react-device-detect/tree/ssr-selectors" rel="noreferrer">ssr-selector</a> which requires you to pass in a user-agent. which could be done using the initial props</p>
<br />
UPDATE:
<p>Because of Ipads not giving a correct or rather well enough defined user-agent, see this <a href="https://forums.developer.apple.com/thread/119186" rel="noreferrer">issue</a>, I decided to create a hook to better detect the device</p>
<pre><code>import { useEffect, useState } from 'react'
function isTouchDevice() {
if (typeof window === 'undefined') return false
const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ')
function mq(query) {
return typeof window !== 'undefined' && window.matchMedia(query).matches
}
// @ts-ignore
if ('ontouchstart' in window || (window?.DocumentTouch && document instanceof DocumentTouch)) return true
const query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('') // include the 'heartz' - https://git.io/vznFH
return mq(query)
}
export default function useIsTouchDevice() {
const [isTouch, setIsTouch] = useState(false)
useEffect(() => {
const { isAndroid, isIPad13, isIPhone13, isWinPhone, isMobileSafari, isTablet } = require('react-device-detect')
setIsTouch(isTouch || isAndroid || isIPad13 || isIPhone13 || isWinPhone || isMobileSafari || isTablet || isTouchDevice())
}, [])
return isTouch
</code></pre>
<p>Because I require the package each time I call that hook, the UA info is updated, it also fixes to SSR out of sync warnings.</p> |
5,721,889 | Is there a list that is sorted automatically in .NET? | <p>I have a collection of <code>Layers</code> where they have names and colors. What I want to do is to sort these first based on colors, then based on their names:</p>
<pre><code>class Layer
{
public string Name {get; set;}
public LayerColor Color {get; set;}
}
enum LayerColor
{
Red,
Blue,
Green
}
</code></pre>
<p>Like:</p>
<pre><code>(red) layer2
(red) layer7
(blue) layer0
(blue) layer3
...
</code></pre>
<p>I was looking at SortedList but that acts like a Dictionary so doesn't allow for duplicate items.</p>
<p>Also I am using an API where I get the list of <code>Layers</code> by creation order, so I need to get the full list of <code>Layers</code> to sort them the way I want.</p>
<p>Eventually the list of <code>Layers</code> will be binded to a WPF UI where the users will have the ability to add new Layers, so that's why I wanted the internal list to always be sorted as the performance is not important (the number of <code>Layers</code> are less than a thousand).</p>
<p>In the end the <code>Layers</code> I sorted will be accessed via something like this:</p>
<pre><code>class Image
{
public MySortedList<Layer> Layers {get; set;}
}
</code></pre>
<p>What's the best way to do this?</p> | 5,721,920 | 8 | 2 | null | 2011-04-19 19:53:59.817 UTC | 5 | 2017-04-27 01:52:36.96 UTC | null | null | null | null | 51,816 | null | 1 | 29 | c#|.net|list|sorting | 49,613 | <p>Did you search for it? <a href="http://msdn.microsoft.com/en-us/library/ms132319.aspx" rel="noreferrer">Generic SortedList</a> and <a href="http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx" rel="noreferrer">SortedList</a>.</p>
<p>So I missed the duplicate part which make it a little bit harder I agree. But here is how I would solve it:</p>
<pre><code>var sortedList = new SortedList<LayerColor, SortedList<Layer, Layer>>();
var redSortedList = new SortedList<Layer, Layer>();
// Add all layers associated with the color red
sortedList.Add(LayerColor.Red, redSortedList);
</code></pre>
<p>Will that work for you. Also, I would prefer to use linq but if you really want a sorted list my solution will most likely work.</p>
<p>Last try:) :</p>
<pre><code>public class YourClass
{
private List<Layer> _layers;
public List<Layer> Layers
{
get
{
_layers = _layers.OrderBy(y => y.LayerColor).ThenBy(y => y.Name).ToList();
return _layers;
}
set
{
_layers = value;
}
}
}
</code></pre>
<p>Note that I'm writing directly in browser without testing it in VS (sitting on OS X), but you probably get the point.</p> |
6,102,398 | php implode (101) with quotes | <p>Imploding a simple array </p>
<p>would look like this</p>
<pre><code>$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
</code></pre>
<p>and that would return this</p>
<pre><code> lastname,email,phone
</code></pre>
<p>great, so i might do this instead </p>
<pre><code>$array = array('lastname', 'email', 'phone');
$comma_separated = implode("','", $array);
$comma_separated = "'".$comma_separated."'";
</code></pre>
<p>and now i have what I want a nice pretty csv string </p>
<pre><code> 'lastname','email','phone'
</code></pre>
<p>is there a better way to do this, it feels to me like there should be an optional parameter for implode am I missing something ?</p> | 6,102,446 | 15 | 2 | null | 2011-05-23 20:06:35.183 UTC | 28 | 2021-10-01 10:16:50.92 UTC | null | null | null | null | 234,670 | null | 1 | 147 | php|arrays|string|csv|implode | 129,066 | <p>No, the way that you're doing it is just fine. <code>implode()</code> only takes 1-2 parameters (if you just supply an array, it joins the pieces by an empty string).</p> |
39,241,851 | Developing spring boot application with lower footprint | <p>In an attempt to keep our microservices, developed in spring-boot to run on Cloud Foundry, smaller in footprint, we are looking for best approach to achieve the same.</p>
<p>Any inputs or pointers in this direction will be most welcomed.</p>
<p>It's surely the best that one always builds the application upwards starting from bare minimum dependencies, and the add any more only when required. Is there more of good practices to follow to further keep the application smaller in size?</p> | 39,249,361 | 1 | 2 | null | 2016-08-31 06:04:01.917 UTC | 27 | 2018-07-18 20:15:39.003 UTC | null | null | null | null | 4,741,070 | null | 1 | 34 | spring-boot | 16,521 | <p>Below are some personal ideas on how to reach <strong>a smaller footprint</strong> with Spring Boot. Your question is too broad for these recommandations to be taken into account in any other context. I'm not entirely sure you want to follow these in most situation, it simply answers "how to achieve a smaller footprint".</p>
<p><strong>(1) Only specify required dependencies</strong></p>
<p>I wouldn't personally worry about it, but if the goal is to have a smaller footprint, you may avoid using <code>starter-* dependencies</code>. Only specify the dependencies you actually use.</p>
<p><strong>Avoid this</strong>:</p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</code></pre>
<blockquote>
<p>In my sample project, the artifact produced <strong>with starter-*</strong> dependencies is <strong>~25MB</strong></p>
</blockquote>
<p><strong>Do this</strong>:</p>
<pre><code><dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
</code></pre>
<blockquote>
<p>In my sample project, the artifact produced <strong>without starter-*</strong> dependencies is <strong>~15MB</strong></p>
</blockquote>
<p><strong>(2) Exclude AutoConfigurations</strong></p>
<p>Exclude the AutoConfiguration you don't need:</p>
<pre><code>@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
</code></pre>
<p><strong>(3) Spring Boot properties</strong></p>
<p>Disable as much as you can in the application.properties (while making sure it does not have a negative impact too):</p>
<pre><code>spring.main.web-environment=false
spring.main.banner-mode=off
spring.jmx.enabled=false
server.error.whitelabel.enabled=false
server.jsp-servlet.registered=false
spring.freemarker.enabled=false
spring.groovy.template.enabled=false
spring.http.multipart.enabled=false
spring.mobile.sitepreference.enabled=false
spring.session.jdbc.initializer.enabled=false
spring.thymeleaf.cache=false
...
</code></pre>
<p><strong>(4) Choose your embedded web container wisely</strong></p>
<p>If launching spring boot with an embedded web container, you may choose a different one:</p>
<ul>
<li>tomcat (by default)</li>
<li>undertow (<a href="https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-undertow" rel="noreferrer">https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-undertow</a>)</li>
<li>jetty (<a href="https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-jetty" rel="noreferrer">https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-jetty</a>)</li>
<li>...</li>
</ul>
<p><strong>(5) Spring's recommandations</strong></p>
<ul>
<li>Memory: <code>java -Xmx32m -Xss256k -jar target/demo-0.0.1-SNAPSHOT.jar</code></li>
<li>Number of threads: <code>server.tomcat.max-threads: 4</code></li>
<li>source: <a href="https://spring.io/blog/2015/12/10/spring-boot-memory-performance" rel="noreferrer">spring-boot-memory-performance</a></li>
</ul>
<p><strong>(6) See also</strong>:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/22201620/how-to-reduce-spring-memory-footprint">How to reduce Spring memory footprint</a></li>
</ul> |
5,127,537 | Java 7 new IO API - Paths.exists | <p>Does anyone know what happened to the <code>path.exists()</code> API method in the latest Java 7 API?
I cannot find the change in the change logs, and between b123 and b130, the method has been removed from the API.I see that there is a static <code>Files.exists</code> method but I'm not sure if that is the replacement or not. </p>
<p>Is anyone following the Java 7 work close enough to know how this should be handled?</p>
<p>Thanks for any help. </p> | 5,130,959 | 1 | 2 | null | 2011-02-26 14:46:36.603 UTC | 2 | 2016-04-09 02:10:03.38 UTC | 2011-02-26 14:53:10.497 UTC | null | 378,968 | null | 370,481 | null | 1 | 75 | java|api|nio | 56,810 | <h1><code>Files.exists</code></h1>
<p>Look in the <a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html" rel="noreferrer"><code>Files</code></a> class for the static methods <a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#exists-java.nio.file.Path-java.nio.file.LinkOption...-" rel="noreferrer"><code>exists()</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#notExists-java.nio.file.Path-java.nio.file.LinkOption...-" rel="noreferrer"><code>notExists()</code></a>. Both take a <a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html" rel="noreferrer"><code>Path</code></a>. </p>
<p>I guess they decided it made more sense as a <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html" rel="noreferrer">static</a> rather than instance method.</p> |
40,956,671 | Passing event and argument to v-on in Vue.js | <p>I pass a parameter in <code>v-on:input</code> directives. If I don't pass it, I can access the event in the method. Is there any way I can still access the event when passing the parameter to the function? Note that I am using vue-router.</p>
<p>This is without passing the parameter. I can access the event object:</p>
<p>HTML</p>
<pre class="lang-html prettyprint-override"><code><input type="number" v-on:input="addToCart" min="0" placeholder="0">
</code></pre>
<p>Javascript</p>
<pre class="lang-js prettyprint-override"><code>methods: {
addToCart: function (event) {
// I need to access the element by using event.target
console.log('In addToCart')
console.log(event.target)
}
}
</code></pre>
<p>This is when passing the parameter. I can't access the event object:</p>
<p>HTML</p>
<pre class="lang-html prettyprint-override"><code><input type="number" v-on:input="addToCart(ticket.id)" min="0" placeholder="0">
</code></pre>
<p>Javascript</p>
<pre class="lang-js prettyprint-override"><code>methods: {
addToCart: function (id) {
// How can I access the element by using event
console.log('In addToCart')
console.log(id)
}
}
</code></pre>
<p>Here is a fiddle of the code, it should be good enough to replicate the problem that I am having:</p>
<p><a href="https://jsfiddle.net/lookman/vdhwkrmq/" rel="noreferrer">https://jsfiddle.net/lookman/vdhwkrmq/</a></p> | 40,956,873 | 4 | 0 | null | 2016-12-04 08:07:05.453 UTC | 30 | 2022-07-15 19:47:02.297 UTC | 2021-12-02 18:01:38.983 UTC | null | 11,047,824 | null | 4,144,667 | null | 1 | 261 | vue.js | 226,367 | <p>If you want to access event object as well as data passed, you have to pass <code>event</code> and <code>ticket.id</code> both as parameters, like following:</p>
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code><input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">
</code></pre>
<p><strong>Javascript</strong></p>
<pre class="lang-js prettyprint-override"><code>methods: {
addToCart: function (event, id) {
// use event here as well as id
console.log('In addToCart')
console.log(id)
}
}
</code></pre>
<p>See working fiddle: <a href="https://jsfiddle.net/nee5nszL/" rel="noreferrer">https://jsfiddle.net/nee5nszL/</a></p>
<h2>Edited: case with vue-router</h2>
<p>In case you are using vue-router, you may have to use <a href="https://v2.vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events" rel="noreferrer">$event</a> in your <code>v-on:input</code> method like following:</p>
<pre class="lang-html prettyprint-override"><code><input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">
</code></pre>
<p>Here is working <a href="https://jsfiddle.net/mimani/raj11s4o/" rel="noreferrer">fiddle</a>.</p> |
33,306,859 | The required anti-forgery cookie "__RequestVerificationToken" is not present | <p>My website is raising this exception around 20 times a day, usually the form works fine but there are instances where this issue occur and I don't know why is so random.</p>
<p>This is logged exception by elmah</p>
<blockquote>
<p>500 HttpAntiForgery The required anti-forgery cookie __RequestVerificationToken" is not present.</p>
</blockquote>
<p>But the form it is sending the the token as shown on the XML log by elmah</p>
<pre><code><form>
<item name="__RequestVerificationToken">
<value string="DNbDMrzHmy37GPS6IFH-EmcIh4fJ2laezIrIEev5f4vOhsY9T7SkH9-1b7GPjm92CTFtb4dGqSe2SSYrlWSNEQG1MUlNyiLP1wtYli8bIh41"/>
</item>
<item name="toPhone">
<value string="XXXXXX"/>
</item>
<item name="smsMessage">
<value string="xxxxxxxx"/>
</item>
</form>
</code></pre>
<p>This is my method on the controller which uses the data Attribute to check if the token is valid or nor</p>
<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> Send(SMSModel model)
{
// my code goes here
}
</code></pre>
<p>This is my form on the view</p>
<pre><code>@using (Html.BeginForm("Send", "SMS", FormMethod.Post, new { @class = "form-sms", autocomplete = "off" }))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">+53</div>
@Html.TextBoxFor(m => m.toPhone, new { @class = "form-control", placeholder = "teléfono", required = "required", type = "tel", maxlength = 8 })
</div>
</div>
</div>
</div>
<div class="form-group" style="position:relative">
<label class="sr-only" for="exampleInputEmail3">Message (up to 135 characters)</label>
@Html.TextAreaFor(m => m.smsMessage, new { rows = 4, @class = "form-control", placeholder = "escriba aquí su mensaje", required = "required", maxlength = "135" })
<span class="char-count">135</span>
</div>
if (ViewBag.Sent == true)
{
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<strong>Su mensaje ha sido enviado <span class="hidden-xs">satisfactoriamente</span></strong>
</div>
}
if (ViewBag.Error == true)
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<strong>Error:</strong> Por favor revise el número de teléfono.
</div>
}
<div class="errorToMany"></div>
<button type="submit" class="btn btn-default btn-block">Enviar SMS</button>
}
</code></pre>
<p>And this how I post my data using AJAX</p>
<pre><code>$('form.form-sms').submit(function (event) {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
beforeSend: function (xhr) {
$('.btn-default').attr("disabled", true);
$('.btn-default').html("Enviando...")
},
success: function (data, textStatus, jqXHR) {
if (data[0] == false && data[1] == "1") {
some code
} else {
location.reload();
}
},
error: function (jqXHR, textStatus, errorThrown) { }
});
return false;
});
</code></pre>
<p>The form works well most time but this error keeps happening and I don't know why, I've checked other questions here on Stack Overflow but nothing works for me.</p>
<p>For further explanation about how I post the data.</p>
<p>This form to send SMS has the fields ToNumber and Message. When a user clicks on the submit Button the AJAX function takes control and post it serializing the form's field data, when my function in the controller finishes and return the JSON result indicating everything went well, the AJAX method reloads the page showing the user a success message.</p>
<p>Any ideas what could be causing this issue.</p> | 33,314,529 | 8 | 0 | null | 2015-10-23 16:04:28.93 UTC | 10 | 2020-07-13 10:48:43.517 UTC | 2017-05-01 01:37:36.88 UTC | null | 584,192 | null | 1,964,280 | null | 1 | 38 | c#|jquery|asp.net-mvc|cookies|antiforgerytoken | 80,433 | <p>It almost sounds as if things are working as expected. </p>
<p>The way the anti forgery helper <code>@Html.AntiForgeryToken()</code> works is by injecting a hidden form field named <code>__RequestVerificationToken</code> into the page AND it also sets a cookie into the browser.</p>
<p>When the form is posted back the two are compared and if they don't match or the cookie is missing then the error is thrown.</p>
<p>So it does not matter that Elmah logs that the form is sending <code>__RequestVerificationToken</code>. It always will, even in the event of <code>CSRF</code> attack, because this is simply the hidden form field.</p>
<pre><code><input name="__RequestVerificationToken" type="hidden" value="DNbDMrzHmy37GPS6IFH-EmcIh4fJ2laezIrIEev5f4vOhsY9T7SkH9-1b7GPjm92CTFtb4dGqSe2SSYrlWSNEQG1MUlNyiLP1wtYli8bIh41" />
</code></pre>
<p>The error message on the other hand says the corresponding <code>COOKIE</code> is not being sent:</p>
<blockquote>
<p>500 HttpAntiForgery The required anti-forgery cookie
__RequestVerificationToken" is not present.</p>
</blockquote>
<p>So basically someone/something is replaying the form post without making the original request to get the cookie. As such they have the hidden form field
<code>__RequestVerificationToken</code> but NOT the cookie to verify it.</p>
<p>So it seems like things are working as they should. Check your logs re: IP numbers, and referrers, etc. You might be under attack or perhaps be doing something weird or buggy when redirecting your form content. As above, <code>referrers</code> are a good place to start for this kind of error, assuming this is not being spoofed.</p>
<p>Also note that as per <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/reload" rel="noreferrer">MDN</a></p>
<pre><code>location.reload();
</code></pre>
<blockquote>
<p>The Location.reload() method reloads the resource from the current
URL. Its optional unique parameter is a Boolean, which, when it is
true, causes the page to always be reloaded from the server. If it is
false or not specified, <strong>the browser may reload the page from its
cache</strong>.</p>
</blockquote>
<p>If it is, on occasion loading from cache, then you might end up with a <code>POST</code> that has the old page token but not the cookie.</p>
<p>So try :</p>
<pre><code>location.reload(true);
</code></pre> |
23,221,096 | Hibernate String Primary Key with Annotation | <p>I am trying to create a Privilege class with Annotations whose Primary Key is a String. I will assign them manually while inserting. Therefore no need for hibernate to generate a value for it. I'm trying to do something like that:</p>
<pre><code>@Id
@GeneratedValue(generator = "assigned")
@Column(name = "ROLE_NAME", nullable = false)
private String roleName;
</code></pre>
<p>But it throws that exception:</p>
<pre><code>Caused by: org.hibernate.AnnotationException: Unknown Id.generator: assigned
</code></pre>
<p>How can I configure a <code>String</code> primary key with annotations?</p> | 23,221,371 | 4 | 0 | null | 2014-04-22 13:30:29.423 UTC | 3 | 2021-10-21 12:52:46.667 UTC | null | null | null | null | 618,279 | null | 1 | 11 | java|hibernate|annotations|primary-key | 41,004 | <p>Since the <code>roleName</code> is not auto-generated, you should simply not annotate it with <code>@GeneratedValue</code>:</p>
<pre><code>@Id
@Column(name = "ROLE_NAME", nullable = false)
private String roleName;
</code></pre> |
19,118,367 | How do I set up Bootstrap after downloading via Composer? | <p>I'm a beginner with Composer, so I know little about it and have little experience with web application development.</p>
<p>I was reading the <a href="https://net.tutsplus.com/tutorials/javascript-ajax/combining-laravel-4-and-backbone/" rel="nofollow noreferrer">Nettuts+</a> Tutorial, and have a basic question about Composer.</p>
<pre><code>{
"require": {
"laravel/framework": "4.0.*",
"way/generators": "dev-master",
"twitter/bootstrap": "dev-master",
"conarwelsh/mustache-l4": "dev-master"
},
"require-dev": {
"phpunit/phpunit": "3.7.*",
"mockery/mockery": "0.7.*"
},
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
"scripts": {
"post-update-cmd": "php artisan optimize"
},
"minimum-stability": "dev"
}
</code></pre>
<p>If I set up my <code>composer.json</code> file as above, after executing <code>composer install --dev</code>, how do I make Bootstrap available for use in the Laravel project?</p>
<p>I mean, I can see the Bootstrap package is downloaded to the vendor directory. Before I only used to download Bootstrap from its official website and manually put the files in the public directory of Laravel, but what is the right way to do this here? Can I leave the Bootstrap files where they are, because I want to update the Bootstrap package to its latest version periodically?</p>
<p>Thanks.</p> | 21,039,021 | 7 | 0 | null | 2013-10-01 14:07:03.09 UTC | 7 | 2019-11-14 14:03:43.243 UTC | 2019-07-28 17:50:30.583 UTC | null | 964,243 | null | 1,536,973 | null | 1 | 32 | laravel|laravel-4|twitter-bootstrap-3|composer-php | 47,980 | <p>We have artisan command to publish the assets(CSS, JS,..). Something like this should work.</p>
<pre><code>php artisan asset:publish --path="vendor/twitter/bootstrap/bootstrap/css" bootstrap/css
php artisan asset:publish --path="vendor/twitter/bootstrap/bootstrap/js" bootstrap/js
</code></pre>
<p>i am not sure about the path.. But this should work.</p> |
48,151,332 | Why are AWS Batch Jobs stuck in RUNNABLE? | <p>I use a computing environment of 0-256 m3.medium on demand instances. My Job definition requires 1 CPU and 3 GB of Ram, which m3.medium has.</p>
<p>What are possible reasons why AWS Batch Jobs are stuck in state <code>RUNNABLE</code>?</p>
<p><a href="https://docs.aws.amazon.com/batch/latest/userguide/job_states.html" rel="noreferrer">AWS</a> says:</p>
<p><code>A job that resides in the queue, has no outstanding dependencies, and is therefore ready to be scheduled to a host. Jobs in this state are started as soon as sufficient resources are available in one of the compute environments that are mapped to the job’s queue. However, jobs can remain in this state indefinitely when sufficient resources are unavailable.</code></p>
<p>but that does not answer my question</p> | 48,706,035 | 5 | 0 | null | 2018-01-08 13:29:06.19 UTC | 5 | 2020-03-27 15:29:42.227 UTC | 2018-01-08 13:36:50.307 UTC | null | 7,531,531 | null | 7,531,531 | null | 1 | 31 | amazon-web-services|aws-batch|aws-ecs | 13,318 | <p>There are other reasons why a Job can get stuck in RUNNABLE:</p>
<ul>
<li>Insufficient permissions for the role associated to the Computed Environment</li>
<li>No internet access from the Compute Environment instance.
You will need to associate a <a href="https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html" rel="noreferrer">NAT</a> or <a href="https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Internet_Gateway.html" rel="noreferrer">Internet Gateway</a> to the Compute Environment subnet.
<ul>
<li>Make sure to check the "Enable auto-assign public IPv4 address" setting
on your Compute Environment's subnet. (Pointed out by @thisisbrians in the comments)</li>
</ul></li>
<li>Problems with your image.
You need to use an ECS optimized AMI or make sure you have the ECS container agent working. More info at <a href="https://docs.aws.amazon.com/batch/latest/userguide/compute_resource_AMIs.html#batch-ami-spec" rel="noreferrer">aws docs</a></li>
<li>You're trying to launch instances for which you account is limited to 0 instances (EC2 console > limits, in the left menu). (Read more on <a href="https://stackoverflow.com/questions/48151332/why-are-aws-batch-jobs-stuck-in-runnable/48706035?noredirect=1#comment88521216_48706035]">gergely-danyi comment</a>)</li>
<li>And as mentioned insufficient resources</li>
</ul>
<p>Also, make sure to read the <a href="https://docs.aws.amazon.com/batch/latest/userguide/troubleshooting.html" rel="noreferrer">AWS Batch troubleshooting </a></p> |
21,341,616 | Publish Multiple Projects to Different Locations on Azure Website | <p><em>Feel free to recommend a better title or changes to my explanation below!</em></p>
<p>I am using Windows Azure Websites (for the first time) and have connected it to a solution in Visual Studio Online (also my first time). I was also able to connect to Visual Studio Online, create a project, throw up a master page and web form connected to a master page and my Azure website updated itself. Great!</p>
<p><strong>My Issue</strong></p>
<p>If I add another project to the solution it seems that this new project overwrites the files in the first one. I can't figure out how to set this up so:</p>
<p>Project 1 -> deploy to wwwroot (happens by default great!)</p>
<p>Project 2 -> deploy to wwwroot/sub/directory/ (doesn't seem to work)</p>
<p>Could somebody explain how to configure project 2 so that when the solution auto deploys to an Azure Website that it goes to a specific location?</p> | 21,346,077 | 1 | 0 | null | 2014-01-24 20:11:03.777 UTC | 15 | 2014-01-26 09:52:27.053 UTC | null | null | null | null | 1,018,496 | null | 1 | 24 | azure|visual-studio-2013|azure-web-app-service|azure-devops | 7,797 | <ol>
<li>Go to the Configure tab for the site in Azure portal.</li>
<li><p>Scroll all the way to the bottom then add a new application where ever you want like Project2 below.
<img src="https://i.stack.imgur.com/e1y8e.jpg" alt=""></p>
<p>Basically the 'Project2' part is the URL after the root '/' and the 'site\wwwroot\Project2' is where the actual folder should live under the site root</p></li>
<li><p>Download the publishing profile and import it in Visual Studio, then add the application name after your site name like below. Also remember to update the destination URL as well </p>
<p><img src="https://i.stack.imgur.com/VEpIB.jpg" alt=""></p></li>
</ol>
<p>hope that helps</p> |
29,039,462 | Which certificate should I use to sign my Mac OS X application? | <p>We are developing a Mac OS X application that we are going to distribute outside the Mac App Store. We ended up having these certificates in the Mac Developers program:</p>
<p><img src="https://i.stack.imgur.com/UETpj.png" alt="List of six certificates: two of type Mac Development, four of types Developer ID Installer, Mac App Distribution, Mac Installer Distribution, Developer ID Application"></p>
<p>and when I go to select one for signing the application, I find this:</p>
<p><img src="https://i.stack.imgur.com/rSc4s.png" alt="Certificate selection menu. Automatic: Mac Developer, Mac Distribution, Developer ID: *; others in Identities in Keychain"></p>
<p>Am I correct in that I should use <code>Developer ID: *</code> for Debug? Will that allow developers that don’t have my company’s certificate to sign the application to be able to run it locally?</p>
<p>What certificate should I use for Release?</p> | 29,040,068 | 2 | 0 | null | 2015-03-13 18:29:42.567 UTC | 9 | 2018-11-13 18:39:01.643 UTC | 2015-03-20 20:37:14.163 UTC | null | 2,157,640 | null | 6,068 | null | 1 | 16 | xcode|macos|certificate|release | 11,646 | <p>For development (for example, the Debug configuratino) use the <code>Mac Developer</code> option, which will choose your local Mac Developer certificate (in your case "Mac Developer: José Fernández"), which is meant for team members working on your project (includes testing/debugging).</p>
<p>For Release, use "Developer ID: *" which will pick <a href="https://developer.apple.com/library/mac/documentation/IDEs/Conceptual/AppDistributionGuide/DistributingApplicationsOutside/DistributingApplicationsOutside.html#//apple_ref/doc/uid/TP40012582-CH12-SW2" rel="noreferrer">the standard application release certificate used outside the AppStore</a>, in your case "Developer ID Application: Carousel Apps. I recommend doing a final test/debug after codesigning to ensure it's working as expected. </p>
<p>The way Xcode picks up certificates is by a simple substring matching.</p>
<h2><a href="https://developer.apple.com/library/mac/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html#//apple_ref/doc/uid/TP40012582-CH31-SW41" rel="noreferrer">Apple Codesigning Certificate Types</a></h2>
<p>(<strong>Name</strong>, <em>Type</em>, Description)</p>
<p><strong>iOS Development</strong></p>
<ul>
<li><em>iPhone Developer</em>: Team Member Name Used to run an iOS app on devices
and use certain app services during development.</li>
</ul>
<p><strong>iOS Distribution</strong></p>
<ul>
<li><em>iPhone Distribution</em>:
Team Name Used to distribute your iOS app on
designated devices for testing or to submit it to the App Store.</li>
</ul>
<p><strong>Mac Development</strong></p>
<ul>
<li><em>Mac Developer</em>: Team Member Name Used to enable certain app services
during development and testing.</li>
</ul>
<p><strong>Mac App Distribution</strong></p>
<ul>
<li><em>3rd Party Mac Developer Application</em>: Team Name Used to sign a Mac app
before submitting it to the Mac App Store.</li>
</ul>
<p><strong>Mac Installer Distribution</strong></p>
<ul>
<li><em>3rd Party Mac Developer Installer</em>: Team Name Used to sign and submit
a Mac Installer Package, containing your signed app, to the Mac App
Store.</li>
</ul>
<p><strong>Developer ID Application</strong></p>
<ul>
<li><em>Developer ID Application</em>: Team Name Used to sign a Mac app before
distributing it outside the Mac App Store.</li>
</ul>
<p><strong>Developer ID Installer</strong></p>
<ul>
<li><em>Developer ID Installer</em>: Team Name Used to sign and distribute a Mac
Installer Package, containing your signed app, outside the Mac App
Store</li>
</ul>
<p><img src="https://i.stack.imgur.com/mgqcr.png" alt="enter image description here">
Once codesigned you can also simulate the launch behavior of your app when Gatekeeper is enabled from <code>Terminal.app</code>:</p>
<pre><code>spctl -a -v Carousel.app
./Carousel.app: accepted
source=Developer ID
</code></pre>
<blockquote>
<p>The <code>Developer ID Application</code> certificate allows your app to run with
<code>Gatekeeper</code> on the setting <strong>"allow apps downloaded from Mac App Store
and identified developers"</strong></p>
</blockquote> |
21,893,674 | Print Function Linked Lists C++ | <p>I'm currently learning Linked Lists in C++, and I can't write a print function which prints out the elements of the list; I mean I wrote the function but it doesn't work properly.</p>
<pre><code>#include <iostream>
using namespace std;
struct node
{
char name[20];
node* next;
};
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = NULL;
if (head == NULL) //is empty
{
head = person;
}
else
{
person = person->next;
}
return head;
}
void printList(node* head)
{
node* temp = head;
cout << temp->name << endl;
}
int main()
{
node* head = NULL;
node* temp = head;
unsigned short people = 0;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> people;
cout << endl;
for (unsigned short i = 1; i <= people; i++)
{
addNewPerson(head);
cout << endl;
}
cout << "LIST: " << endl;
cout << endl;
while (temp != NULL)
{
printList(temp);
temp = temp->next;
}
cin.get();
}
</code></pre>
<p>I am wondering what I'm doing wrong, please help me!</p> | 21,894,342 | 6 | 1 | null | 2014-02-19 22:13:09.487 UTC | 2 | 2019-12-15 12:05:11.787 UTC | 2014-02-20 01:18:44.5 UTC | null | 1,009,479 | null | 2,075,578 | null | 1 | 3 | c++|function|printing|linked-list | 49,193 | <p>It is obvious that function addNewPerson is wrong.</p>
<pre><code>node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = NULL;
if (head == NULL) //is empty
{
head = person;
}
else
{
person = person->next;
}
return head;
}
</code></pre>
<p>You allocated new node person. </p>
<pre><code> node* person = new node;
</code></pre>
<p>Set its field next to NULL</p>
<pre><code> person->next = NULL;
</code></pre>
<p>Then if head is not equal to NULL you set person to person->next</p>
<pre><code> person = person->next;
</code></pre>
<p>As person->next was set to NULL it means that now also person will be equal to NULL.</p>
<p>Moreover the function returns head that can be changed in the function. However you ignore returned value in main</p>
<pre><code>addNewPerson(head);
</code></pre>
<p>At least there should be</p>
<pre><code>head = addNewPerson(head);
</code></pre>
<p>The valid function addNewPerson could look the following way</p>
<pre><code>node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = head;
head = person;
return head;
}
</code></pre>
<p>And in main you have to write</p>
<pre><code> for (unsigned short i = 1; i <= people; i++)
{
head = addNewPerson(head);
cout << endl;
}
</code></pre>
<p>Function printList does not output the whole list. It outputs only data member name of the first node that is of head. </p>
<pre><code>void printList(node* head)
{
node* temp = head;
cout << temp->name << endl;
}
</code></pre>
<p>It should look the following way</p>
<pre><code>void printList(node* head)
{
for ( ; head; head = head->next )
{
cout << head->name << endl;
}
}
</code></pre>
<p>And at last main should look as</p>
<pre><code>int main()
{
node* head = NULL;
unsigned short people = 0;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> people;
cout << endl;
for ( unsigned short i = 0; i < people; i++ )
{
head = addNewPerson(head);
cout << endl;
}
cout << "LIST: " << endl;
cout << endl;
printList( head );
cin.get();
}
</code></pre> |
33,423,702 | How to use > (greater-than) inside a template parameter and not get a parsing error? | <p>I want to only define a function based on the size of the template parameter:</p>
<pre><code>template <class T>
typename std::enable_if<sizeof(T) > 1, void>::type
foobify(T v) {
// ...
}
int main() {
//foobify((unsigned char)30); // should not compile
foobify((long)30);
}
</code></pre>
<p>However, I get:</p>
<pre><code>main.cpp:8:41: error: expected unqualified-id before numeric constant
typename std::enable_if<sizeof(T) > 1, void>::type
</code></pre>
<p>It works if I instead do <code>1 < sizeof(T)</code>. Thus I believe GCC is thinking I am ending the template parameter, instead of continuing the boolean expression. </p>
<p>Is there any way to use <code>></code> itself without having to work around it?</p> | 33,423,740 | 3 | 2 | null | 2015-10-29 20:11:10.843 UTC | 2 | 2021-07-29 03:11:22.373 UTC | null | null | null | null | 15,055 | null | 1 | 28 | c++|parsing|templates | 6,048 | <p>Yes, expressions using that operator must be parenthesized. See [temp.names]/3:</p>
<blockquote>
<p>When parsing a <em>template-argument-list</em>, <strong>the first non-nested <code>></code><sup>138</sup> is taken as the ending delimiter
rather than a greater-than operator.</strong> [..] [ <em>Example:</em></p>
<pre><code>template<int i> class X { /* ...*/ };
X< 1>2 > x1; // syntax error
X<(1>2)> x2; // OK
</code></pre>
<p><em>— end example</em> ]</p>
<p><sup> 138) A <code>></code> that encloses the <em>type-id</em> of a <code>dynamic_cast</code>, <code>static_cast</code>, <code>reinterpret_cast</code> or <code>const_cast</code>, or which encloses the
<em>template-argument</em>s of a subsequent <em>template-id</em>, is considered nested for the purpose of this description.</sup></p>
</blockquote>
<p>Clearly that doesn't apply if you use the symmetric counterpart of that comparison, i.e. employing <code><</code>, instead - parsing is unambiguous in that case.</p> |
29,999,360 | Upgrading mongodb has no effect and still shows the old version | <p>Following are the commands which I used to upgrade my mongodb version from 2.6.9 to latest, but its still showing me the previous version. Let me know what I am doing wrong with the upgrading process. The problem is that <code>mongod -version</code> still shows the old version installed after upgrade.</p>
<p>Docs which I refer to - <a href="http://docs.mongodb.org/master/tutorial/install-mongodb-on-ubuntu/" rel="noreferrer">Mongodb Docs</a> </p>
<p>Steps I followed -</p>
<ul>
<li>sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10</li>
<li>echo "deb <a href="http://repo.mongodb.org/apt/ubuntu" rel="noreferrer">http://repo.mongodb.org/apt/ubuntu</a> "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list</li>
<li>sudo apt-get update</li>
<li>sudo apt-get install -y mongodb-org </li>
</ul>
<p>Result -</p>
<pre><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be upgraded:
mongodb-org
1 upgraded, 0 newly installed, 0 to remove and 139 not upgraded.
Need to get 3,608 B of archives.
After this operation, 0 B of additional disk space will be used.
Get:1 http://repo.mongodb.org/apt/ubuntu/ trusty/mongodb-org/3.0/multiverse mongodb-org amd64 3.0.2 [3,608 B]
Fetched 3,608 B in 0s (18.3 kB/s)
(Reading database ... 298790 files and directories currently installed.)
Preparing to unpack .../mongodb-org_3.0.2_amd64.deb ...
arg: upgrade
Unpacking mongodb-org (3.0.2) over (2.6.9) ...
Setting up mongodb-org (3.0.2) ...
</code></pre>
<p>After this I re started the service - <code>sudo service mongod restart</code></p>
<p>But still its showing me version <code>2.6.9</code> Let me know what I am doing wrong here..or missed any step ?</p> | 30,327,520 | 9 | 5 | null | 2015-05-02 06:49:58.95 UTC | 8 | 2022-03-24 03:07:11.007 UTC | 2017-06-30 12:50:51.483 UTC | null | 1,590,502 | null | 639,406 | null | 1 | 47 | mongodb|ubuntu | 32,046 | <p>I'm in the exact same situation, followed the exact same steps, and had the same issue.</p>
<p>What worked for me was:</p>
<p><a href="http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/#uninstall-mongodb" rel="nofollow noreferrer">Uninstalling</a>:</p>
<pre><code>sudo service mongod stop
sudo apt-get purge mongodb-org*
</code></pre>
<p><strong>Do NOT remove data directories</strong> - all your data will be lost if you do.</p>
<p>Note: Calling <code>sudo apt-get purge mongodb-org*</code> deletes the <code>mongod.conf</code> file. In case you want to keep this file after the update, make sure you <strong>create a backup copy</strong> of it and use it after the new version has been installed.</p>
<p>Then <a href="http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/#install-the-mongodb-packages" rel="nofollow noreferrer">install mongodb</a> with:</p>
<pre><code>sudo apt-get install -y mongodb-org
</code></pre>
<p>This assumes that you've already performed the previous installation steps (importing the public key, creating a list file, reloading local package database) as you've stated.</p> |
34,094,030 | Log all HTTP requests of Tomcat Server? | <p>Is it possible to print all requests to Tomcat and responses from Tomcat in a logfile?</p>
<p>ex:</p>
<blockquote>
<blockquote>
<p>request</p>
<p>headers: [header1=a, header2=a]</p>
<p>params: [param1=avv, param2=b]</p>
<p>response</p>
<p>status-code = 200</p>
<p>response = its works</p>
</blockquote>
</blockquote> | 34,096,888 | 3 | 1 | null | 2015-12-04 17:25:27.23 UTC | 4 | 2019-01-02 14:39:11.703 UTC | 2019-01-02 14:39:11.703 UTC | null | 352,319 | null | 2,836,188 | null | 1 | 12 | tomcat|logging|request | 58,850 | <p>Put an <code>AccessLogValve</code> in the <code>Host</code> or <code>Context</code> element e.g.:</p>
<pre><code><Host name="www.mysite.com" appBase="..." >
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs" prefix="mysitelog." suffix=".txt"
pattern="..." resolveHosts="false" />
</Host>
</code></pre>
<p>The <code>pattern</code> attribute can take one of two shorthand values (<em>common</em>,<em>combined</em>) or a custom pattern using a number of constants and replacement strings. Let me quote the Tomcat docs:</p>
<p><a href="https://tomcat.apache.org/tomcat-8.0-doc/config/valve.html#Access_Log_Valve" rel="noreferrer">https://tomcat.apache.org/tomcat-8.0-doc/config/valve.html#Access_Log_Valve</a></p>
<blockquote>
<p>Values for the pattern attribute are made up of literal text strings,
combined with pattern identifiers prefixed by the "%" character to
cause replacement by the corresponding variable value from the current
request and response. The following pattern codes are supported:</p>
<pre><code>%a - Remote IP address
%A - Local IP address
%b - Bytes sent, excluding HTTP headers, or '-' if zero
%B - Bytes sent, excluding HTTP headers
%h - Remote host name (or IP address if enableLookups for the connector is false)
%H - Request protocol
%l - Remote logical username from identd (always returns '-')
%m - Request method (GET, POST, etc.)
%p - Local port on which this request was received. See also %{xxx}p below.
%q - Query string (prepended with a '?' if it exists)
%r - First line of the request (method and request URI)
%s - HTTP status code of the response
%S - User session ID
%t - Date and time, in Common Log Format
%u - Remote user that was authenticated (if any), else '-'
%U - Requested URL path
%v - Local server name
%D - Time taken to process the request, in millis
%T - Time taken to process the request, in seconds
%F - Time taken to commit the response, in millis
%I - Current request thread name (can compare later with stacktraces)
</code></pre>
<p>There is also support to write information incoming or outgoing
headers, cookies, session or request attributes and special timestamp
formats. It is modeled after the Apache HTTP Server log configuration
syntax. Each of them can be used multiple times with different xxx
keys:</p>
<pre><code>%{xxx}i write value of incoming header with name xxx
%{xxx}o write value of outgoing header with name xxx
%{xxx}c write value of cookie with name xxx
%{xxx}r write value of ServletRequest attribute with name xxx
%{xxx}s write value of HttpSession attribute with name xxx
%{xxx}p write local (server) port (xxx==local) or remote (client) port (xxx=remote)
%{xxx}t write timestamp at the end of the request formatted using the enhanced SimpleDateFormat pattern xxx
</code></pre>
</blockquote>
<p>As you can see there are quite a few fields that can be used, but if you still need more, you have to write your own <code>AccessLogValve</code> implementation.</p> |
10,553,377 | How to make a digital signature in a web application (JavaScript) using a smartcard? | <p>We have written a document management system and would like to digitally sign documents using the web client. Our Java client application is already able to apply and check digital signature, but we would like to make signature even with our web client. This is written in GWT and so, when run on the client side, it is a JavaScript application.</p>
<p>We not want to create a Java applet and download it on the client and execute it. We would like to use the browser security device or the browser API in order to sign a document. We would also like to keep the complete document server side, and move to the client only the document hash.</p>
<p>We feel this should be possible using <strong>NSS</strong> or <strong>npapi/npruntime</strong>, but we did not find any information about this. (By the way, is npruntime available also in IE? Should we use ActiveX for achieving the same result with IE?)</p>
<p>Do you have any hints?</p> | 10,561,313 | 5 | 1 | null | 2012-05-11 14:31:46.17 UTC | 10 | 2019-04-18 16:29:11.36 UTC | 2016-05-24 18:33:32.797 UTC | null | 472,495 | null | 387,880 | null | 1 | 9 | digital-signature|npapi|pkcs#11 | 27,262 | <p>After some more googling I found the answer. Mozilla export part of its NSS module via <a href="https://developer.mozilla.org/en/JavaScript_crypto" rel="nofollow noreferrer">window.crypto</a> object. A more standard way of doing such operation is probably via <a href="https://wiki.mozilla.org/Privacy/Features/DOMCryptAPISpec/Latest" rel="nofollow noreferrer">DOMCrypt</a>, that is currently <a href="http://www.w3.org/2011/11/webcryptography-charter.html" rel="nofollow noreferrer">discusses in W3C</a>.
Google Chrome developer will wait W3C to standardize DOMCrypt, while Microsoft require the use of an ActiveX object <a href="http://bozhobg.wordpress.com/2009/04/16/how-to-create-a-digital-signing-solution-with-only-javascript/" rel="nofollow noreferrer">as explained here</a> (this works even with Firefox/Chrome/Opera on Windows).</p> |
22,755,795 | how to Retrieve data from database and display it in a jsp text fields using jdbc connection | <p>I am retrieving data from database and displaying it in table in a <code>JSP</code> but I do not have any idea about how to display it on text fields.</p>
<p>e.g. </p>
<ol>
<li>when I search a index number.</li>
<li>the the result (name , address, age) must come to the textfeilds which are in my <code>JSP</code></li>
</ol>
<p>My code:</p>
<pre><code>public class S2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "shoppingCart";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Connected!");
String pid = request.getParameter("pid");
ArrayList al = null;
ArrayList pid_list = new ArrayList();
String query = "select * from user where uid='" + pid + "' ";
System.out.println("query " + query);
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
al = new ArrayList();
out.println(rs.getString(1));
out.println(rs.getString(2));
out.println(rs.getString(3));
out.println(rs.getString(4));
out.println(rs.getString(5));
al.add(rs.getString(1));
al.add(rs.getString(2));
al.add(rs.getString(3));
al.add(rs.getString(4));
al.add(rs.getString(5));
System.out.println("al :: " + al);
pid_list.add(al);
}
request.setAttribute("piList", pid_list);
RequestDispatcher view = request.getRequestDispatcher("/searchview.jsp");
view.forward(request, response);
conn.close();
System.out.println("Disconnected!");
} catch (Exception e) {
e.printStackTrace();
}
</code></pre> | 46,153,735 | 5 | 2 | null | 2014-03-31 07:27:10.873 UTC | 1 | 2017-09-11 10:41:07.017 UTC | 2017-09-11 10:08:52.687 UTC | null | 7,294,900 | null | 2,695,450 | null | 1 | 5 | java|mysql|jsp|jdbc | 62,978 | <p>Make sure you have included the jdbc driver in your project and "build" it. Then:</p>
<ol>
<li><p>Make the database connection and retrieve the query result. </p></li>
<li><p>Return the query result and save in an object of ResultSet.</p></li>
<li><p>Traverse through the object and display the query results.</p></li>
</ol>
<p>The example code below demonstrates this in detail.</p>
<pre><code>String label = request.getParameter("label");
//retrieving a variable from a previous page
Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null)
{
System.out.println("Connection successful");
}
ResultSet rs = listresult.dbresult.func(dbc, label);
//The above function is mentioned in the end.
//It is defined in another package- listresult
while (rs.next())
{
%>
<form name="demo form" method="post">
<table>
<tr>
<td>
Label Name:
</td>
<td>
<input type="text" name="label"
value="<%=rs.getString("lname")%>">
</td>
</tr>
</table>
</form>
<% } %>
public static ResultSet func(Connection dbc, String x)
{
ResultSet rs = null;
String sql;
PreparedStatement pst;
try
{
sql = "select lname from demo where label like '" + x + "'";
pst = dbc.prepareStatement(sql);
rs = pst.executeQuery();
}
catch (Exception e)
{
e.printStackTrace();
String sqlMessage = e.getMessage();
}
return rs;
}
</code></pre>
<p>I have tried to make this example as detailed as possible. If any queries do ask.</p> |
7,626,076 | How to set current date and time using prepared statement? | <p>I have a column in database having datatype <code>DATETIME</code>. I want to set this column value to current date and time using `PreparedStatement. How do I do that?</p> | 7,626,080 | 2 | 0 | null | 2011-10-02 11:31:08.313 UTC | 9 | 2018-05-04 17:30:57.21 UTC | 2011-10-02 11:41:19.95 UTC | null | 157,882 | null | 266,074 | null | 1 | 31 | java|datetime|jdbc|prepared-statement | 84,501 | <p>Use <a href="http://download.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setTimestamp%28int,%20java.sql.Timestamp%29" rel="noreferrer"><code>PreparedStatement#setTimestamp()</code></a> wherein you pass a <a href="http://download.oracle.com/javase/6/docs/api/java/sql/Timestamp.html" rel="noreferrer"><code>java.sql.Timestamp</code></a> which is constructed with <a href="http://download.oracle.com/javase/6/docs/api/java/lang/System.html#currentTimeMillis%28%29" rel="noreferrer"><code>System#currentTimeMillis()</code></a>.</p>
<pre class="lang-java prettyprint-override"><code>preparedStatement.setTimestamp(index, new Timestamp(System.currentTimeMillis()));
// ...
</code></pre>
<p>Alternativaly, if the DB supports it, you could also call a DB specific function to set it with the current timestamp. For example MySQL supports <code>now()</code> for this. E.g.</p>
<pre class="lang-sql prettyprint-override"><code>String sql = "INSERT INTO user (email, creationdate) VALUES (?, now())";
</code></pre>
<p>Or if the DB supports it, change the field type to one which automatically sets the insert/update timestamp, such as <a href="http://dev.mysql.com/doc/refman/5.0/en/timestamp.html" rel="noreferrer"><code>TIMESTAMP</code></a> instead of <code>DATETIME</code> in MySQL.</p> |
7,063,053 | PHP Error handling: die() Vs trigger_error() Vs throw Exception | <p>In regards to Error handling in PHP -- As far I know there are 3 styles:</p>
<ol>
<li><p><code>die()</code>or <code>exit()</code> style:</p>
<pre><code>$con = mysql_connect("localhost","root","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
</code></pre></li>
<li><p><code>throw Exception</code> style:</p>
<pre><code> if (!function_exists('curl_init')) {
throw new Exception('need the CURL PHP extension.
Recomplie PHP with curl');
}
</code></pre></li>
<li><p><code>trigger_error()</code> style:</p>
<pre><code>if(!is_array($config) && isset($config)) {
trigger_error('Error: config is not an array or is not set', E_USER_ERROR);
}
</code></pre></li>
</ol>
<p>Now, in the PHP manual all three methods are used. </p>
<ul>
<li><p>What I want to know is which style should I prefer & why?</p></li>
<li><p>Are these 3 drop in replacements of each other & therefore can be used interchangeably?</p></li>
</ul>
<p>Slightly OT: Is it just me or everyone thinks PHP error handling options are just <em>too many</em> to the extent it confuses php developers?</p> | 7,063,076 | 2 | 3 | null | 2011-08-15 08:42:08.65 UTC | 43 | 2017-03-21 21:38:53.547 UTC | 2017-03-21 21:38:53.547 UTC | null | 7,735,647 | null | 367,985 | null | 1 | 131 | error-handling|php | 32,829 | <p>The first one should never be used in production code, since it's transporting information irrelevant to end-users (a user can't do anything about <em>"Cannot connect to database"</em>).</p>
<p>You throw Exceptions if you know that at a certain critical code point, your application <em>can fail</em> and you want your code to recover across multiple call-levels.</p>
<p><code>trigger_error()</code> lets you fine-grain error reporting (by using different levels of error messages) and you can hide those errors from end-users (using <a href="http://php.net/manual/en/function.set-error-handler.php" rel="noreferrer"><code>set_error_handler()</code></a>) but still have them be displayed to you during testing.</p>
<p>Also <code>trigger_error()</code> can produce non-fatal messages important during development that can be suppressed in production code using a custom error handler. You can produce fatal errors, too (<code>E_USER_ERROR</code>) but those aren't recoverable. If you trigger one of those, program execution <em>stops</em> at that point. This is why, for fatal errors, Exceptions should be used. This way, you'll have more control over your program's flow:</p>
<pre><code>// Example (pseudo-code for db queries):
$db->query('START TRANSACTION');
try {
while ($row = gather_data()) {
$db->query('INSERT INTO `table` (`foo`,`bar`) VALUES(?,?)', ...);
}
$db->query('COMMIT');
} catch(Exception $e) {
$db->query('ROLLBACK');
}
</code></pre>
<p>Here, if <code>gather_data()</code> just plain croaked (using <code>E_USER_ERROR</code> or <code>die()</code>) there's a chance, previous <code>INSERT</code> statements would have made it into your database, even if not desired and you'd have no control over what's to happen next.</p> |
22,945,826 | What does "unsupported operand type(s) for -: 'int' and 'tuple'" means? | <p>I got a error saying:</p>
<pre><code>unsupported operand type(s) for -: 'int' and 'tuple'
</code></pre>
<p>How do I correct it?</p>
<pre><code>from scipy import integrate
cpbar = lambda T: (3.826 - (3.979e-3)*T + 24.558e-6*T**2 - 22.733e-9*T**3 + 6.963e-12*T**4)*8.314
deltahbarCH4 = integrate.quad(cpbar,298,1000)
var = deltahbarCH4
hRPbar = hRPbar + (deltahbarCO2 + 2*deltahbarH2O - var -2*deltahbarO2)
</code></pre> | 22,945,940 | 2 | 1 | null | 2014-04-08 18:54:29.797 UTC | 2 | 2014-04-08 19:06:12.483 UTC | 2014-04-08 19:03:22.823 UTC | null | 100,297 | null | 3,498,229 | null | 1 | 6 | python|scipy|tuples | 63,016 | <p><a href="http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.integrate.quad.html" rel="nofollow"><code>integrate.quad()</code> returns a tuple</a>; <code>deltahbarCO2 + 2*deltahbarH2O</code> is an integer, you are trying to subtract the <code>var</code> tuple.</p>
<p>If you wanted <em>just</em> the integral <code>y</code> of the <code>integrate.quad()</code> result, use the first element of that tuple:</p>
<pre><code>var = deltahbarCH4[0]
</code></pre>
<p>or use tuple assignment:</p>
<pre><code>var, err = deltabarCH4
</code></pre> |
23,138,671 | how to add authentication header to $window.open | <p>I have angularjs application where users enter data that is saved to database, then on server side it is compiled into pdf file. All access requires appropriate authentication headers in place. After needed data is filled a user presses button to save data and then to retrieve pdf file. Optimally, I call <code>$window.open(url_generating_pdf</code>) in my angularjs app. This works well and opens in another window, but how to add authentication header to this <code>$window</code> request? In my understanding I cannot download pdf, and print it with ajax, so I am missing this authentication. Or would there be other ways to call url from server, and make the file open in another window?</p> | 33,047,717 | 3 | 2 | null | 2014-04-17 16:31:18.903 UTC | 9 | 2020-01-09 10:04:25.907 UTC | 2017-02-22 17:08:45.98 UTC | null | 1,272,394 | null | 2,576,168 | null | 1 | 23 | angularjs|authentication|download | 58,686 | <p>I think you can add this authentication parameters in URL and do a GET in your server side</p>
<pre><code>//Add authentication headers as params
var params = {
access_token: 'An access_token',
other_header: 'other_header'
};
//Add authentication headers in URL
var url = [url_generating_pdf, $.param(params)].join('?');
//Open window
window.open(url);
</code></pre> |
37,663,854 | Convert ggplot object to plotly in shiny application | <p>I am trying to convert a ggplot object to plotly and show it in a shiny application. But I encountered an error "no applicable method for 'plotly_build' applied to an object of class "NULL""</p>
<p>I was able to return the ggplot object to the shiny application successfully, </p>
<pre><code>output$plot1 <- renderplot({
gp <- ggplot(data = mtcars, aes(x = disp, y = cyl)) + geom_smooth(method = lm, formula = y~x) + geom_point() + theme_gdocs()
})
</code></pre>
<p>but somehow plotly cannot convert it. </p>
<p>My code looks like this </p>
<pre><code>output$plot2 <- renderplotly({
gp <- ggplot(data = mtcars, aes(x = disp, y = cyl)) + geom_smooth(method = lm, formula = y~x) + geom_point() + theme_gdocs()
ggplotly()
})
</code></pre> | 37,664,052 | 2 | 1 | null | 2016-06-06 17:52:43.643 UTC | 11 | 2021-04-23 00:16:54.337 UTC | null | null | null | null | 5,016,733 | null | 1 | 21 | r|ggplot2|shiny|plotly | 23,281 | <p>Try:</p>
<pre><code>library(shiny)
library(ggplot2)
library(ggthemes)
library(plotly)
ui <- fluidPage(
titlePanel("Plotly"),
sidebarLayout(
sidebarPanel(),
mainPanel(
plotlyOutput("plot2"))))
server <- function(input, output) {
output$plot2 <- renderPlotly({
ggplotly(
ggplot(data = mtcars, aes(x = disp, y = cyl)) +
geom_smooth(method = lm, formula = y~x) +
geom_point() +
theme_gdocs())
})
}
shinyApp(ui, server)
</code></pre> |
37,889,914 | What is a projection layer in the context of neural networks? | <p>I am currently trying to understand the architecture behind the <em>word2vec</em> neural net learning algorithm, for representing words as vectors based on their context.</p>
<p>After reading <a href="http://arxiv.org/pdf/1301.3781v3.pdf" rel="noreferrer">Tomas Mikolov paper</a> I came across what he defines as a <strong>projection layer</strong>. Even though this term is widely used when referred to <em>word2vec</em>, I couldn't find a precise definition of what it actually is in the neural net context.</p>
<p><a href="https://i.stack.imgur.com/W46yb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W46yb.png" alt="Word2Vec Neural Net architecture"></a></p>
<p>My question is, in the neural net context, what is a projection layer? Is it the name given to a hidden layer whose links to previous nodes share the same weights? Do its units actually have an activation function of some kind?</p>
<p>Another resource that also refers more broadly to the problem can be found in <a href="http://www.coling-2014.org/COLING%202014%20Tutorial-fix%20-%20Tomas%20Mikolov.pdf" rel="noreferrer">this tutorial</a>, which also refers to a <em>projection layer</em> around page 67.</p> | 58,910,682 | 3 | 2 | null | 2016-06-17 20:30:07.347 UTC | 27 | 2020-12-01 10:25:41.65 UTC | 2017-11-18 21:20:45.083 UTC | null | 3,924,118 | null | 4,747,593 | null | 1 | 59 | machine-learning|nlp|neural-network|word2vec | 18,216 | <p>I find the previous answers here a bit overcomplicated - a projection layer is just a simple matrix multiplication, or in the context of NN, a regular/dense/linear layer, without the non-linear activation in the end (sigmoid/tanh/relu/etc.) The idea is to <strong>project</strong> the (e.g.) 100K-dimensions discrete vector into a 600-dimensions continuous vector (I chose the numbers here randomly, "your mileage may vary"). The exact matrix parameters are learned through the training process.</p>
<p>What happens before/after already depends on the model and context, and is not what OP asks.</p>
<p>(In <a href="https://youtu.be/VkjSaOZSZVs" rel="noreferrer">practice</a> you wouldn't even bother with the matrix multiplication (as you are multiplying a 1-hot vector which has 1 for the word index and 0's everywhere else), and would treat the trained matrix as a lookout table (i.e. the 6257th word in the corpus = the 6257th row/column (depends how you define it) in the projection matrix).)</p> |
37,775,675 | Imageview set color filter to gradient | <p>I have a white image that I'd like to color with a gradient. Instead of generating a bunch of images each colored with a specific gradient, I'd like to do this in code (not xml). </p>
<p>To change an image's color, I use </p>
<pre><code>imageView.setColorFilter(Color.GREEN);
</code></pre>
<p>And this works fine. But how can I apply a gradient color instead of a solid color? <code>LinearGradient</code> doesn't help, because setColorFilter can't be applied to <code>Shader</code> objects. </p>
<p><strong>EDIT</strong>: This is the image I have:</p>
<p><a href="https://i.stack.imgur.com/vKDQi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vKDQi.png" alt="enter image description here"></a></p>
<p>This is what I want:</p>
<p><a href="https://i.stack.imgur.com/lwv96.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lwv96.png" alt="enter image description here"></a></p>
<p>And this is what I'm getting:</p>
<p><a href="https://i.stack.imgur.com/jqHeq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jqHeq.png" alt="enter image description here"></a></p> | 37,816,689 | 3 | 2 | null | 2016-06-12 14:59:29.703 UTC | 14 | 2016-06-17 08:55:40.637 UTC | 2016-06-16 19:40:30.553 UTC | null | 2,022,349 | null | 2,022,349 | null | 1 | 30 | android|imageview|gradient | 13,389 | <p>You have to get <code>Bitmap</code> of your <code>ImageView</code> and redraw same <code>Bitmap</code> with <code>Shader</code></p>
<pre><code>public void clickButton(View v){
Bitmap myBitmap = ((BitmapDrawable)myImageView.getDrawable()).getBitmap();
Bitmap newBitmap = addGradient(myBitmap);
myImageView.setImageDrawable(new BitmapDrawable(getResources(), newBitmap));
}
public Bitmap addGradient(Bitmap originalBitmap) {
int width = originalBitmap.getWidth();
int height = originalBitmap.getHeight();
Bitmap updatedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(updatedBitmap);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, 0, 0, height, 0xFFF0D252, 0xFFF07305, Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawRect(0, 0, width, height, paint);
return updatedBitmap;
}
</code></pre>
<p><strong>UPDATE 3</strong>
I changed: colors of gradient, LinearGradient width = 0 and PorterDuffXfermode.
Here a good picture to understand PorterDuffXfermode:
<a href="https://i.stack.imgur.com/rLIEz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rLIEz.png" alt="enter image description here"></a></p> |
37,004,069 | Error:Jack is required to support java 8 language features | <p>When I tried to update my android project to use Java 8 after getting android studio 2.1 and android N SDK
by adding </p>
<pre><code>compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
</code></pre>
<p>I had this error </p>
<blockquote>
<p>Error:Jack is required to support java 8 language features. Either enable Jack or remove sourceCompatibility JavaVersion.VERSION_1_8.</p>
</blockquote>
<p>What should I do?</p> | 37,004,259 | 1 | 2 | null | 2016-05-03 12:24:28.437 UTC | 27 | 2017-08-19 04:45:00.2 UTC | 2016-07-23 18:16:50.337 UTC | null | 6,051,408 | null | 3,998,402 | null | 1 | 138 | android|android-studio|android-gradle-plugin|jack-compiler | 90,682 | <blockquote>
<p>Error:Jack is required to support java 8 language features. Either
enable Jack or remove sourceCompatibility JavaVersion.VERSION_1_8.</p>
</blockquote>
<p>The error say that you have to <strong>enable Jack</strong>.</p>
<p>To enable support for Java 8 in your Android project, you need to configure your <code>build.gradle</code> file like that</p>
<pre><code>android {
...
compileSdkVersion 23
buildToolsVersion "24rc2"
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
</code></pre> |
47,721,246 | EF Core 2.0 Enums stored as string | <p>I was able to store an enum as a string in the database.</p>
<pre><code>builder.Entity<Company>(eb =>
{
eb.Property(b => b.Stage).HasColumnType("varchar(20)");
});
</code></pre>
<p>But when it comes time to query EF doesn't know to parse the string into an enum. How can I query like so:</p>
<pre><code>context
.Company
.Where(x => x.Stage == stage)
</code></pre>
<p>This is the exception: Conversion failed when converting the varchar value 'Opportunity' to data type int</p> | 50,589,798 | 3 | 4 | null | 2017-12-08 19:50:13.067 UTC | 4 | 2022-07-15 21:08:13.663 UTC | null | null | null | null | 2,097,401 | null | 1 | 30 | entity-framework|ef-core-2.0 | 23,554 | <p>Value Conversions feature is new in EF Core 2.1.</p>
<blockquote>
<p>Value converters allow property values to be converted when reading
from or writing to the database. This conversion can be from one value
to another of the same type (for example, encrypting strings) or from
a value of one type to a value of another type (for example,
converting enum values to and from strings in the database.)</p>
</blockquote>
<pre><code>public class Rider
{
public int Id { get; set; }
public EquineBeast Mount { get; set; }
}
public enum EquineBeast
{
Donkey,
Mule,
Horse,
Unicorn
}
</code></pre>
<p>You can use own conversion</p>
<pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Rider>()
.Property(e => e.Mount)
.HasConversion(
v => v.ToString(),
v => (EquineBeast)Enum.Parse(typeof(EquineBeast), v));
}
</code></pre>
<p>or Built-in converter</p>
<pre><code>var converter = new EnumToStringConverter<EquineBeast>();
modelBuilder
.Entity<Rider>()
.Property(e => e.Mount)
.HasConversion(converter);
</code></pre> |
2,051,632 | IE8 XSS filter: what does it really do? | <p>Internet Explorer 8 has a new security feature, an <a href="http://msdn.microsoft.com/en-us/library/dd565647%28VS.85%29.aspx" rel="noreferrer">XSS filter</a> that tries to intercept cross-site scripting attempts. It's described this way:</p>
<blockquote>
<p>The XSS Filter, a feature new to Internet Explorer 8, detects JavaScript in URL and HTTP POST requests. If JavaScript is detected, the XSS Filter searches evidence of reflection, information that would be returned to the attacking Web site if the attacking request were submitted unchanged. If reflection is detected, the XSS Filter sanitizes the original request so that the additional JavaScript cannot be executed.</p>
</blockquote>
<p>I'm finding that the XSS filter kicks in even when there's no "evidence of reflection", and am starting to think that the filter simply notices when a request is made to another site and the response contains JavaScript.</p>
<p>But even that is hard to verify because the effect seems to come and go. IE has different zones, and just when I think I've reproduced the problem, the filter doesn't kick in anymore, and I don't know why.</p>
<p>Anyone have any tips on how to combat this? What is the filter really looking for? Is there any way for a good-guy to POST data to a 3rd-party site which can return HTML to be displayed in an iframe and not trigger the filter?</p>
<p>Background: I'm loading a JavaScript library from a 3rd-party site. That JavaScript harvests some data from the current HTML page, and posts it to the 3rd-party site, which responds with some HTML to be displayed in an iframe. To see it in action, visit an <a href="http://recipe.aol.com/recipe/oatmeal-butter-cookies/142275" rel="noreferrer">AOL Food</a> page and click the "Print" icon just above the story.</p> | 2,052,195 | 3 | 1 | null | 2010-01-12 19:12:58.41 UTC | 15 | 2011-03-25 05:15:40.81 UTC | null | null | null | null | 14,343 | null | 1 | 45 | internet-explorer-8|xss | 46,736 | <p>What does it really do? It allows third parties to link to a messed-up version of your site.</p>
<p>It kicks in when [a few conditions are met and] it sees a string in the query submission that also exists verbatim in the page, and which it thinks might be dangerous.</p>
<p>It assumes that if <code><script>something()</script></code> exists in both the query string and the page code, then it must be because your server-side script is insecure and reflected that string straight back out as markup without escaping.</p>
<p>But of course apart from the fact that's it's a perfectly valid query someone might have typed that matches by coincidence, it's also just as possible that they match because someone looked at the page and deliberately copied part of it out. For example:</p>
<blockquote>
<p><a href="http://www.bing.com/search?q=%3Cscript+type%3D%22text%2Fjavascript%22%3E" rel="noreferrer">http://www.bing.com/search?q=%3Cscript+type%3D%22text%2Fjavascript%22%3E</a></p>
</blockquote>
<p>Follow that in IE8 and I've successfully sabotaged your Bing page so it'll give script errors, and the pop-out result bits won't work. Essentially it gives an attacker whose link is being followed license to pick out and disable parts of the page he doesn't like — and that might even include other security-related measures like framebuster scripts.</p>
<p>What does IE8 consider ‘potentially dangerous’? A lot more and a lot stranger things than just this script tag. <a href="http://michael-coates.blogspot.com/2009/07/ie-8-anti-xss-bit-overblown.html" rel="noreferrer">eg</a>. What's more, it appears to match against a set of ‘dangerous’ templates using a text pattern system (presumably regex), instead of any kind of HTML parser like the one that will eventually parse the page itself. Yes, use IE8 and your browser is pařṣinͅg HT̈́͜ML w̧̼̜it̏̔h ͙r̿e̴̬g̉̆e͎x͍͔̑̃̽̚.</p>
<p>‘XSS protection’ by looking at the strings in the query is <strong>utterly bogus</strong>. It can't be ‘fixed’; the very concept is intrinsically flawed. Apart from the problem of stepping in when it's not wanted, it can't ever really protect you from anything but the most basic attacks — and the attackers will surely workaround such blocks as IE8 becomes more widely used. If you've been forgetting to escape your HTML output correctly you'll still be vulnerable; all XSS “protection” has to offer you is a false sense of security. Unfortunately Microsoft seem to like this false sense of security; there is similar XSS “protection” in ASP.NET too, on the server side.</p>
<p>So if you've got a clue about webapp authoring and you've been properly escaping output to HTML like a good boy, it's definitely a good idea to disable this unwanted, unworkable, wrong-headed intrusion by outputting the header:</p>
<pre><code>X-XSS-Protection: 0
</code></pre>
<p>in your HTTP responses. (And using <code>ValidateRequest="false"</code> in your pages if you're using ASP.NET.)</p>
<p>For everyone else, who still slings strings together in PHP without taking care to encode properly... well you might as well leave it on. Don't expect it to actually protect your users, but your site is already broken, so who cares if it breaks a little more, right?</p>
<blockquote>
<p>To see it in action, visit an AOL Food page and click the "Print" icon just above the story.</p>
</blockquote>
<p>Ah yes, I can see this breaking in IE8. Not immediately obvious where IE has made the hack to the content that's stopped it executing though... the only cross-domain request I can see that's a candidate for the XSS filter is this one to <code>http://h30405.www3.hp.com/print/start</code>:</p>
<pre><code>POST /print/start HTTP/1.1
Host: h30405.www3.hp.com
Referer: http://recipe.aol.com/recipe/oatmeal-butter-cookies/142275?
csrfmiddlewaretoken=undefined&characterset=utf-8&location=http%253A%2F%2Frecipe.aol.com%2Frecipe%2Foatmeal-butter-cookies%2F142275&template=recipe&blocks=Dd%3Do%7Efsp%7E%7B%3D%25%3F%3D%3C%28%2B.%2F%2C%28%3D3%3F%3D%7Dsp%7Ct@kfoz%3D%25%3F%3D%7E%7C%7Czqk%7Cpspm%3Db3%3Fd%3Do%7Efsp%7E%7B%3D%25%3F%3D%3C%7D%2F%27%2B%2C.%3D3%3F%3D%7Dsp%7Ct@kfoz%3D%25%3F%3D%7E%7C%7Czqk...
</code></pre>
<p>that <code>blocks</code> parameter continues with pages more gibberish. Presumably there is <em>something</em> there that (by coincidence?) is reflected in the returned HTML and triggers one of IE8's messed up ideas of what an XSS exploit looks like.</p>
<p>To fix this, HP need to make the server at h30405.www3.hp.com include the <code>X-XSS-Protection: 0</code> header.</p> |
2,092,327 | What is the most clever and easy approach to sync data between multiple entities? | <p>In today’s world where a lot of computers, mobile devices or web services share data or act like hubs, syncing gets more important. As we all know solutions that sync aren’t the most comfortable ones and it’s best not to sync at all.</p>
<p>I’m still curious how you would implement a syncing solution to sync between multiple entities. There are already a lot of different approaches, like comparing a changed date field or a hash and using the most recent data or letting the user chose what he wants to use in a case of a conflict. Another approach is to try to automatically merge conflicted data (which in my opinion isn’t so clever, because a machine can’t guess what the user meant).</p>
<p>Anyway, here are a couple of questions related to sync that we should answer before starting to implement syncing:</p>
<ul>
<li>What is the most recent data? How do I want to represent it?</li>
<li>What do I do in case of a conflict? Merge? Do I prompt and ask the user what to do?</li>
<li>What do I do when I get into an inconsistent state (e.g. a disconnect due to a flakey mobile network connection)?</li>
<li>What do I have to do when I don’t want to get into an inconsistent state?</li>
<li>How do I resume a current sync that got interrupted?</li>
<li>How do I handle data storage (e.g. MySQL database on a web service, Core Data on an iPhone; and how do I merge/sync the data without a lot of glue code)?</li>
<li>How should I handle edits from the user that happen during the sync (which runs in the background, so the UI isn’t blocked)?</li>
<li>How and in which direction do I propagate changes (e.g. a user creates a „Foo“ entry on his computer and doesn’t sync; then he’s on the go and creates another „Foo“ entry; what happens when he tries to sync both devices)? Will the user have two „Foo“ entries with different unique IDs? Will the user have only one entry, but which one?</li>
<li>How should I handle sync when I have hierarchical data? Top-down? Bottom-up? Do I treat every entry atomically or do I only look at a supernode? How big is the trade-off between oversimplifying things and investing too much time into the implementation?</li>
<li>…</li>
</ul>
<p>There are a lot of other questions and I hope that I could inspire you enough. Syncing is a fairly general problem. Once a good, versatile syncing approach is found, it should be easier to apply it to a concrete application, rather than start thinking from scratch. I realize that there are already a lot of applications that try to solve (or successfully solve) syncing, but they are already fairly specific and don’t give enough answers to syncing approaches in general.</p> | 2,094,197 | 3 | 0 | null | 2010-01-19 09:12:52.883 UTC | 54 | 2021-06-17 09:34:32.77 UTC | 2016-01-10 15:25:47.153 UTC | null | 4,370,109 | null | 133,166 | null | 1 | 51 | database|algorithm|mobile|synchronization | 13,955 | <p>Where I work we have developed an "offline" version of our main (web) application for users to be able to work on their laptops in locations where they do not have internet access. When the user comes back to the main site they need to synchronise the data they entered offline with our main application.</p>
<p>So, to answer your questions:</p>
<blockquote>
<ul>
<li>What is the most recent data? How do I want to represent it?</li>
</ul>
</blockquote>
<p>We have a LAST_UPDATED_DATE column on every table. The server keeps a track of when synchronisations take place, so when the offline application requests a synchronisation the server says "hey, only give me data changed since this date".</p>
<blockquote>
<ul>
<li>What do I do in case of a conflict? Merge? Do I prompt and ask
the user what to do?</li>
</ul>
</blockquote>
<p>In our case the offline application is only able to update a relatively small subset of all the data. As each record is synchronised we check if it is one of these cases, and if so then we compare the LAST_UPDATED_DATE for the record both online and offline. If the dates are different then we also check the values (because it's not a conflict if they're both updated to the same value). If there is a conflict we record the difference, set a flag to say there is at least one conflict, and carry on checking the rest of the details. Once the process is finished then if the "isConflict" flag is set the user is able to go to a special page which displays the differences and decide which data is the "correct" version. This version is then saved on the host and the "isConflict" flag is reset.</p>
<blockquote>
<ul>
<li>What do I have to do when I don’t want to get into an inconsistent
state?</li>
<li>How do I resume a current sync that got interrupted?</li>
</ul>
</blockquote>
<p>Well, we try to avoid getting into an inconsistent state in the first place. If a synchronistaion is interrupted for any reason then the last_synchronisation_date is not updated, and so the next time a synchronisation is started it will start from the same date as the start date for the previous (interuppted) synchronisation.</p>
<blockquote>
<ul>
<li>How do I handle data storage (e.g. MySQL database on a web service, Core
Data on an iPhone; and how do I
merge/sync the data without a lot of
glue code)?</li>
</ul>
</blockquote>
<p>We use standard databases on both applications, and Java objects in between. The objects are serialised to XML (and gzipped to speed up the transfer) for the actual synchronisation process, then decompressed/deserialised at each end.</p>
<blockquote>
<ul>
<li>How should I handle edits from the user that happen during the sync
(which runs in the background, so the
UI isn’t blocked)?</li>
</ul>
</blockquote>
<p>These edits would take place after the synchronisation start date, and so would not be picked up on the other side until the next synchronisation.</p>
<blockquote>
<ul>
<li>How and in which direction do I propagate changes (e.g. a user creates
a „Foo“ entry on his computer and
doesn’t sync; then he’s on the go and
creates another „Foo“ entry; what
happens when he tries to sync both
devices)? Will the user have two „Foo“
entries with different unique IDs?
Will the user have only one entry, but
which one?</li>
</ul>
</blockquote>
<p>That's up to you to decide how you want to handle this particular Foo... i.e. depending on what the primary key of Foo is and how you determine whether one Foo is the same as another.</p>
<blockquote>
<ul>
<li>How should I handle sync when I have hierarchical data? Top-down?
Bottom-up? Do I treat every entry
atomically or do I only look at a
supernode?</li>
</ul>
</blockquote>
<p>The synchronisation is atomic, so if one record fails then the whole process is marked as incomplete, similar to a subversion commit transaction.</p>
<blockquote>
<ul>
<li>How big is the trade-off between oversimplifying things and investing
too much time into the implementation?</li>
</ul>
</blockquote>
<p>I'm not sure exactly what you mean, but I'd say it all depends on your situation and the type / quantity of data you want to sync. It might take a long time to design and implement the process, but it's possible.</p>
<p>Hope that helps you or at least gives you a few ideas! :)</p> |
8,671,702 | Passing list of parameters to SQL in psycopg2 | <p>I have a list of ids of rows to fetch from database. I'm using python and psycopg2, and my problem is how to effectively pass those ids to SQL? I mean that if I know the length of that list, it is pretty easy because I can always manually or automatically add as many "%s" expressions into query string as needed, but here I don't know how much of them I need. It is important that I need to select that rows using sql "id IN (id1, id2, ...)" statement. I know that it is possible to check the length of the list and concatenate suitable number of "%s" into query string, but I'm afraid that it would be very slow and ugly. Does anyone have an idea on how to solve it? And please don't ask why I need to do it with "IN" statement - it is a benchmark which is a part of my class assignment. Thanks in advance!</p> | 8,671,854 | 3 | 1 | null | 2011-12-29 18:21:04.927 UTC | 10 | 2022-02-28 12:30:58.253 UTC | 2011-12-29 18:27:25.36 UTC | null | 183,066 | null | 785,454 | null | 1 | 60 | python|postgresql|psycopg2 | 34,472 | <p>Python tuples are converted to sql lists in psycopg2:</p>
<pre><code>cur.mogrify("SELECT * FROM table WHERE column IN %s;", ((1,2,3),))
</code></pre>
<p>would output</p>
<pre><code>'SELECT * FROM table WHERE column IN (1,2,3);'
</code></pre>
<p>For Python newcomers: It is unfortunately important to use a tuple, not a list here. Here's a second example:</p>
<pre><code>cur.mogrify("SELECT * FROM table WHERE column IN %s;",
tuple([row[0] for row in rows]))
</code></pre> |
19,322,345 | How do I change the default index page in Apache? | <p>I would like to change the default web page that shows up when I browse my site. I currently have a reporting program running, and it outputs a file called index.html. I cannot change what it calls the file. Therefore, my landing page must be called something else. Right now, when I browse my site it takes me to the reporting page.</p>
<p>From what I see, whatever you call index.html it will pull that up as your default. I want to change that to landing.html. How do I do this?</p>
<p>I am a folder (Folding @ Home). The reporting program is HFM.net. HFM can output an html file with my current folding statistics. It names the html file index. I do not want that to be my default home page. I would like a menu-like landing where I can choose if I want to see my stats, or something else. The website is at /home/tyler/Documents/hfm/website (landing.html and hfm's index.html are here). Apache2 is in its default directory.</p>
<p>I'm also running Ubuntu 13.04.</p> | 19,322,414 | 3 | 1 | null | 2013-10-11 15:54:25.37 UTC | 19 | 2021-08-18 17:09:02.183 UTC | 2013-10-11 16:45:14.033 UTC | null | 1,340,075 | null | 1,340,075 | null | 1 | 81 | html|apache|indexing|default | 452,082 | <p>I recommend using <code>.htaccess</code>. You only need to add:</p>
<pre><code>DirectoryIndex home.php
</code></pre>
<p>or whatever page name you want to have for it.</p>
<p><strong>EDIT</strong>: basic htaccess tutorial.</p>
<p>1) Create <code>.htaccess</code> file in the directory where you want to change the index file.</p>
<ul>
<li>no extension</li>
<li><code>.</code> in front, to ensure it is a "hidden" file</li>
</ul>
<p>Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.</p>
<p>2) Set server to allow reading of <code>.htaccess</code> files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)</p>
<p>Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at <code>/etc/apache2/sites-available/default</code> for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:</p>
<pre><code><Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
</code></pre>
<p>Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:</p>
<pre><code>sudo service apache2 restart
</code></pre>
<p>Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.</p>
<p>Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another <code>.htaccess</code> file in that sub-site's root and it will overwrite the declaration in the parent.</p> |
562,108 | How do I use a GlobalContext property in a log4net appender name? | <p>I'm trying to customise a log4net file path to use a property I have set in the <code>log4net.GlobalContext.Properties</code> dictionary.</p>
<pre><code>log4net.GlobalContext.Properties["LogPathModifier"] = "SomeValue";
</code></pre>
<p>I can see that this value is set correctly when debugging through it. and then in my configuration</p>
<pre><code><file type="log4net.Util.PatternString"
value="Logs\%appdomain_%property{LogPathModifier}.log" />
</code></pre>
<p>However, the output of this gives me "_(null).log" at the end of the path. What gives?</p> | 572,251 | 4 | 0 | null | 2009-02-18 17:41:41.063 UTC | 16 | 2014-10-07 23:28:13.987 UTC | 2013-03-05 14:24:51.637 UTC | null | 3,619 | Long Pham | 67,965 | null | 1 | 40 | c#|log4net | 43,237 | <p>I ran into the same behavior and solved it by setting the global variable before calling the XmlConfigurator... Here is what I am successfully using:</p>
<p>log4net.config details:</p>
<pre><code><appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
<File type="log4net.Util.PatternString" value="App_Data/%property{LogName}" />
...
</appender>
</code></pre>
<p>Global.asax details:</p>
<pre><code>private static readonly log4net.ILog log = log4net.LogManager.GetLogger("Global.asax");
void Application_Start(object sender, EventArgs e)
{
// Set logfile name and application name variables
log4net.GlobalContext.Properties["LogName"] = GetType().Assembly.GetName().Name + ".log";
log4net.GlobalContext.Properties["ApplicationName"] = GetType().Assembly.GetName().Name;
// Load log4net configuration
System.IO.FileInfo logfile = new System.IO.FileInfo(Server.MapPath("log4net.config"));
log4net.Config.XmlConfigurator.ConfigureAndWatch(logfile);
// Record application startup
log.Debug("Application startup");
}
</code></pre>
<p>Hope this helps...</p> |
42,974,450 | Iterate over Worksheets, Rows, Columns | <p>I want to print all data (all rows) of a specific column in python using <code>openpyxl</code> I am working in this way;</p>
<pre><code>from openpyxl import load_workbook
workbook = load_workbook('----------/dataset.xlsx')
sheet = workbook.active
for i in sheet:
print(sheet.cell(row=i, column=2).value)
</code></pre>
<p>But it gives </p>
<blockquote>
<p>if row < 1 or column < 1:
TypeError: unorderable types: tuple() < int()</p>
</blockquote>
<p>Because i am iterating in <code>row=i</code>. If I use <code>sheet.cell(row=4, column=2).value</code> it print the value of cell. But how can I iterate over all document?</p>
<p><strong>Edit 1</strong></p>
<p>On some research, it is found that data can be get using Sheet Name. The <code>Sheet 1</code> exists in the <code>.xlsx</code> file but its data is not printing. Any problem in this code? </p>
<pre><code>workbook = load_workbook('---------------/dataset.xlsx')
print(workbook.get_sheet_names())
worksheet =workbook.get_sheet_by_name('Sheet1')
c=2
for i in worksheet:
d = worksheet.cell(row=c, column=2)
if(d.value is None):
return
else:
print(d.value)
c=c+1
</code></pre> | 42,977,775 | 3 | 3 | null | 2017-03-23 11:15:11.143 UTC | 14 | 2020-01-10 04:02:17.577 UTC | 2018-09-19 07:43:37.5 UTC | null | 7,414,759 | null | 6,705,756 | null | 1 | 18 | python|openpyxl | 52,204 | <p>Read the <a href="http://openpyxl.readthedocs.io" rel="noreferrer">OpenPyXL Documentation</a></p>
<p>Iteration over all <code>worksheets</code> in a <code>workbook</code>, for instance: </p>
<pre><code>for n, sheet in enumerate(wb.worksheets):
print('Sheet Index:[{}], Title:{}'.format(n, sheet.title))
</code></pre>
<blockquote>
<p><strong>Output</strong>: </p>
<pre><code>Sheet Index:[0], Title: Sheet
Sheet Index:[1], Title: Sheet1
Sheet Index:[2], Title: Sheet2
</code></pre>
</blockquote>
<hr>
<p>Iteration over all <code>rows</code> and <code>columns</code> in <strong>one</strong> Worksheet: </p>
<pre><code>worksheet = workbook.get_sheet_by_name('Sheet')
for row_cells in worksheet.iter_rows():
for cell in row_cells:
print('%s: cell.value=%s' % (cell, cell.value) )
</code></pre>
<p><strong>Output</strong>: </p>
<pre><code><Cell Sheet.A1>: cell.value=²234
<Cell Sheet.B1>: cell.value=12.5
<Cell Sheet.C1>: cell.value=C1
<Cell Sheet.D1>: cell.value=D1
<Cell Sheet.A2>: cell.value=1234
<Cell Sheet.B2>: cell.value=8.2
<Cell Sheet.C2>: cell.value=C2
<Cell Sheet.D2>: cell.value=D2
</code></pre>
<hr>
<p>Iteration over all <code>columns</code> of <strong>one</strong> <code>row</code>, for instance <code>row==2</code>: </p>
<pre><code>for row_cells in worksheet.iter_rows(min_row=2, max_row=2):
for cell in row_cells:
print('%s: cell.value=%s' % (cell, cell.value) )
</code></pre>
<p><strong>Output</strong>: </p>
<pre><code><Cell Sheet.A2>: cell.value=1234
<Cell Sheet.B2>: cell.value=8.2
<Cell Sheet.C2>: cell.value=C2
<Cell Sheet.D2>: cell.value=D2
</code></pre>
<hr>
<p>Iteration over <strong>all</strong> <code>rows</code>, only <code>column</code> <strong>2</strong>: </p>
<pre><code>for col_cells in worksheet.iter_cols(min_col=2, max_col=2):
for cell in col_cells:
print('%s: cell.value=%s' % (cell, cell.value))
</code></pre>
<p><strong>Output</strong>: </p>
<pre><code><Cell Sheet.B1>: cell.value=12.5
<Cell Sheet.B2>: cell.value=8.2
<Cell Sheet.B3>: cell.value=9.8
<Cell Sheet.B4>: cell.value=10.1
<Cell Sheet.B5>: cell.value=7.7
</code></pre>
<p><strong><em>Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice: 4.3.3.2</em></strong> </p> |
37,284,216 | Spark SQL passing a variable | <p>I have following Spark sql and I want to pass variable to it. How to do that? I tried following way.</p>
<pre><code> sqlContext.sql("SELECT count from mytable WHERE id=$id")
</code></pre> | 37,284,383 | 6 | 1 | null | 2016-05-17 18:57:48.09 UTC | 1 | 2022-07-21 07:28:20.73 UTC | 2016-05-17 19:11:17.12 UTC | null | 1,410,669 | null | 1,260,441 | null | 1 | 11 | sql|select | 43,729 | <p>You are almost there just missed <code>s</code> :)</p>
<pre><code>sqlContext.sql(s"SELECT count from mytable WHERE id=$id")
</code></pre> |
32,239,353 | Command Validation in DDD with CQRS | <p>I am learning DDD and making use of the CQRS pattern. I don't understand how to validate business rules in a command handler without reading from the data store. </p>
<p>For example, Chris wants to give Ashley a gift.</p>
<p>The command might be GiveGiftCommand. </p>
<p>At what point would I verify Chris actually owns the gift he wants to give? And how would I do that without reading from the database?</p> | 32,245,241 | 3 | 4 | null | 2015-08-27 01:41:22.477 UTC | 9 | 2017-07-29 02:53:14.143 UTC | null | null | null | null | 234,867 | null | 1 | 19 | validation|domain-driven-design|cqrs | 10,576 | <p>There are different views and opinions about validation in command handlers.</p>
<p>Command <strong>can be rejected</strong>, we can say <strong>No</strong> to the command if it is not valid.</p>
<p>Typically you would have a validation that occurs on the UI and that might be duplicated inside the command handler (some people tend to put it in the domain too). Command handler then can run simple validation that can occur outside of the entity like is data in correct format, are there expected values, etc.</p>
<p>Business logic, on the other hand, <strong>should not be in a command handler</strong>. It should be in your domain.</p>
<p>So I think that the underlying question is...</p>
<h2>Should I query the read side from Command Handlers?</h2>
<p>I would say no. Do not use the read model in the command handlers or domain logic. But you <strong>can always query your read model from the client</strong> to fetch the data you need in for your command and to validate the command. You would query the read side on the client to check would if Chris actually owns the gift he wants to give. Of course, the validation involving a read model is likely to be eventually consistent, which is of course another reason a command could be rejected from the aggregate, inside the command handler.</p>
<p>Some people disagree saying that if you require your commands to contain the data the handler needs to validate your command, than you can never change the validation logic within your handler/domain without affecting the client as well. This exposes too much of the domain knowledge to the client and go against the fact that the client only wants to express an intent. So they would tend to provide an <code>GiftService</code> interface (which are part of the ubiquitous language) to your command handler and then implement the interface as needed - which might include querying the read side.</p>
<p>I think that the <strong>client should always assume that the commands it issues will succeed</strong>. Calling the read side to validate the command shouldn't be needed. Getting two contradictory commands is very unlikely (users creating accounts with the same email address). Then you should have a mean to issue a corrective action, something like for example a Saga/Process Manager. So instead making a corrective action would be less problematic that if the command could have been validated and not dispatched in the first place.</p> |
4,210,254 | How to sign a JAR file using a .PFX file | <p>We sign our .net code with a .PFX cert file. A colleague now needs to use the the same cert to sign a .jar file for a customer.</p>
<p>Can someone point me to a link or an example of how I can do this please?</p>
<p>The jar file will be used on Oracle Web Logic Server running on Solaris.</p>
<p>And, once signed do we need to send out anything other signed jar file?</p>
<p>Thanks.</p> | 4,210,860 | 1 | 0 | null | 2010-11-17 23:26:03.537 UTC | 10 | 2021-11-25 22:01:32.447 UTC | null | null | null | null | 30,225 | null | 1 | 13 | certificate|code-signing|pfx|jar-signing | 18,078 | <p>[Link updated thanks to @Ezequiel]</p>
<p><a href="https://support.comodo.com/index.php?/Knowledgebase/Article/View/1207/7/how-to-sign-java-jar-files" rel="nofollow noreferrer">https://support.comodo.com/index.php?/Knowledgebase/Article/View/1207/7/how-to-sign-java-jar-files</a></p>
<p>Check if you can see the certs</p>
<pre><code>-> keytool -list -v -storetype pkcs12 -keystore file.pfx
</code></pre>
<p>Note the alias.</p>
<p>If it can:
<code>-> jarsigner -storetype pkcs12 -keystore file.pfx myjar.jar alias</code></p>
<p>That's all there is to it.</p>
<p>To verify the signature of the file...</p>
<pre><code>-> jarsigner -verify JAR_FILE
</code></pre>
<p>Where JAR_FILE is the file to be signed.</p> |
39,135,233 | Create a paginated PDF—Mac OS X | <p>I am making a Mac app (in Swift 3 using Xcode 8, Beta 5) with which the user can make a long note and export it as a PDF. </p>
<p>To create this PDF, I am using Cocoa's <code>dataWithPDF:</code> method with the following code:</p>
<pre><code>do {
// define bounds of PDF as the note text view
let rect: NSRect = self.noteTextView.bounds
// create the file path for the PDF
if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first {
// add the note title to path
let path = NSURL(fileURLWithPath: dir).appendingPathComponent("ExportedNote.pdf")
// Create a PDF of the noteTextView and write it to the created filepath
try self.noteTextView.dataWithPDF(inside: rect).write(to: path!)
} else {
print("Path format incorrect.") // never happens to me
}
} catch _ {
print("something went wrong.") // never happens to me
}
</code></pre>
<p>This completely works, but there's one problem: the PDF goes only on one page, which means the page gets really long when there's a lot of text in the note. How can I force the PDF to go onto as many letter-size pages as it needs, either while my app is exporting the PDF or right after?</p> | 39,479,101 | 1 | 4 | null | 2016-08-25 01:12:14.25 UTC | 9 | 2017-03-13 00:37:35.047 UTC | 2016-09-05 20:34:11.707 UTC | null | 5,700,898 | null | 5,700,898 | null | 1 | 13 | swift|macos|cocoa|pdf|swift3 | 3,438 | <p>After weeks of frustration, I have come up with the definitive way of creating a paginated PDF in a Swift app. And it's not as complicated as it seems (the following is based on <strong>Swift 2</strong>):</p>
<hr>
<p><strong><em>Note</em></strong>: Before you read more, you should know I made an easy tool on Github so you can do this in many fewer steps (and in Swift 3, which no longer needs any Objective-C). <a href="https://github.com/owlswipe/CocoaPDFCreator" rel="noreferrer">Check that out here</a>.</p>
<hr>
<p><strong>Step 1:</strong> Set up your App Sandboxing correctly. Every submitted Mac app requires App Sandboxing correctly, so it's best to just take 30 seconds to set it up right now. If it's not on already, go to your Target's settings and then the Capabilities header. Turn on App Sandboxing, up at the top. You should see many sub-capabilities, enable any one of these your app needs, and make sure to have <code>User Selected File</code> set to <code>Read/Write</code>.</p>
<p><strong>Step 2:</strong> Add this function to your code, which will create an invisible webview and add your text into it.</p>
<pre><code>func createPDF(fromHTMLString: String) {
self.webView.mainFrame.loadHTMLString(htmlString, baseURL: nil)
self.delay(1) {
MyCreatePDFFile(self.webView)
}
}
</code></pre>
<p><strong>Step 3:</strong> Create the <code>delay()</code> function to allow Xcode to wait a second for the HTML to be loaded into the web view. </p>
<pre><code> func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
</code></pre>
<p>(Note: For the Swift 3 version of this function, <a href="https://stackoverflow.com/a/24318861/5700898">go here</a>.)</p>
<p><strong>Step 4:</strong> Add the declaration of our WebView above the function you added in step 2.</p>
<pre><code>var webView = WebView()
</code></pre>
<p><strong>Step 5:</strong> You may notice that we haven't created the <code>MyCreatePDFFile()</code> function yet. Turns out that there is no way to convert this WebView to a PDF with Swift, so we're going to have to turn to Objective-C (<em>groan</em>). Yep, you're going to have to run some Objective-C in your Swift app. </p>
<p><strong>Step 6:</strong> Create a <code>.m</code> file by going to <code>File</code> -> <code>New</code> -> <code>File</code> (or by hitting <kbd>CMD</kbd> + <kbd>N</kbd>) then double-clicking on <code>Objective-C File</code>. Name it <code>CreatePDF.m</code> and leave it as an Empty File.</p>
<p><strong>Step 7:</strong> When adding your <code>.m</code> file, you should get a prompt to add a bridging header:</p>
<p><img src="https://i.stack.imgur.com/nakLZ.png" alt="enter image description here"></p>
<p>Click <code>Yes</code>. </p>
<p>If you did not see the prompt, or accidentally deleted your bridging header, add a new <code>.h</code> file to your project and name it <code><#YourProjectName#>-Bridging-Header.h</code></p>
<p>In some situations, particularly when working with ObjC frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your Bridging Header <code>.h</code> file named as mentioned above, then make sure you link its path in your target's project settings like this:</p>
<p><img src="https://i.stack.imgur.com/8LiwF.gif" alt="enter image description here"></p>
<p><strong>Step 8:</strong> Create a <code>.h</code> file by going to <code>File</code> -> <code>New</code> -> <code>File</code> (or by hitting <kbd>CMD</kbd> + <kbd>N</kbd>) then double-clicking on <code>Header File</code>. Name it <code>CreatePDF.h</code>.</p>
<p><strong>Step 9:</strong> In your <code>CreatePDF.h</code> file, add the following code, which imports Cocoa and WebKit and sets up for your PDF creation function:</p>
<pre><code>#ifndef CreatePDF_h
#define CreatePDF_h
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
@interface Thing : NSObject
void MyCreatePDFFile(WebView *thewebview);
@end
#endif /* CreatePDF_h */
</code></pre>
<p><strong>Step 10:</strong> Time to setup the <code>.m</code> file for the PDF creation function. Start by adding this to the empty <code>.m</code> file:</p>
<pre><code>#import "CreatePDF.h"
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
@implementation Thing
void MyCreatePDFFile(WebView *thewebview) {
}
@end
</code></pre>
<p><strong>Step 11:</strong> Now you can add the code to the <code>MyCreatePDFFile(..)</code> function. Here's the function itself (this goes inside the currently-empty <code>void</code> function):</p>
<pre><code>NSDictionary *printOpts = @{
NSPrintJobDisposition: NSPrintSaveJob // sets the print job to save the PDF instead of print it.
};
NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printOpts];
[printInfo setPaperSize:NSMakeSize(595.22, 841.85)]; // sets the paper size to a nice size that works, you can mess around with it
[printInfo setTopMargin:10.0];
[printInfo setLeftMargin:10.0];
[printInfo setRightMargin:10.0];
[printInfo setBottomMargin:10.0];
NSPrintOperation *printOp = [NSPrintOperation printOperationWithView:[[[thewebview mainFrame] frameView] documentView] printInfo:printInfo]; // sets the print operation to printing the WebView as a document with the print info set above
printOp.showsPrintPanel = NO; // skip the print question and go straight to saving pdf
printOp.showsProgressPanel = NO;
[printOp runOperation];
</code></pre>
<p><strong>Step 12:</strong> Now add this to your bridging header to allow your Swift file to see that Objective-C function you just made.</p>
<pre><code>#import "CreatePDF.h"
</code></pre>
<p><strong>Step 13:</strong> There shouldn't be any errors from this code left, but if there are please comment below about them. </p>
<p><strong>Step 14:</strong> To call the <code>createPDF</code> function from anywhere your Swift file, do the following:</p>
<pre><code>createPDF("<h1>Title!</h1><p>\(textview.text!)</p>")
</code></pre>
<p>The string you see inside <code>createPDF</code> is HTML, and can be edited to anything HTML. If you don't know HTML, you can see some of the very basics <a href="http://www.w3schools.com/html/html_basic.asp" rel="noreferrer">right here</a>.</p>
<p><strong>That should be it!</strong> You should now be able to create paginated PDFs right from Swift, on Cocoa/Mac apps.</p>
<hr>
<h2>Credits</h2>
<ul>
<li><p><a href="https://stackoverflow.com/questions/39318882/call-an-objective-c-method-from-swift-app">How to run Objective-C code in a Swift project</a>, thanks to Matt.</p></li>
<li><p><a href="http://lists.apple.com/archives/cocoa-dev/2014/Aug/msg00292.html" rel="noreferrer">How to write a PDF from a WebView in Obj-C</a>, thanks to some random web forum.</p></li>
<li><a href="https://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift/24005242#24005242">How to create a bridging header manually</a>, thanks to Logan.</li>
<li><a href="https://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861">Delay function in Swift</a>, thanks to Matt.</li>
<li><a href="https://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift/24005242#24005242">Images</a>, thanks to Logan.</li>
</ul>
<p>Note: This answer was tested to work with Xcode 7, Swift 2, and OS X El Captian. If you have any problems using it with Xcode 8/Swift 3/macOS Sierra, let me know.</p> |
6,834,579 | How to replace line-breaks with commas using grep in TextWrangler? | <p>I have a text-file container a number of lines, which I need to turn into a csv. What is the easiest way to replace all the line-breaks with ", ". I have TextWrangler and read that it would do so by using grep and regular expressions, but have very little experience using regular expressions and don't know how grep works. Anyone who can help me get started?</p> | 6,834,707 | 2 | 0 | null | 2011-07-26 18:15:41.743 UTC | 3 | 2020-01-07 04:09:22.23 UTC | null | null | null | null | 864,046 | null | 1 | 19 | regex|grep|line-breaks|textwrangler | 70,910 | <ol>
<li>Choose Find from the Search menu. TextWrangler opens the Find window.</li>
<li>Select the "Grep" checkbox</li>
<li>Type the string you are looking for ("\n" or "\r\n" or "\r") in the Find textfield.</li>
<li>Type the replace string (", ") in the Replace text field.</li>
<li>Click "Replace All"</li>
</ol>
<p>See chapters 7 and 8 of the <a href="http://pine.barebones.com/manual/TextWrangler_User_Manual.pdf" rel="noreferrer">TextWrangler User Manual</a> if you have problems.</p> |
6,860,686 | Extend AuthorizeAttribute Override AuthorizeCore or OnAuthorization | <p>Using ASP.NET MVC I am creating a custom Authorize attribute to take care of some custom authorization logic. I have looked at a lot of examples and it is pretty straight forward but my question is which method is best to override, AuthorizeCore or OnAuthorization? I have seen many examples overriding one or the other. Is there a difference? </p> | 6,860,804 | 2 | 1 | null | 2011-07-28 14:31:01.497 UTC | 13 | 2014-02-17 15:14:57.01 UTC | null | null | null | null | 489,213 | null | 1 | 55 | asp.net-mvc|asp.net-mvc-3|authorization|action-filter | 19,076 | <p>The clue is in the return types:</p>
<p><code>AuthorizeCore</code> returns a boolean - it is <em>decision making</em> code. This should be limited to looking at the user's identity and testing which roles they are in etc. etc. Basically it should answer the question: </p>
<p><code>Do I want this user to proceed?</code> </p>
<p>It should not perform any additional activities "on the side".</p>
<p><code>OnAuthorize</code> returns void - this is where you put any <em>functionality</em> that needs to occur at this point. e.g. Write to a log, store some data in session etc etc.</p> |
7,462,398 | Django template, if tag based on current URL value | <p>I want to be able to do an if tag based on the current URL value.</p>
<p>for example, if the current page's url is <code>accounts/login/</code> then don't show a link, without passing a variable from the view.</p>
<p>I am not sure how I can write an <code>{% if %}</code> tag for this, is it possible?</p> | 7,462,469 | 3 | 1 | null | 2011-09-18 15:18:44.96 UTC | 5 | 2021-09-23 07:33:38.893 UTC | null | null | null | null | 851,920 | null | 1 | 32 | django | 25,851 | <p>If you pass the "request" object to your template, then you are able to use this:</p>
<pre><code>{% if request.get_full_path == "/account/login/" %}
</code></pre> |
7,231,157 | How to submit form on change of dropdown list? | <p>I am creating a page in JSP where I have a dropdown list and once the user selects a value he has to click on the go button and then the value is sent to the Servlet.</p>
<pre><code> </select>
<input type="submit" name="GO" value="Go"/>
</code></pre>
<p>How do I make it so that it does it on change? E.g. when the user selects John all his details are retrived from the DB and displayed. I want the system to do it without having to click the go button.</p> | 7,231,215 | 4 | 0 | null | 2011-08-29 14:00:58.77 UTC | 56 | 2022-09-15 01:53:36.187 UTC | 2011-08-29 14:07:08.223 UTC | null | 157,882 | null | 329,563 | null | 1 | 359 | html|jsp | 761,979 | <p>Just ask assistance of JavaScript.</p>
<pre><code><select onchange="this.form.submit()">
...
</select>
</code></pre>
<h3>See also:</h3>
<ul>
<li><a href="http://www.htmldog.com/guides/htmlintermediate/javascript/" rel="noreferrer">HTML dog - JavaScript tutorial</a></li>
</ul> |
21,775,082 | how to remove duplicates in SAS data step | <p>How to remove duplicates in SAS data step. </p>
<pre><code>data uscpi;
input year month cpi;
datalines;
1990 6 129.9
1990 7 130.4
1990 8 131.6
1990 9 132.7
1991 4 135.2
1991 5 135.6
1991 6 136.0
1991 7 136.2
;
run;
PROC SORT DATA = uscpi OUT = uscpi_dist NODUPKEY;
BY year ;
RUN;
</code></pre>
<p>i can with proc step, but how to remove it in data step. Thanks in advance</p> | 21,775,491 | 1 | 2 | null | 2014-02-14 09:10:33.97 UTC | 1 | 2014-09-18 10:25:59.117 UTC | 2014-02-14 09:14:32.643 UTC | null | 426,834 | null | 3,298,261 | null | 1 | 1 | duplicates|sas|datastep | 38,731 | <p>You can use the <code>first.</code> & <code>last.</code> automatic variables created by SAS when using <code>by-group</code> processing. They give more control on which row you consider as duplicate.
Please read the manual to <a href="https://support.sas.com/documentation/cdl/en/lrcon/62955/HTML/default/viewer.htm#a001283274.htm" rel="noreferrer">understand by group processing in a Data Step</a></p>
<pre><code> data uscpi_dedupedByYear;
set uscpi_sorted;
by year;
if first.year; /*only keep the first occurence of each distinct year. */
/*if last.year; */ /*only keep the last occurence of each distinct year*/
run;
</code></pre>
<p>A lot depends on who your input dataset is sorted. For ex: If your input dataset is sorted by year & month and you use <code>if first.year;</code> then you can see that it only keeps the earliest month in any given year. However, if your dataset is sorted by <code>year & descending month</code> then <code>if first.year;</code> retains last month in any given year.</p>
<p>This behaviour obviously differs from how <code>nodupkey</code> works.</p> |
42,888,024 | Git Bash (mintty) is extremely slow on Windows 10 OS | <p>I installed Git on my <strong>Windows 10</strong> a couple of months ago. It worked well for some time. But now, it's running very slow.</p>
<p>The <code>git status</code> command takes <strong>7 seconds</strong> to execute, and <code>git stash</code> takes <strong>many minutes</strong> for stashing (even if there is nothing to stash). Also, I would like to point out that <code>git status</code> prints the result instantaneously, but I can not enter a new command for a few seconds, as shown in the image below.</p>
<p><a href="https://i.stack.imgur.com/Fo2fQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Fo2fQ.png" alt="The screen is stuck like this for 7 seconds" /></a></p>
<p>I have tried solutions to similar problems like <a href="https://stackoverflow.com/questions/4485059/git-bash-is-extremely-slow-in-windows-7-x64">link1</a>, <a href="http://dev.nettreo.com/post/2010/03/19/Solution-to-slow-Git-bash-when-logged-in-as-a-domain-user.aspx" rel="noreferrer">link2</a>, etc., but none of these have worked.</p>
<p><strong>P.S.:</strong> I use Windows Defender antivirus, and it is <strong>NOT</strong> making my Bash slow. Also, <strong>cmd</strong> takes more time to execute <code>git</code> commands while <strong>git bash</strong> takes longer to run any command.</p>
<hr />
<p><strong>Update:</strong> I have switched to Ubuntu, and therefore, I don't use Windows presently. So, there is no way I can check if any of the solutions work for me. I have accepted the answer provided by <a href="https://stackoverflow.com/users/5276055/pschild">@pschild</a> since it has the most upvotes and seems to have worked for many people.</p> | 43,762,587 | 20 | 10 | null | 2017-03-19 14:55:33.87 UTC | 39 | 2022-07-28 17:32:53.41 UTC | 2021-11-28 23:34:02.297 UTC | null | 7,263,373 | null | 7,263,373 | null | 1 | 115 | git|windows-10|git-bash|mingw-w64|mintty | 106,939 | <p>I recently ran into the exact same issue. After trying all the advice from this thread and a lot of other threads, I finally found a solution <a href="https://github.com/git-for-windows/git/issues/1129" rel="noreferrer">here</a>, respectively in the linked issue <a href="https://github.com/git-for-windows/git/issues/1070" rel="noreferrer">here</a>.</p>
<p><strong>Disabling AMD Radeon graphics driver in the Windows device manager</strong> and switching to integrated Intel HD graphics <strong>worked for me</strong> - for whatever reason.</p>
<p>Hope that helps! </p>
<p>In my case, I found <strong>sh.exe</strong> shell to be significantly faster than bash.exe. You can find sh.exe in git_install_dir/bin.</p>
<p>Hope this helps people having this issue while only having integrated Intel HD graphics!</p> |