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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,147,457 | uninstall ruby version from rbenv | <p>How to uninstall or remove ruby version from <a href="https://github.com/rbenv/rbenv" rel="noreferrer">rbenv</a>. I have installed two versions of ruby. While switching to ruby 1.9.3, I am getting segmentation fault. Can anyone please help, how to remove a particular version from rbenv?</p> | 9,164,547 | 4 | 0 | null | 2012-02-05 06:45:21.24 UTC | 12 | 2021-04-16 20:13:02.233 UTC | 2020-09-04 04:34:55.687 UTC | null | 63,810 | null | 614,990 | null | 1 | 99 | ruby|rbenv | 76,006 | <p><strong>New way</strong></p>
<p>Use the <code>uninstall</code> command: <code>rbenv uninstall [-f|--force] <version></code></p>
<pre><code>rbenv uninstall 2.1.0 # Uninstall Ruby 2.1.0
</code></pre>
<p>Use <code>rbenv versions</code> to see which versions you have installed.</p>
<hr>
<p><strong>Old way</strong></p>
<p>To remove a Ruby version from rbenv, delete the corresponding directory in <code>~/.rbenv/versions</code>. E.g.</p>
<pre><code>rm -rf ~/.rbenv/versions/1.9.3-p0
</code></pre>
<p>Run <code>rbenv rehash</code> afterwards to clean up any stale shimmed binaries from the removed version.</p> |
47,329,132 | How to get HMAC with Crypto Web API | <p>How can I get HMAC-SHA512(key, data) in the browser using Crypto Web API (<code>window.crypto</code>)?</p>
<p>Currently I am using CryptoJS library and it is pretty simple:</p>
<p><code>CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();</code></p>
<p>Result is <code>91c14b8d3bcd48be0488bfb8d96d52db6e5f07e5fc677ced2c12916dc87580961f422f9543c786eebfb5797bc3febf796b929efac5c83b4ec69228927f21a03a</code>.</p>
<p>I want to get rid of extra dependencies and start using Crypto Web API instead. How can I get the same result with it?</p> | 47,332,317 | 2 | 2 | null | 2017-11-16 12:00:04.593 UTC | 9 | 2022-05-07 15:06:48.32 UTC | null | null | null | null | 4,942,412 | null | 1 | 22 | javascript|cryptography|window.crypto | 7,969 | <p>Answering my own question. The code below returns the same result as <code>CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();</code></p>
<p>There are promises everywhere as WebCrypto is asynchronous:</p>
<pre><code>// encoder to convert string to Uint8Array
var enc = new TextEncoder("utf-8");
window.crypto.subtle.importKey(
"raw", // raw format of the key - should be Uint8Array
enc.encode("mysecretkey"),
{ // algorithm details
name: "HMAC",
hash: {name: "SHA-512"}
},
false, // export = false
["sign", "verify"] // what this key can do
).then( key => {
window.crypto.subtle.sign(
"HMAC",
key,
enc.encode("myawesomedata")
).then(signature => {
var b = new Uint8Array(signature);
var str = Array.prototype.map.call(b, x => x.toString(16).padStart(2, '0')).join("")
console.log(str);
});
});
</code></pre> |
10,487,008 | MVC C# TempData | <p>Can somebody please explain the purpose of TempData in MVC.
I understand it behaves like ViewBag but what does it do beyond that.</p> | 10,487,959 | 3 | 1 | null | 2012-05-07 18:16:50.31 UTC | 6 | 2020-10-20 07:39:10.46 UTC | 2016-08-09 13:20:09.247 UTC | null | 4,390,133 | null | 996,431 | null | 1 | 20 | c#|asp.net-mvc|tempdata | 39,811 | <blockquote>
<p>TempData is meant to be a very short-lived instance, and you should
only use it during the current and the subsequent requests only! Since
TempData works this way, you need to know for sure what the next
request will be, and redirecting to another view is the only time you
can guarantee this. Therefore, the only scenario where using TempData
will reliably work is when you are redirecting. This is because a
redirect kills the current request (and sends HTTP status code 302
Object Moved to the client), then creates a new request on the server
to serve the redirected view. Looking back at the previous
HomeController code sample means that the TempData object could yield
results differently than expected because the next request origin
can't be guaranteed. For example, the next request can originate from
a completely different machine and browser instance.</p>
</blockquote>
<p><a href="http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications" rel="noreferrer">http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications</a></p> |
22,458,575 | What's the difference between next() and nextLine() methods from Scanner class? | <p>What is the main difference between <code>next()</code> and <code>nextLine()</code>?<br>
My main goal is to read the all text using a <code>Scanner</code> which may be "connected" <strong>to any source</strong> (file for example).</p>
<p>Which one should I choose and why?</p> | 22,458,766 | 16 | 1 | null | 2014-03-17 15:34:15.617 UTC | 63 | 2022-04-11 08:54:14.58 UTC | 2015-04-07 06:48:40.683 UTC | null | 1,244,127 | null | 3,375,314 | null | 1 | 104 | java|java.util.scanner | 325,907 | <p>I always prefer to read input using <code>nextLine()</code> and then parse the string.</p>
<p>Using <code>next()</code> will only return what comes before the delimiter (defaults to whitespace). <code>nextLine()</code> automatically moves the scanner down after returning the current line.</p>
<p>A useful tool for parsing data from <code>nextLine()</code> would be <code>str.split("\\s+")</code>.</p>
<pre><code>String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces
</code></pre>
<p>For more information regarding the Scanner class or String class refer to the following links.</p>
<p>Scanner: <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html" rel="noreferrer">http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html</a></p>
<p>String: <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html" rel="noreferrer">http://docs.oracle.com/javase/7/docs/api/java/lang/String.html</a></p> |
22,465,018 | How to return a single result from Spring-Data-JPA? | <p>I'm trying to get a single result from a Spring Data query. I'm looking to return the greatest ID from a user table. I was hoping it would be straightforward, but I'm a little lost.</p>
<p>So far, based on <a href="https://stackoverflow.com/a/9315989/827480">this related SO post</a>, I've come to the conclusion that I need to use a <code>Specification</code> to define my query and <code>Page</code>d results, specifying the number of results I want to retrieve. Unfortunately, I'm getting a <code>HibernateJdbcException</code> data access exception.</p>
<p>My <code>Specification</code>/<code>Predicate</code> is supposed to be fairly simple and reflect: <code>from User order by id</code>:</p>
<pre><code>Page<User> result =userRepository.findAll(new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
query.orderBy(cb.desc(root.get("id")));
return query.getRestriction();
}
}, new PageRequest(0, 10));
MatcherAssert.assertThat(result.isFirstPage(), is(true));
User u = result.getContent().get(0);
</code></pre>
<p>Exception Thrown:</p>
<pre><code>org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [n/a]; SQL state [90016]; error code [90016]; could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:651)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:106)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
...
...
Caused by: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:449)
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:67)
at org.springframework.data.jpa.repository.query.QueryUtils.executeCountQuery(QueryUtils.java:406)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.readPage(SimpleJpaRepository.java:433)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:332)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
... 46 more
Caused by: org.h2.jdbc.JdbcSQLException: Column "USER1_.ID" must be in the GROUP BY list; SQL statement:
/* select count(generatedAlias0) from User as generatedAlias0, User as generatedAlias1 where 1=1 order by generatedAlias1.id desc */ select count(user0_.id) as col_0_0_ from user user0_ cross join user user1_ where 1=1 order by user1_.id desc [90016-173]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:331)
at org.h2.message.DbException.get(DbException.java:171)
at org.h2.message.DbException.get(DbException.java:148)
at org.h2.expression.ExpressionColumn.updateAggregate(ExpressionColumn.java:166)
at org.h2.command.dml.Select.queryGroup(Select.java:344)
at org.h2.command.dml.Select.queryWithoutCache(Select.java:620)
at org.h2.command.dml.Query.query(Query.java:314)
at org.h2.command.dml.Query.query(Query.java:284)
at org.h2.command.dml.Query.query(Query.java:36)
at org.h2.command.CommandContainer.query(CommandContainer.java:91)
at org.h2.command.Command.executeQuery(Command.java:195)
at org.h2.jdbc.JdbcPreparedStatement.executeQuery(JdbcPreparedStatement.java:106)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
... 78 more
</code></pre>
<p>I'm a little lost by the Hibernate error - it's asking for a <code>group</code> clause. I presume it has something to do with the way I've created the Predicate, but I am not sure how to create a simple predicate like this.</p>
<p><strong>EDIT</strong></p>
<p>As suggested by @OliverGierke, I tried to remove the <code>root = query.from(User.class)</code> but the hibernate still throws the same error (I enabled full hibernate query tracing). Strangely, however, this time, there is no <code>GROUP BY</code> in the generated SQL so I'm even more confused than before.</p>
<pre><code>2014-03-18 11:59:44,475 [main] DEBUG org.hibernate.SQL -
/* select
count(generatedAlias0)
from
User as generatedAlias0
order by
generatedAlias0.id desc */ select
count(user0_.id) as col_0_0_
from
user user0_
order by
user0_.id desc
Hibernate:
/* select
count(generatedAlias0)
from
User as generatedAlias0
order by
generatedAlias0.id desc */ select
count(user0_.id) as col_0_0_
from
user user0_
order by
user0_.id desc
2014-03-18 11:59:44,513 [main] WARN hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 90016, SQLState: 90016
2014-03-18 11:59:44,513 [main] ERROR hibernate.engine.jdbc.spi.SqlExceptionHelper - Column "USER0_.ID" must be in the GROUP BY list; SQL statement:
/* select count(generatedAlias0) from User as generatedAlias0 order by generatedAlias0.id desc */ select count(user0_.id) as col_0_0_ from user user0_ order by user0_.id desc [90016-173]
</code></pre> | 22,472,888 | 2 | 1 | null | 2014-03-17 20:46:57.023 UTC | 1 | 2014-03-19 13:11:28.68 UTC | 2017-05-23 11:46:16.663 UTC | null | -1 | null | 827,480 | null | 1 | 15 | java|jpa|spring-data|spring-data-jpa | 43,195 | <p>You're not using the <code>root</code> getting handed into the <code>Specification</code> instance to invoke the <code>.get(…)</code> method on. That fails the instance to register <code>id</code> being used and thus transparently adding it to the result set.</p>
<p>Simply removing <code>root = query.from(User.class);</code> should do the trick.</p>
<p>What puzzles me though is that you mention you're intending to build a "find by id" query. What you're actually building is a "find all ordered by id". If it's really the former you want to get, there's a predefined <code>findOne(…)</code> method on <code>CrudRepository</code> you can use.</p>
<p>Given the comments below it seems what you're actually trying to achieve is finding a single user with the smallest id. This can also be achieved by simply extending <code>PagingAndSortingRepository</code> and then use client code like this:</p>
<pre><code>interface UserRepository extends PagingAndSortingRepository<User, Long> { … }
Page<User> users = repository.findAll(new PageRequest(0, 1, Direction.ASC, "id"));
User user = users.getContent.get(0);
</code></pre>
<p>This will limit the result to the first page by a page size of 1 with ascending ordering by id. </p> |
7,368,926 | Division in Haskell | <p>I'm making a function in Haskell that halves only the evens in a list and I am experiencing a problem. When I run the complier it complains that you can't perform division of an int and that I need a fractional int type declaration. I have tried changing the type declaration to float, but that just generated another error. I have included the function's code below and was hoping for any form of help.</p>
<pre><code>halfEvens :: [Int] -> [Int]
halfEvens [] = []
halfEvens (x:xs) | odd x = halfEvens xs
| otherwise = x/2:halfEvens xs
</code></pre>
<p>Thank you for reading.</p> | 7,368,939 | 2 | 1 | null | 2011-09-10 00:54:50.763 UTC | 4 | 2020-08-26 13:13:42.36 UTC | 2011-09-10 01:20:57.467 UTC | null | 208,257 | null | 809,055 | null | 1 | 39 | haskell|division | 107,139 | <p>Use <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:div" rel="noreferrer"><code>div</code></a>, which performs integer division:</p>
<pre><code>halfEvens :: [Int] -> [Int]
halfEvens [] = []
halfEvens (x:xs) | odd x = halfEvens xs
| otherwise = x `div` 2 : halfEvens xs
</code></pre>
<p>The <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:-47-" rel="noreferrer"><code>(/)</code></a> function requires arguments whose type is in the class Fractional, and performs standard division. The <code>div</code> function requires arguments whose type is in the class Integral, and performs integer division.</p>
<p>More precisely, <code>div</code> and <code>mod</code> round toward negative infinity. Their cousins, <code>quot</code> and <code>rem</code>, behave like <a href="https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c">integer division in C</a> and round toward zero. <code>div</code> and <code>mod</code> are usually correct when doing modular arithmetic (e.g. when calculating the day of the week given a date), while <code>quot</code> and <code>rem</code> are slightly faster (I think).</p>
<p>Playing around a bit in GHCi:</p>
<pre><code>> :t div
div :: Integral a => a -> a -> a
> :t (/)
(/) :: Fractional a => a -> a -> a
> 3 / 5
0.6
> 3 `div` 5
0
> (-3) `div` 5
-1
> (-3) `quot` 5
0
> [x `mod` 3 | x <- [-10..10]]
[2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1]
> [x `rem` 3 | x <- [-10..10]]
[-1,0,-2,-1,0,-2,-1,0,-2,-1,0,1,2,0,1,2,0,1,2,0,1]
</code></pre> |
23,403,368 | How can I reattach to tmux process | <p>I had to reboot my box today. I had several program running in tmux sessions. They seem to be still alive, how can I reattach to them?
I tried <code>tmux a processID</code> but it didn't work.</p>
<pre><code>/home/me 21$ ps aux | grep tmux
me 1299 0.0 0.0 22244 1920 ? Ss Apr28 0:40 tmux -2 -f /tmp/r-plugin-me/tmux.conf new-session -s vimrpluginme1398670569alnn51oynp1vollnn51f2v4r_ied_delta1meRalphaCalibr VIMINSTANCEID=alnn51oynp1vollnn51f2v4r_ied_delta1meRal
me 2575 0.0 0.0 54164 3500 ? S 07:35 0:00 xterm -e tmux -2 -f /home/me/.tmux.conf -S /tmp/vX0qRrR/78
me 2577 0.0 0.0 19892 1400 pts/2 Ss+ 07:35 0:00 tmux -2 -f /home/me/.tmux.conf -S /tmp/vX0qRrR/78
me 2579 0.0 0.0 22128 1832 ? Ss 07:35 0:00 tmux -2 -f /home/me/.tmux.conf -S /tmp/vX0qRrR/78
me 5155 0.0 0.0 6380 756 pts/4 S+ 07:46 0:00 grep tmux
me 31340 0.0 0.0 23348 3000 ? Ss Apr28 0:17 tmux -2 -f /home/me/.tmux.conf -S /tmp/vIqEM06/78
</code></pre> | 23,403,908 | 2 | 1 | null | 2014-05-01 06:51:20.457 UTC | 15 | 2021-09-28 20:11:03.29 UTC | 2017-11-20 17:26:37.003 UTC | null | 775,954 | null | 1,846,968 | null | 1 | 89 | tmux | 64,612 | <p>You can not re-attach a process id. You need to reattach the corresponding <code>tmux</code> session.</p>
<p>So do <code>tmux ls</code>. Pick whatever session you want to re-attach. Then do <code>tmux attach -d -t <session id></code> to re-attach it to a new tmux instance and release it from the old one.</p> |
19,280,527 | MVC 5 Seed Users and Roles | <p>I have been playing about with the new MVC 5, I have a few models, controller and views setup using code first migrations. </p>
<p>My question is how do I seed users and roles? I currently seed some reference data in my Seed method in Configuration.cs. But it looks to me that the user and roles tables are not created until something first hits the AccountController. </p>
<p>I currently have two connection strings so I can separate my data from my authentication into different databases.</p>
<p>How can I get the user, roles, etc tables populate along with my others? And not when the account controller is hit?</p> | 20,521,530 | 7 | 1 | null | 2013-10-09 19:08:13.633 UTC | 40 | 2020-05-04 15:57:32.367 UTC | 2016-11-07 16:58:19.267 UTC | null | 104,219 | null | 1,563,157 | null | 1 | 98 | asp.net-mvc|asp.net-mvc-5|entity-framework-migrations|seeding | 67,556 | <p>Here is example of usual Seed approach:</p>
<pre><code>protected override void Seed(SecurityModule.DataContexts.IdentityDb context)
{
if (!context.Roles.Any(r => r.Name == "AppAdmin"))
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = "AppAdmin" };
manager.Create(role);
}
if (!context.Users.Any(u => u.UserName == "founder"))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser {UserName = "founder"};
manager.Create(user, "ChangeItAsap!");
manager.AddToRole(user.Id, "AppAdmin");
}
}
</code></pre>
<p>I used package-manager "update-database". DB and all tables were created and seeded with data.</p> |
3,771,824 | Select range in contenteditable div | <p>I've got a <code>contenteditable</code> div and a few paragraphs in it.</p>
<p>Here's my code:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div id="main" contenteditable="true"
style="border:solid 1px black; width:300px; height:300px">
<div>Hello world!</div>
<div>
<br>
</div>
<div>This is a paragraph</div>
</div>
</body>
</html>
</code></pre>
<p>Assuming, I want to make a range selection which will contain the string "world! This is"</p>
<p>How to do that?</p> | 3,773,788 | 1 | 0 | null | 2010-09-22 17:13:36.097 UTC | 11 | 2017-11-30 08:56:05.343 UTC | 2016-07-15 04:56:14.307 UTC | null | 455,340 | null | 455,340 | null | 1 | 24 | javascript|selection|range | 31,102 | <p>Once you've got hold of the text nodes containing the text you want highlighted, it's easy. How you get those depends on how generic you need this to be. As it is at the moment, before the user has edited it, the following will work:</p>
<pre><code>var mainDiv = document.getElementById("main");
var startNode = mainDiv.firstChild.firstChild;
var endNode = mainDiv.childNodes[2].firstChild;
var range = document.createRange();
range.setStart(startNode, 6); // 6 is the offset of "world" within "Hello world"
range.setEnd(endNode, 7); // 7 is the length of "this is"
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
</code></pre> |
8,691,858 | Where are My.Settings saved in VB 2010 .NET? | <p>Are <code>My.Settings</code> values saved in the program itself or do they get stored in the registry? So, for example, if I set a <code>My.Settings</code> value with a program, then I copy the program itself to another PC - is the <code>My.Settings</code> value still set?</p> | 8,691,876 | 4 | 1 | null | 2012-01-01 04:35:48.14 UTC | 3 | 2015-12-02 06:17:24.097 UTC | 2012-01-01 04:48:13.817 UTC | null | 707,111 | null | 496,965 | null | 1 | 17 | .net|vb.net|my.settings | 50,443 | <p>It depends upon the <a href="http://msdn.microsoft.com/en-us/library/ms379611%28v=vs.80%29.aspx">scope</a> you have selected. There are two scope settings - Application and User scope.</p>
<p>From MSDN article:</p>
<blockquote>
<p><strong>Application-scoped settings</strong> are read-only and are shared between all
users of that application. These settings are stored in the app.config
file in the section. At run time, the app.config
file will be in your bin folder and will be named with your
application's name (MySettingsDemo.exe.config).</p>
<p><strong>User-scope settings</strong> are specific for each user. They can be read and
set safely by the application code at run time. These settings are
stored in a user.config file. To be technically accurate, there are
two user.configs per user per application—one for non-roaming and one
for roaming. Although the Visual Basic 2005 documentation states that
the user.config file will be named according to the user's name
(joe.config), this is not the case. The user.config file is created in
the:</p>
</blockquote>
<pre><code><c:\Documents and Settings>\<username>\[LocalSettings\]ApplicationData\<companyname>\<appdomainname>_<eid>_<hash>\<verison>.
</code></pre> |
19,818,756 | Extract row with maximum value in a group pandas dataframe | <p>A similar question is asked here:
<a href="https://stackoverflow.com/questions/15705630/python-how-can-i-get-the-row-which-has-the-max-value-in-goups-making-groupby">Python : Getting the Row which has the max value in groups using groupby</a></p>
<p>However, I just need one record per group even if there are more than one record with maximum value in that group. </p>
<p>In the example below, I need one record for "s2". For me it doesn't matter which one. </p>
<pre><code>>>> df = DataFrame({'Sp':['a','b','c','d','e','f'], 'Mt':['s1', 's1', 's2','s2','s2','s3'], 'Value':[1,2,3,4,5,6], 'count':[3,2,5,10,10,6]})
>>> df
Mt Sp Value count
0 s1 a 1 3
1 s1 b 2 2
2 s2 c 3 5
3 s2 d 4 10
4 s2 e 5 10
5 s3 f 6 6
>>> idx = df.groupby(['Mt'])['count'].transform(max) == df['count']
>>> df[idx]
Mt Sp Value count
0 s1 a 1 3
3 s2 d 4 10
4 s2 e 5 10
5 s3 f 6 6
>>>
</code></pre> | 19,818,942 | 4 | 1 | null | 2013-11-06 17:30:08.163 UTC | 16 | 2022-08-30 23:57:22.153 UTC | 2017-05-23 11:55:07.73 UTC | null | -1 | null | 1,140,126 | null | 1 | 31 | python|pandas | 30,236 | <p>You can use <code>first</code></p>
<pre><code>In [14]: df.groupby('Mt').first()
Out[14]:
Sp Value count
Mt
s1 a 1 3
s2 c 3 5
s3 f 6 6
</code></pre>
<h1>Update</h1>
<p>Set <code>as_index=False</code> to achieve your goal</p>
<pre><code>In [28]: df.groupby('Mt', as_index=False).first()
Out[28]:
Mt Sp Value count
0 s1 a 1 3
1 s2 c 3 5
2 s3 f 6 6
</code></pre>
<h1>Update Again</h1>
<p>Sorry for misunderstanding what you mean. You can sort it first if you want the one with max count in a group</p>
<pre><code>In [196]: df.sort('count', ascending=False).groupby('Mt', as_index=False).first()
Out[196]:
Mt Sp Value count
0 s1 a 1 3
1 s2 e 5 10
2 s3 f 6 6
</code></pre> |
19,397,100 | Adding a title page, page headers and footers using Pandoc | <p>How do you specify that Pandoc should use a specific header and footer when generating a PDF from Markdown?</p>
<p>Currently I use the following to create my doc from the command line:</p>
<pre><code>pandoc -s -V geometry:margin=1in --number-sections -o doc.pdf doc.mkd
</code></pre>
<p>This gives a lovely result with numbered sections.</p>
<p>What I would like to do, is to include a header and footer on each page. How do I go about it?</p>
<p>The <a href="http://johnmacfarlane.net/pandoc/demo/example9/pandocs-markdown.html">extensions mechanism</a>, e.g. <code>pandoc_title_block</code> may hold the key, but how do you use it?</p>
<p>Lastly (as a bonus), is there some way to create a title page for a document using pandoc?</p> | 19,620,699 | 1 | 1 | null | 2013-10-16 07:02:40.393 UTC | 8 | 2019-05-17 00:50:21.45 UTC | null | null | null | null | 828,757 | null | 1 | 14 | pandoc | 21,812 | <p>When using the <code>-s</code> (<code>--standalone</code>) argument for the generation of PDFs, Pandoc uses a specific LateX template.</p>
<p>You can look at the template with <code>pandoc -D latex</code> and notice that there are many variables that you can set (the same way you did you with <code>-V geometry:margin=1in</code> in your command).</p>
<p>In order to add a specific header/footer, you can modify this template and use the <code>--template</code> argument in the command line.</p>
<p>You can get more information here <a href="https://pandoc.org/demo/example19/Templates.html" rel="nofollow noreferrer">Pandoc demo templates</a></p> |
19,671,845 | How can I generate a random number within a range in Rust? | <blockquote>
<p>Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.</p>
</blockquote>
<p>I came across the following example of how to generate a random number using Rust, but it doesn't appear to work. The example doesn't show which version of Rust it applies to, so perhaps it is out-of-date, or perhaps I got something wrong.</p>
<pre><code>// http://static.rust-lang.org/doc/master/std/rand/trait.Rng.html
use std::rand;
use std::rand::Rng;
fn main() {
let mut rng = rand::task_rng();
let n: uint = rng.gen_range(0u, 10);
println!("{}", n);
let m: float = rng.gen_range(-40.0, 1.3e5);
println!("{}", m);
}
</code></pre>
<p>When I attempt to compile this, the following error results:</p>
<pre class="lang-none prettyprint-override"><code>test_rand002.rs:6:17: 6:39 error: type `@mut std::rand::IsaacRng` does not
implement any method in scope named `gen_range`
test_rand002.rs:6 let n: uint = rng.gen_range(0u, 10);
^~~~~~~~~~~~~~~~~~~~~~
test_rand002.rs:8:18: 8:46 error: type `@mut std::rand::IsaacRng` does not
implement any method in scope named `gen_range`
test_rand002.rs:8 let m: float = rng.gen_range(-40.0, 1.3e5);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>There is another example (as follows) on the same page (above) that does work. However, it doesn't do exactly what I want, although I could adapt it.</p>
<pre><code>use std::rand;
use std::rand::Rng;
fn main() {
let mut rng = rand::task_rng();
let x: uint = rng.gen();
println!("{}", x);
println!("{:?}", rng.gen::<(f64, bool)>());
}
</code></pre>
<p>How can I generate a "simple" random number using Rust (e.g.: <code>i64</code>) within a given range (e.g.: 0 to n)?</p> | 19,674,981 | 4 | 1 | null | 2013-10-30 00:47:21.297 UTC | 6 | 2022-09-09 21:38:14.577 UTC | 2019-04-15 15:21:21.6 UTC | null | 155,423 | null | 1,949,390 | null | 1 | 60 | random|rust|rust-obsolete | 61,014 | <blockquote>
<p>Editor's note: <strong>This answer is for a version of Rust prior to 1.0 and is not valid in Rust 1.0.</strong> See <a href="https://stackoverflow.com/a/37017052/48136">Manoel Stilpen's answer</a> instead.</p>
</blockquote>
<p>This has been changing a lot recently (sorry! it's all been me), and in Rust 0.8 it was called <a href="http://static.rust-lang.org/doc/0.8/std/rand/trait.Rng.html#fn.gen_integer_range" rel="nofollow noreferrer"><code>gen_integer_range</code></a> (note the <code>/0.8/</code> rather than <code>/master/</code> in the URL, if you are using 0.8 you <em>need</em> to be reading those docs).</p>
<p>A word of warning: <code>.gen_integer_range</code> was entirely incorrect in many ways, the new <code>.gen_range</code> doesn't have incorrectness problems.</p>
<hr />
<p>Code for master (where <code>.gen_range</code> works fine):</p>
<pre><code>use std::rand::{task_rng, Rng};
fn main() {
// a number from [-40.0, 13000.0)
let num: f64 = task_rng().gen_range(-40.0, 1.3e4);
println!("{}", num);
}
</code></pre> |
506,807 | Creating multiple numbers with certain number of bits set | <h2>Problem</h2>
<p>I need to create 32 Bit numbers (signed or unsigned doesn't matter, the highest bit will never be set anyway) and each number must have a given number of Bits set.</p>
<h2>Naive Solution</h2>
<p>The easiest solution is of course to start with the number of zero. Within a loop the number is now increased by one, the number of Bits is counted, if the count has the desired value, the number is stored to a list, if not the loop just repeats. The loop is stopped if enough numbers have been found. Of course this works just fine, but it's awfully slow once the number of desired Bits gets very high.</p>
<h2>A Better Solution</h2>
<p>The simplest number having (let's say) 5 Bits set is the number where the first 5 Bit are set. This number can be easily created. Within a loop the first bit is set and the number is shifted to the left by one. This loop runs 5 times and I found the first number with 5 Bits set. The next couple of numbers are easy to create as well. We now pretend the number to be 6 Bit wide and the highest one is not set. Now we start shifting the first zero bit to the right, so we get 101111, 110111, 111011, 111101, 111110. We could repeat this by adding another 0 to front and repeating this process. 0111110, 1011110, 1101110, etc. However that way numbers will grow much faster than necessary, as using this simple approach we leave out numbers like 1010111.</p>
<p>So is there a better way to create all possible permutations, a generic approach, that can be used, regardless how many bits the next number will have and regardless how many set bits we need set?</p> | 506,862 | 4 | 2 | null | 2009-02-03 11:50:31.19 UTC | 10 | 2021-12-17 09:12:08.883 UTC | 2020-06-20 09:12:55.06 UTC | starblue | -1 | Mecki | 15,809 | null | 1 | 20 | algorithm|binary|permutation|combinations | 6,806 | <p>You can use the <a href="https://web.archive.org/web/20130731200134/http://hackersdelight.org/hdcodetxt/snoob.c.txt" rel="nofollow noreferrer">bit-twiddling hack from hackersdelight.org</a>.</p>
<p>In his book he has code to get the next higher number with the same number of one-bit set.</p>
<p>If you use this as a primitive to increase your number all you have to do is to find a starting point. Getting the first number with N bits set is easy. It's just 2^(N-1) -1.</p>
<p>You will iterate through all possible numbers very fast that way.</p>
<pre><code> unsigned next_set_of_n_elements(unsigned x)
{
unsigned smallest, ripple, new_smallest, ones;
if (x == 0) return 0;
smallest = (x & -x);
ripple = x + smallest;
new_smallest = (ripple & -ripple);
ones = ((new_smallest/smallest) >> 1) - 1;
return ripple | ones;
}
// test code (shown for two-bit digits)
void test (void)
{
int bits = 2;
int a = pow(2,bits) - 1;
int i;
for (i=0; i<100; i++)
{
printf ("next number is %d\n", a);
a = next_set_of_n_elements(a);
}
}
</code></pre> |
747,670 | jQuery: selecting checked checkbox | <p>Suppose I have the following HTML:</p>
<pre><code><form id="myform">
<input type='checkbox' name='foo[]'/> Check 1<br/>
<input type='checkbox' name='foo[]' checked='true'/> Check 2<br/>
<input type='checkbox' name='foo[]'/> Check 3<br/>
</form>
</code></pre>
<p>Now, how do I select the checked input fields with name 'foo[]'?</p>
<p>This is my attempt, but it doesn't work:</p>
<pre><code>$("#myform input[name='foo']:checked:enabled");
</code></pre> | 747,682 | 4 | 2 | null | 2009-04-14 13:55:05.567 UTC | 1 | 2019-09-06 21:13:14.1 UTC | 2019-09-06 21:13:14.1 UTC | null | 78,297 | null | 78,297 | null | 1 | 35 | jquery|checkbox|input|jquery-selectors | 64,520 | <p>The name of the field isn't <code>foo</code>, it is <code>foo[]</code>. You could use the <a href="http://docs.jquery.com/Selectors/attributeStartsWith#attributevalue" rel="noreferrer">attributeStartsWith</a> selector:</p>
<pre><code>$("input[name^='foo']:checked:enabled",'#myform');
</code></pre>
<p>Ideally, you'd be able to do this:</p>
<pre><code>$("input[name='foo[]']:checked:enabled",'#myform');
</code></pre>
<p>But as <a href="https://stackoverflow.com/questions/739695/jquery-selector-value-escaping/740168#740168">this answer</a> explains, jQuery uses this to parse the <code>value</code> part of the <code>attr=value</code> condition:</p>
<pre><code>(['"]*)(.*?)\3|)\s*\]
</code></pre>
<blockquote>
<p>\3 being the group containing the opening quotes, which weirdly are allowed to be multiple opening quotes, or no opening quotes at all. The .*? then can parse any character, including quotes until it hits the first ‘]’ character, ending the match. There is no provision for backslash-escaping CSS special characters, so you can't match an arbitrary string value in jQuery.</p>
</blockquote>
<p>In other words, as soon as jQuery hits the first <code>]</code> it thinks the value is over. So you are stuck with startsWith or using pure DOM elements, as that answer also explains.</p>
<p><strong>SUPER DUPER IMPORTANT EDIT</strong>:<br>
This bug is fixed, apparently. You should be able to use the code I described as "ideal", above.</p> |
880,662 | Extend a java class from one file in another java file | <p>How can I include one java file into another java file? </p>
<p>For example:
If I have 2 java file one is called <code>Person.java</code> and one is called <code>Student.java</code>. How can I include <code>Person.java</code> into <code>Student.java</code> so that I can extend the class from <code>Person.java</code> in <code>Student.java</code></p> | 880,688 | 4 | 0 | null | 2009-05-19 01:58:31.333 UTC | 23 | 2018-02-10 04:57:09.04 UTC | 2018-02-10 04:57:09.04 UTC | null | 79,855 | null | 52,745 | null | 1 | 68 | java|import|include | 336,568 | <p>Just put the two files in the same directory. Here's an example:</p>
<p>Person.java</p>
<pre><code>public class Person {
public String name;
public Person(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
</code></pre>
<p>Student.java</p>
<pre><code>public class Student extends Person {
public String somethingnew;
public Student(String name) {
super(name);
somethingnew = "surprise!";
}
public String toString() {
return super.toString() + "\t" + somethingnew;
}
public static void main(String[] args) {
Person you = new Person("foo");
Student me = new Student("boo");
System.out.println("Your name is " + you);
System.out.println("My name is " + me);
}
}
</code></pre>
<p>Running Student (since it has the main function) yields us the desired outcome:</p>
<pre><code>Your name is foo
My name is boo surprise!
</code></pre> |
1,093,429 | Add a user control to a wpf window | <p>I have a user control that I've created, however when I go to add it to the XAML in the window, Intellisense doesn't pick it up, and I can't figure out how to add it to the window.</p> | 1,093,451 | 4 | 0 | null | 2009-07-07 16:39:58.38 UTC | 11 | 2019-10-15 13:13:19.347 UTC | 2018-02-09 17:37:32.61 UTC | null | 102,937 | null | 88,770 | null | 1 | 73 | wpf|user-controls | 121,471 | <p>You need to add a reference inside the window tag. Something like:</p>
<pre><code>xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
</code></pre>
<p>(When you add xmlns:controls=" intellisense should kick in to make this bit easier)</p>
<p>Then you can add the control with:</p>
<pre><code><controls:CustomControlClassName ..... />
</code></pre> |
45,417,335 | Python: use cookie to login with Selenium | <p>What I want to do is to open a page (for example youtube) and be automatically logged in, like when I manually open it in the browser.</p>
<p>From what I've understood, I have to use cookies, the problem is that I can't understand how.</p>
<p>I tried to download youtube cookies with this:</p>
<pre><code>driver = webdriver.Firefox(executable_path="driver/geckodriver.exe")
driver.get("https://www.youtube.com/")
print(driver.get_cookies())
</code></pre>
<p>And what I get is:</p>
<blockquote>
<p>{'name': 'VISITOR_INFO1_LIVE', 'value': 'EDkAwwhbDKQ', 'path': '/', 'domain': '.youtube.com', 'expiry': None, 'secure': False, 'httpOnly': True}</p>
</blockquote>
<p>So what cookie do I have to load to automatically log in?</p> | 45,419,194 | 6 | 3 | null | 2017-07-31 13:30:07.347 UTC | 12 | 2020-10-02 08:36:30.23 UTC | 2017-07-31 13:50:31.59 UTC | null | 7,450,068 | null | 7,450,068 | null | 1 | 13 | python|selenium | 41,512 | <p>You can use <a href="https://docs.python.org/3/library/pickle.html" rel="noreferrer"><code>pickle</code></a> to save cookies as text file and load it later:</p>
<pre><code>def save_cookie(driver, path):
with open(path, 'wb') as filehandler:
pickle.dump(driver.get_cookies(), filehandler)
def load_cookie(driver, path):
with open(path, 'rb') as cookiesfile:
cookies = pickle.load(cookiesfile)
for cookie in cookies:
driver.add_cookie(cookie)
</code></pre> |
23,662,131 | Redis's huge files won't delete? | <p>I'm using Redis-server for windows ( <a href="https://github.com/MSOpenTech/redis/tree/2.8.4_msopen" rel="noreferrer">2.8.4 - MSOpenTech</a>) / windows 8 64bit.</p>
<p>It is working great , but even after I run :</p>
<p><img src="https://i.stack.imgur.com/pe9mo.png" alt="enter image description here" /></p>
<p>I see this : <em>(and here are my questions)</em></p>
<ul>
<li><p><strong>When <code>Redis-server.exe</code> is up</strong> , I see <a href="https://i.stack.imgur.com/sqJi3.png" rel="noreferrer">3 large files</a> :</p>
<p><img src="https://i.stack.imgur.com/sqJi3.png" alt="enter image description here" /></p>
</li>
<li><p><strong>When <code>Redis-server.exe</code> is down</strong> , I see <a href="https://i.stack.imgur.com/Odzf0.png" rel="noreferrer">2 large files</a> :</p>
</li>
</ul>
<p><img src="https://i.stack.imgur.com/Odzf0.png" alt="enter image description here" /></p>
<p><strong>Question :</strong></p>
<p>— Didn't I just tell it to erase all DB ? so why are those 2/3 huge files are still there ?
How can I completely erase those files? ( without re-generating)</p>
<p><em>NB
It seems that it is doing deletion of keys without freeing occupied space. if so , How can I free this unused space?</em></p> | 23,663,284 | 4 | 1 | null | 2014-05-14 18:16:40.54 UTC | 8 | 2015-11-11 01:06:07.147 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 859,154 | null | 1 | 27 | windows|redis|redis-server | 13,352 | <p>From <a href="https://github.com/MSOpenTech/redis/issues/83">https://github.com/MSOpenTech/redis/issues/83</a>
"Redis uses the fork() UNIX system API to create a point-in-time snapshot of the data store for storage to disk. This impacts several features on Redis: AOF/RDB backup, master-slave synchronization, and clustering. Windows does not have a fork-like API available, so we have had to simulate this behavior by placing the Redis heap in a memory mapped file that can be shared with a child(quasi-forked) process. By default we set the size of this file to be equal to the size of physical memory. In order to control the size of this file we have added a maxheap flag. See the Redis.Windows.conf file in msvs\setups\documentation (also included with the NuGet and Chocolatey distributions) for details on the usage of this flag. "</p> |
69,619,604 | Visual Studio Code: Review Merge Changes Side by Side, rather than top down | <p>Is there any way to compare file changes in Visual Studio Code Side By Side, rather than top down? Regular Visual Studio Enterprise has this option.</p>
<p>This is during git merge conflict resolution.</p>
<p><a href="https://i.stack.imgur.com/HRfye.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HRfye.png" alt="enter image description here" /></a></p> | 69,626,228 | 4 | 0 | null | 2021-10-18 16:37:31.177 UTC | 3 | 2022-08-31 13:03:56.53 UTC | 2021-10-18 16:43:17.24 UTC | null | 15,435,022 | null | 15,435,022 | null | 1 | 30 | git|visual-studio-code|vscode-settings|vscode-git | 14,196 | <p>2022: update for <a href="https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_69.md#3-way-merge-editor" rel="noreferrer">VSCode 1.69 (June 2022)</a>, as noted in <a href="https://stackoverflow.com/users/10158227/audwin-oyong">Audwin Oyong</a>'s <a href="https://stackoverflow.com/a/72995431/6309">answer</a>, there is now a 3-way merge view, which allows a side-by-side resolution.</p>
<blockquote>
<p>In this release, we continued working on the 3-way merge editor.<br />
This feature can be enabled by setting <code>git.mergeEditor</code> to <code>true</code> and will be enabled by default in future releases.</p>
<p>The merge editor allows you to quickly resolve Git merge conflicts. >
When enabled, the merge editor can be opened by clicking on a conflicting file in the Source Control view.<br />
Checkboxes are available to accept and combine changes in <code>Theirs</code> or <code>Yours</code>:</p>
<p><a href="https://i.stack.imgur.com/2aPDQ.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/2aPDQ.gif" alt="Merge Editor Conflict Resolution Demo" /></a></p>
</blockquote>
<p>And VSCode 1.70 (July 2022) will offer a way to open the regular file (not in 3 way merge mode).<br />
Same as diff editor, it could use an action in the editor title area</p>
<p><a href="https://i.stack.imgur.com/Re32T.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Re32T.png" alt="https://user-images.githubusercontent.com/1926584/176448981-01a0b0e4-5261-4ec3-9e27-1efb68c6b39a.png" /></a></p>
<p>See <a href="https://github.com/microsoft/vscode/pull/155159" rel="noreferrer">PR 155159</a> and its new action <code>merge.openResult</code>.</p>
<p><a href="https://stackoverflow.com/users/10158227/audwin-oyong">Audwin Oyong</a> adds, based on the <a href="https://github.com/microsoft/vscode-docs/blob/913c6d1faa66cbcfed6fd23c120745894e289f96/release-notes/v1_69.md#3-way-merge-editor" rel="noreferrer">release notes</a>:</p>
<blockquote>
<p>To turn off the 3-way merge view, you can set <code>git.mergeEditor</code> to <code>false</code>.</p>
</blockquote>
<p>Open the VSCode settings with <kbd>Ctrl</kbd><kbd>,</kbd>:</p>
<p><a href="https://i.stack.imgur.com/5U09f.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5U09f.png" alt="git.mergeEditor setting" /></a></p>
<p><sup>(From <a href="https://stackoverflow.com/users/9370716/harshil-patanvadiya">Harshil Patanvadiya</a>'s <a href="https://stackoverflow.com/a/73556238/6309">answer</a>)</sup></p>
<hr />
<p>2021: By default, you see all conflicts "top down", but for each one, clicking on "compare changes" would open a tab with a side-by-side diff.</p>
<p><a href="https://i.stack.imgur.com/XUNRO.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/XUNRO.gif" alt="https://cloud.githubusercontent.com/assets/1926584/26586117/7e70828a-454e-11e7-9bb6-67646a20bfe0.gif" /></a></p>
<p>(from <a href="https://github.com/microsoft/vscode/issues/27562" rel="noreferrer">issue 27562</a>)</p>
<p>Not ideal, but a good workaround.</p>
<hr />
<p>In VSCode 1.71 (Aug. 2022):</p>
<blockquote>
<h2><a href="https://github.com/microsoft/vscode/issues/155280" rel="noreferrer">Merge Editor: Toggling word wrap should apply to all editors</a></h2>
<p>It was weird when I toggled word wrap in the merge editor yet only the editor I was focused on had it toggled.<br />
I kind of expected all editors to have it toggled.</p>
<p>My rationale is that toggling word wrap is usually a symptom of having long lines and the chances that all three editors have long lines is high if a single editor has long lines.</p>
</blockquote>
<p>And:</p>
<blockquote>
<h2><a href="https://github.com/microsoft/vscode/issues/153800#issuecomment-1219762873" rel="noreferrer">Improve Merge Editor Story For Files Having/Getting Conflict Markers</a></h2>
<p>Originally we had this icon along to toggle between the raw file and merge editor views. Could use it with this new label too.<br />
git-merge felt out of place as an icon choice to my eyes.
<a href="https://i.stack.imgur.com/4BeFP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4BeFP.png" alt="https://user-images.githubusercontent.com/25163139/185460190-0d652b9c-a4a7-4cb6-8958-80e42a72f0f7.png" /></a></p>
</blockquote> |
19,599,064 | angularjs ng-disabled doesn't add disabled to button | <p>I have an input button that I want to set to disabled if a user selects a certain value from a select box:</p>
<p>Select menu:</p>
<pre><code><select id="jobstatus" name="jobstatus" ng-model="associate.JobStatus" class="form-control">
<option value="0">Current</option>
<option value="1">Former</option>
<option value="2">Never worked there</option>
</select>
</code></pre>
<p>Input Button:</p>
<pre><code> <input type="submit" class="btn btn-info pull-right
btn-lg btn-block" ng-disabled="{{associate.JobStatus === '2'}}" />
</code></pre>
<p>Now when I am viewing the source, when I do select option <code>2</code>, the input button element changes from value <code>ng-disabled="false"</code> to <code>ng-disabled="true"</code> but the disabled attribute is not applied to the button.</p>
<p>What am I doing wrong here?</p> | 19,599,226 | 3 | 0 | null | 2013-10-25 20:39:59.953 UTC | 4 | 2021-08-30 14:17:46.697 UTC | 2015-11-05 12:46:52.337 UTC | null | 3,962,914 | null | 1,424,115 | null | 1 | 24 | javascript|angularjs | 95,597 | <p>Use this</p>
<pre><code><input type="submit" class="btn btn-info pull-right btn-lg btn-block" ng-disabled="associate.JobStatus == 2" />
</code></pre> |
38,228,393 | NGINX remove .html extension | <p>So, I found an answer to removing the .html extension on my page, that works fine with this code:</p>
<pre><code>server {
listen 80;
server_name _;
root /var/www/html/;
index index.html;
if (!-f "${request_filename}index.html") {
rewrite ^/(.*)/$ /$1 permanent;
}
if ($request_uri ~* "/index.html") {
rewrite (?i)^(.*)index\.html$ $1 permanent;
}
if ($request_uri ~* ".html") {
rewrite (?i)^(.*)/(.*)\.html $1/$2 permanent;
}
location / {
try_files $uri.html $uri $uri/ /index.html;
}
}
</code></pre>
<p>But if I open mypage.com it redirects me to mypage.com/index
<br>
Wouldn't this be fixed by declaring index.html as index? Any help is appreciated.</p> | 38,238,001 | 2 | 0 | null | 2016-07-06 15:55:23.407 UTC | 18 | 2020-07-29 01:38:56.827 UTC | 2019-01-13 00:36:27.44 UTC | null | 7,735,711 | null | 4,871,527 | null | 1 | 39 | html|nginx | 32,619 | <h1>The "Holy Grail" Solution for Removing ".html" in NGINX:</h1>
<p><strong>UPDATED ANSWER:</strong> This question piqued my curiosity, and I went on another, more in-depth search for a "holy grail" solution for <code>.html</code> redirects in NGINX. Here is the link to the answer I found, since I didn't come up with it myself: <a href="https://stackoverflow.com/a/32966347/4175718">https://stackoverflow.com/a/32966347/4175718</a></p>
<p>However, I'll give an example and explain how it works. Here is the code:</p>
<pre><code>location / {
if ($request_uri ~ ^/(.*)\.html) {
return 302 /$1;
}
try_files $uri $uri.html $uri/ =404;
}
</code></pre>
<p>What's happening here is a pretty ingenious use of the <code>if</code> directive. NGINX runs a regex on the <code>$request_uri</code> portion of incoming requests. The regex checks if the URI has an .html extension and then stores the extension-less portion of the URI in the built-in variable <code>$1</code>.</p>
<p>From the <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html" rel="noreferrer">docs</a>, since it took me a while to figure out where the <code>$1</code> came from:</p>
<blockquote>
<p>Regular expressions can contain captures that are made available for later reuse in the $1..$9 variables.</p>
</blockquote>
<p>The regex both checks for the existence of unwanted .html requests and effectively sanitizes the URI so that it does not include the extension. Then, using a simple <code>return</code> statement, the request is redirected to the sanitized URI that is now stored in <code>$1</code>.</p>
<p>The best part about this, as original author <a href="https://stackoverflow.com/users/1122270/cnst">cnst</a> explains, is that</p>
<blockquote>
<p>Due to the fact that $request_uri is always constant per request, and is not affected by other rewrites, it won't, in fact, form any infinite loops.</p>
</blockquote>
<p>Unlike the rewrites, which operate on <strong>any</strong> <code>.html</code> request (including the invisible internal redirect to <code>/index.html</code>), this solution only operates on external URIs that are visible to the user.</p>
<h2>What does "try_files" do?</h2>
<p>You will still need the <code>try_files</code> directive, as otherwise NGINX will have no idea what to do with the newly sanitized extension-less URIs. The <code>try_files</code> directive shown above will first try the new URL by itself, then try it with the ".html" extension, then try it as a directory name.</p>
<p>The NGINX docs also explain how the default <code>try_files</code> directive works. The default <code>try_files</code> directive is ordered differently than the example above so the explanation below does not perfectly line up:</p>
<blockquote>
<p>NGINX will first append <code>.html</code> to the end of the URI and try to serve it. If it finds an appropriate <code>.html</code> file, it will return that file and will <strong>maintain the extension-less URI</strong>. If it cannot find an appropriate <code>.html</code> file, it will try the URI without any extension, then the URI as a directory, and then finally return a 404 error.</p>
</blockquote>
<h2>UPDATE: What does the regex do?</h2>
<p>The above answer touches on the use of regular expressions, but here is a more specific explanation for those who are still curious. The following regular expression (regex) is used:</p>
<pre><code>^/(.*)\.html
</code></pre>
<p>This breaks down as:</p>
<p><code>^</code>: indicates beginning of line.</p>
<p><code>/</code>: match the character "/" literally. Forward slashes do NOT need to be escaped in NGINX.</p>
<p><code>(.*)</code>: capturing group: match any character an unlimited number of times</p>
<p><code>\.</code>: match the character "." literally. This must be escaped with a backslash.</p>
<p><code>html</code>: match the string "html" literally.</p>
<p>The capturing group <code>(.*)</code> is what contains the non-".html" portion of the URL. This can later be referenced with the variable <code>$1</code>. NGINX is then configured to re-try the request (<code>return 302 /$1;</code>) and the <code>try_files</code> directive internally re-appends the ".html" extension so the file can be located.</p>
<h2>UPDATE: Retaining the query string</h2>
<p>To retain query strings and arguments passed to a <code>.html</code> page, the <code>return</code> statement can be changed to:</p>
<pre><code>return 302 /$1$is_args$args;
</code></pre>
<p>This should allow requests such as <code>/index.html?test</code> to redirect to <code>/index?test</code> instead of just <code>/index</code>.</p>
<hr />
<h3>Note that this is considered safe usage of the `if` directive.</h3>
<p>From the NGINX page If Is Evil:</p>
<blockquote>
<p>The only 100% safe things which may be done inside if in a location context are:</p>
<p>return ...;</p>
<p>rewrite ... last;</p>
</blockquote>
<hr />
<h3>Also, note that you may swap out the '302' redirect for a '301'.</h3>
<p>A <code>301</code> redirect is permanent, and is cached by web browsers and search engines. If your goal is to permanently remove the <code>.html</code> extension from pages that are already indexed by a search engine, you will want to use a <code>301</code> redirect. However, if you are testing on a live site, it is best practice to start with a <code>302</code> and only move to a <code>301</code> when you are absolutely confident your configuration is working correctly.</p> |
59,761,941 | How to add bottom elevation to a container in Flutter? | <p>I've already seen <a href="https://stackoverflow.com/questions/52227846/how-can-i-add-shadow-to-the-widget-in-flutter">this</a> and <a href="https://stackoverflow.com/questions/49600056/add-custom-boxshadow-to-flutter-card/49600394#49600394">this</a> and <a href="https://stackoverflow.com/questions/51333105/flutter-add-box-shadow-to-a-transparent-container">this</a> but they don't answer my question. I need elevation on my <code>Container</code> <em>just</em> below it, not all around it. </p>
<p>Here's what I have as of now:</p>
<p><a href="https://i.stack.imgur.com/ZTR5c.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ZTR5c.jpg" alt="container with shadow"></a></p>
<p>My goal at the end is to eliminate the shadow at the top of the days of the week.</p>
<p>I use the code from <a href="https://stackoverflow.com/a/55833281/10808802">this</a> answer to achieve that shadow effect on my <code>Container</code> but I don't want it all the way around, just on the bottom with the rounded corners and not on the top. Any help would be appreciated.</p> | 59,762,629 | 10 | 0 | null | 2020-01-16 01:43:19.447 UTC | 11 | 2022-02-25 20:45:02.953 UTC | 2020-03-31 16:48:15.713 UTC | null | 10,808,802 | null | 10,808,802 | null | 1 | 58 | flutter|shadow | 95,329 | <p>Use <code>ClipRRect</code> to remove shadow effects and add bottom <code>margin</code> to <code>Container</code> to overcome <code>ClipRRect</code> at bottom only to show shadow effect.</p>
<p><strong>Example:</strong></p>
<pre><code>import "package:flutter/material.dart";
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: Container(
height: 100.0,
margin: const EdgeInsets.only(bottom: 6.0), //Same as `blurRadius` i guess
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
offset: Offset(0.0, 1.0), //(x,y)
blurRadius: 6.0,
),
],
),
),
),
),
),
);
}
}
</code></pre>
<p><strong>Result:</strong></p>
<p><a href="https://i.stack.imgur.com/2uX9H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2uX9H.png" alt="enter image description here"></a></p> |
23,225,604 | How do I resize a WebDriverJS browser window? | <p>I am using <a href="https://code.google.com/p/selenium/wiki/WebDriverJs">WebDriverJS</a>, the JavaScript bindings for WebDriver, to do some simple frontend testing (driven by nodejs). However, I'm running into difficulties resizing the window, and <a href="http://selenium.googlecode.com/git/docs/api/javascript/class_webdriver_WebDriver_Window.html">the documentation</a> is just a bit unclear to me.</p>
<pre><code>var webdriver = require('selenium-wedriver');
driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
driver.get("http://www.google.com")
.then(function() {
driver.Window.setSize(400, 400); // <-- should resize, does nothing
})
// more thenables...
</code></pre>
<p>Everything works normally and it gives no error, but the browser window does not resize. Am I referencing this setSize method incorrectly?</p> | 23,417,273 | 2 | 0 | null | 2014-04-22 16:49:15.963 UTC | 8 | 2014-12-02 07:23:38.813 UTC | 2014-12-02 07:23:38.813 UTC | null | 1,666,394 | null | 1,666,394 | null | 1 | 16 | javascript|node.js|selenium|selenium-webdriver | 10,806 | <p>After <em>more than a week</em> of confused searching through the api docs and google, the answer was actually lying inside of the tests folder of the <a href="https://github.com/SeleniumHQ/selenium/blob/master/javascript/node/selenium-webdriver/test/window_test.js">selenium-webdriver tests</a> node module!!</p>
<pre><code>driver.manage().window().setSize(x, y);
</code></pre> |
1,497,073 | Blackberry - fields layout animation | <p>It's easy to show some animation within one field - BitmapField or Screen:<br>
[Blackberry - background image/animation RIM OS 4.5.0][1]</p>
<p>But what if you need to move <strong>fields</strong>, not just images?</p>
<p>May be used: </p>
<ul>
<li>game workflow functionality, like chess, puzzle etc</li>
<li>application user-defined layout, like in Google gadgets</li>
<li>enhanced GUI animation effects</li>
</ul>
<p>So, I'd like to exchange my expirience in this task, on the other hand, I'd like to know about any others possibilities and suggestions.</p> | 1,497,076 | 1 | 1 | null | 2009-09-30 09:40:57.8 UTC | 9 | 2015-09-22 00:13:26.26 UTC | 2015-09-22 00:13:26.26 UTC | null | 1,849,664 | null | 67,407 | null | 1 | 7 | user-interface|blackberry|animation|custom-controls | 6,275 | <p>This effect may be easily achived with custom layout: </p>
<pre><code>class AnimatedManager extends Manager {
int ANIMATION_NONE = 0;
int ANIMATION_CROSS_FLY = 1;
boolean mAnimationStart = false;
Bitmap mBmpBNormal = Bitmap.getBitmapResource("blue_normal.png");
Bitmap mBmpBFocused = Bitmap.getBitmapResource("blue_focused.png");
Bitmap mBmpRNormal = Bitmap.getBitmapResource("red_normal.png");
Bitmap mBmpRFocused = Bitmap.getBitmapResource("red_focused.png");
Bitmap mBmpYNormal = Bitmap.getBitmapResource("yellow_normal.png");
Bitmap mBmpYFocused = Bitmap.getBitmapResource("yellow_focused.png");
Bitmap mBmpGNormal = Bitmap.getBitmapResource("green_normal.png");
Bitmap mBmpGFocused = Bitmap.getBitmapResource("green_focused.png");
int[] width = null;
int[] height = null;
int[] xPos = null;
int[] yPos = null;
BitmapButtonField mBButton = new BitmapButtonField(mBmpBNormal,
mBmpBFocused);
BitmapButtonField mRButton = new BitmapButtonField(mBmpRNormal,
mBmpRFocused);
BitmapButtonField mYButton = new BitmapButtonField(mBmpYNormal,
mBmpYFocused);
BitmapButtonField mGButton = new BitmapButtonField(mBmpGNormal,
mBmpGFocused);
public AnimatedManager() {
super(USE_ALL_HEIGHT | USE_ALL_WIDTH);
add(mBButton);
add(mRButton);
add(mYButton);
add(mGButton);
width = new int[] { mBButton.getPreferredWidth(),
mRButton.getPreferredWidth(),
mYButton.getPreferredWidth(),
mGButton.getPreferredWidth() };
height = new int[] { mBButton.getPreferredHeight(),
mRButton.getPreferredHeight(),
mYButton.getPreferredHeight(),
mGButton.getPreferredHeight() };
xPos = new int[] { 0, getPreferredWidth() - width[1], 0,
getPreferredWidth() - width[3] };
yPos = new int[] { 0, 0, getPreferredHeight() - height[2],
getPreferredHeight() - height[3] };
Timer timer = new Timer();
timer.schedule(mAnimationTask, 0, 100);
}
TimerTask mAnimationTask = new TimerTask() {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
updateLayout();
};
});
};
};
MenuItem mAnimationMenuItem = new MenuItem("Start", 0, 0) {
public void run() {
mAnimationStart = true;
};
};
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(mAnimationMenuItem);
}
public int getPreferredHeight() {
return Display.getHeight();
}
public int getPreferredWidth() {
return Display.getWidth();
}
protected void sublayout(int width, int height) {
width = getPreferredWidth();
height = getPreferredHeight();
if (getFieldCount() > 3) {
Field first = getField(0);
Field second = getField(1);
Field third = getField(2);
Field fourth = getField(3);
layoutChild(first, this.width[0], this.height[0]);
layoutChild(second, this.width[1], this.height[1]);
layoutChild(third, this.width[2], this.height[2]);
layoutChild(fourth, this.width[3], this.height[3]);
if (mAnimationStart) {
boolean anim1 = performLayoutAnimation(0,
width - this.width[0],
height - this.height[0]);
boolean anim2 = performLayoutAnimation(1, 0,
height - this.height[1]);
boolean anim3 = performLayoutAnimation(2,
width - this.width[2], 0);
boolean anim4 = performLayoutAnimation(3, 0, 0);
mAnimationStart = anim1 || anim2 || anim3 || anim4;
}
setPositionChild(first, xPos[0], yPos[0]);
setPositionChild(second, xPos[1], yPos[1]);
setPositionChild(third, xPos[2], yPos[2]);
setPositionChild(fourth, xPos[3], yPos[3]);
}
setExtent(width, height);
}
boolean performLayoutAnimation(int fieldIndex, int x, int y) {
boolean result = false;
if (xPos[fieldIndex] > x) {
xPos[fieldIndex] -= 2;
result = true;
} else if (xPos[fieldIndex] < x) {
xPos[fieldIndex] += 2;
result = true;
}
if (yPos[fieldIndex] > y) {
yPos[fieldIndex] -= 1;
result = true;
} else if (yPos[fieldIndex] < y) {
yPos[fieldIndex] += 1;
result = true;
}
return result;
}
}
</code></pre>
<p>BitmapButtonField class I've used: </p>
<pre><code>class BitmapButtonField extends ButtonField {
Bitmap mNormal;
Bitmap mFocused;
int mWidth;
int mHeight;
public BitmapButtonField(Bitmap normal, Bitmap focused) {
super(CONSUME_CLICK);
mNormal = normal;
mFocused = focused;
mWidth = mNormal.getWidth();
mHeight = mNormal.getHeight();
setMargin(0, 0, 0, 0);
setPadding(0, 0, 0, 0);
setBorder(BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
setBorder(VISUAL_STATE_ACTIVE, BorderFactory
.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
}
protected void paint(Graphics graphics) {
Bitmap bitmap = null;
switch (getVisualState()) {
case VISUAL_STATE_NORMAL:
bitmap = mNormal;
break;
case VISUAL_STATE_FOCUS:
bitmap = mFocused;
break;
case VISUAL_STATE_ACTIVE:
bitmap = mFocused;
break;
default:
bitmap = mNormal;
}
graphics.drawBitmap(0, 0, bitmap.getWidth(), bitmap.getHeight(),
bitmap, 0, 0);
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void layout(int width, int height) {
setExtent(mWidth, mHeight);
}
protected void applyTheme(Graphics arg0, boolean arg1) {
}
}
</code></pre> |
1,796,165 | LINQ group by expression syntax | <p>I've got a T-SQL query similar to this:</p>
<pre><code>SELECT r_id, r_name, count(*)
FROM RoomBindings
GROUP BY r_id, r_name
</code></pre>
<p>I would like to do the same using LINQ. So far I got here:</p>
<pre><code>var rooms = from roomBinding in DALManager.Context.RoomBindings
group roomBinding by roomBinding.R_ID into g
select new { ID = g.Key };
</code></pre>
<p>How can I extract the count(*) and r_name part?</p> | 1,796,210 | 1 | 1 | null | 2009-11-25 10:57:03.633 UTC | 7 | 2013-06-07 23:10:13.1 UTC | 2009-11-25 11:12:17.2 UTC | null | 31,136 | null | 40,872 | null | 1 | 49 | c#|linq | 44,509 | <p>Try this:</p>
<pre><code>var rooms = from roomBinding in DALManager.Context.RoomBindings
group roomBinding by new
{
Id = roomBinding.R_ID,
Name = roomBinding.r_name
}
into g
select new
{
Id = g.Key.Id,
Name = g.Key.Name,
Count = g.Count()
};
</code></pre>
<p><strong>Edit by Nick - Added method chain syntax for comparison</strong></p>
<pre><code>var rooms = roomBinding.GroupBy(g => new { Id = g.R_ID, Name = g.r_name })
.Select(g => new
{
Id = g.Key.Id,
Name = g.Key.Name,
Count = g.Count()
});
</code></pre> |
23,980,929 | What changes introduced in C++14 can potentially break a program written in C++11? | <p><strong>Introduction</strong></p>
<p>With the <em>C++14</em> (aka. <em>C++1y</em>) Standard in a state close to being final, programmers must ask themselves about backwards compatibility, and issues related to such.</p>
<hr>
<p><strong>The question</strong></p>
<p>In the answers of <a href="https://stackoverflow.com/q/23047198/1090079">this question</a> it is stated that the Standard has an <em>Appendix</em> dedicated to information regarding changes between revisions.</p>
<p>It would be helpful if these potential issues in the previously mentioned <em>Appendix</em> could be explained, perhaps with the help of any formal documents related to what is mentioned there.</p>
<ul>
<li><em>According to the Standard</em>: What changes introduced in <em>C++14</em> can potentially break a program written in C++11?</li>
</ul> | 23,980,931 | 1 | 0 | null | 2014-06-01 14:34:06.883 UTC | 94 | 2020-03-06 20:10:12.687 UTC | 2020-03-06 20:10:12.687 UTC | null | 6,451,573 | null | 1,090,079 | null | 1 | 58 | c++|c++11|c++14|language-lawyer|c++-faq | 51,275 | <blockquote>
<p><sup><strong>Note</strong>: In this post I consider a "<em>breaking change</em>" to be either, or both, of;<br /></sup>
<sup><code></code> 1. a change that will make legal <em>C++11</em> ill-formed when compiled as <em>C++14</em>, and;<br />
<code></code>2. a change that will change the runtime behavior when compiled as <em>C++14</em>, vs <em>C++11</em>.</sup></p>
</blockquote>
<hr>
<h1><em>C++11</em> vs <em>C++14</em>, what does the Standard say?</h1>
<p>The Standard draft (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf" rel="noreferrer">n3797</a>) has a section dedicated for just this kind of information, where it describes the (potentially breaking) differences between one revision of the standard, and another. </p>
<p>This post has used that section, <code>[diff.cpp11]</code>, as a base for a semi-elaborate discussion regarding the changes that could affect code written for <em>C++11</em>, but compiled as <em>C++14</em>.</p>
<hr>
<h2>C.3.1] Digit Separators</h2>
<p>The digit separator was introduced so that one could, in a more readable manner, write numeric literals and split them up in a way that is more natural way.</p>
<pre><code>int x = 10000000; // (1)
int y = 10'000'000; // (2), C++14
</code></pre>
<p><sup>It's easy to see that <em>(2)</em> is much easier to read than <em>(1)</em> in the above snippet, while both initializers have the same value.</sup></p>
<p>The potential issue regarding this feature is that the <em>single-quote</em> always denoted the start/end of a <em>character-literal</em> in <em>C++11</em>, but in <em>C++14</em> a <em>single-quote</em> can either be surrounding a <em>character-literal</em>, or used in the previously shown manner <em>(2)</em>.</p>
<p><br /></p>
<p><strong>Example Snippet, legal in both <em>C++11</em> and <em>C++14</em>, but with different behavior.</strong></p>
<pre><code>#define M(x, ...) __VA_ARGS__
int a[] = { M(1'2, 3'4, 5) };
// int a[] = { 5 }; <-- C++11
// int a[] = { 3'4, 5 }; <-- C++14
// ^-- semantically equivalent to `{ 34, 5 }`
</code></pre>
<p>( Note: More information regarding <em>single-quotes</em> as digit separators can be found in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3781.pdf" rel="noreferrer">n3781.pdf</a> )</p>
<hr>
<h2>C.3.2] Sized Deallocation</h2>
<p><em>C++14</em> introduces the opportunity to declare a global overload of <code>operator delete</code> suitable for <em>sized deallocation</em>, something which wasn't possible in <em>C++11</em>.</p>
<p>However, the Standard also mandates that a developer cannot declare just one of the two related functions below, it must declare either <strong>none</strong>, or <strong>both</strong>; which is stated in <em>[new.delete.single]p11</em>.</p>
<pre><code>void operator delete (void*) noexcept;
void operator delete (void*, std::size_t) noexcept; // sized deallocation
</code></pre>
<p><br /></p>
<p>Further information regarding the potential problem:</p>
<blockquote>
<blockquote>
<p>Existing programs that redefine the global unsized version do not also
define the sized version. When an implementation introduces a sized
version, the replacement would be incomplete and it is likely that
programs would call the implementation-provided sized deallocator on
objects allocated with the programmer-provided allocator.</p>
<p><sup><strong>Note</strong>: Quote taken from <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3536.html#Compatibility" rel="noreferrer">n3536 - C++ Sized Deallocation</a></p>
</blockquote>
</blockquote>
<p>( Note: More of interest is available in the paper titled <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3536.html" rel="noreferrer">n3536 - C++ Sized Deallocation</a>, written by <em>Lawrence Crowl</em> )</p>
<hr>
<h2>C.3.3] <code>constexpr</code> member-functions, no longer implicitly <code>const</code></h2>
<p>There are many changes to <em>constexpr</em> in C++14, but the only change that will change semantics between <em>C++11</em>, and <em>C++14</em> is the <em>constantness</em> of a <em>member-function</em> marked as <em>constexpr</em>.</p>
<p>The rationale behind this change is to allow <em>constexpr</em> <em>member-functions</em> to mutate the object to which they belong, something which is allowed due to the <a href="http://isocpp.org/files/papers/N3652.html" rel="noreferrer">relaxation of <em>constexpr</em></a>.</p>
<pre><code>struct A { constexpr int func (); };
// struct A { constexpr int func () const; }; <-- C++11
// struct A { constexpr int func (); }; <-- C++14
</code></pre>
<p><br /></p>
<p>Recommended material on this change, and why it is important enough to introduce potential code-breakage:</p>
<ul>
<li><a href="http://akrzemi1.wordpress.com/2013/06/20/constexpr-function-is-not-const/" rel="noreferrer"><strong>Andrzej's C++ blog</strong> - “constexpr” function is not “const”</a></li>
<li><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3598.html" rel="noreferrer"><strong>open-std.org</strong> - constexpr member functions and implicit const</a></li>
<li><a href="http://open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3652.html" rel="noreferrer">(<strong>open-std.org</strong> - Relaxing constraints on constexpr functions)</a></li>
</ul>
<p><br /></p>
<p><strong>Example snippet, legal in both <em>C++11</em> and <em>C++14</em>, but with different behavior</strong></p>
<pre><code>struct Obj {
constexpr int func (int) {
return 1;
}
constexpr int func (float) const {
return 2;
}
};
</code></pre>
<p></sup></p>
<pre><code>Obj const a = {};
int const x = a.func (123);
// int const x = 1; <-- C++11
// int const x = 2; <-- C++14
</code></pre>
<hr>
<h2>C.3.4] Removal of <code>std::gets</code></h2>
<p><a href="http://en.cppreference.com/w/cpp/io/c/gets" rel="noreferrer"><code>std::gets</code></a> has been <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3770.html#GB9" rel="noreferrer">removed</a> from the Standard Library because it is <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1194.htm" rel="noreferrer">considered dangerous</a>.</p>
<p>The implications of this is of course that trying to compile code written for C++11, in C++14, where such a function is used will most likely just fail to compile.</p>
<p><br /></p>
<p>( Note: there are ways of writing <a href="http://codepad.org/ZxyMmP6C" rel="noreferrer">code</a> that doesn't fail to compile, and have different behavior, that depends on the removal of <code>std::gets</code> from the <em>Standard Library</em> )</p> |
20,975,542 | Handle Laravel 4 upload big file exception | <p>My target is to manage the max upload file exception, and show a client side friendly message, but I don´t know where is the best place to controll this. This is my controller method:</p>
<pre><code>public function upload_file()
{
if (!Input::hasFile('file'))
return;
$utils = App::make('utils');
$file = Input::file('file');
$name = Input::get('name');
$size = $file->getSize();
if ($size > FileModel::$max_file_size)
return json_encode(array('success'=>false, 'message'=>sprintf('The file size should be lower than %smb.',FileModel::$max_file_size/1000000)));
$original_file_name = $file->getClientOriginalName();
$destination_directory = "";
$final_file_name = $utils->copy_file_to_location($file);
return json_encode(array('success'=>true, 'file'=>$original_file_name));
}
</code></pre>
<p>And this is the utils copy_file_to_location method:</p>
<pre><code>public function copy_file_to_location($file, $destination_directory = "")
{
if (!isset($file))
return;
$file_name = time()."_".$file->getClientOriginalName();
$file->move(app_path().'/storage/files/'.$destination_directory, $file_name);
return $file_name;
}
</code></pre>
<p>I don't knwo where to handle the exception that is raised when uploading files that have a grater size than the server max upload file size variable. Where and how should I handle this to show a user friendly message and do not lock the user interface. By the way I'm using ExtJs 4 in the client side. Thanks.</p>
<hr>
<p>EDIT</p>
<hr>
<p>I found a related <a href="https://stackoverflow.com/questions/2133652/how-to-gracefully-handle-files-that-exceed-phps-post-max-size">question</a> that helps a lot (it is the same problem), but I need to know where, inside Laravel, should I check this.</p> | 21,004,469 | 3 | 0 | null | 2014-01-07 15:30:37.193 UTC | 9 | 2017-10-27 17:02:52.037 UTC | 2017-05-23 11:46:55.11 UTC | null | -1 | null | 1,655,482 | null | 1 | 5 | php|file-upload|extjs4|laravel-4 | 11,896 | <p>There are two case: the file size is greater than the php variable <code>upload_max_filesize</code> and the second one is when it is grater than <code>post_max_size</code> variable. In the first one an exception is raised so an easy way it is catching it. In the second case there are not exception and I used <a href="https://stackoverflow.com/questions/2133652/how-to-gracefully-handle-files-that-exceed-phps-post-max-size">this</a> question for solving it.</p>
<p>Now, where check this code: in the Laravel controller aciton method. I thought that code in the controller's action never was excecuted, but I was wrong. So finally this is a way to solve this:</p>
<pre><code> public function upload_file()
{
$file_max = ini_get('upload_max_filesize');
$file_max_str_leng = strlen($file_max);
$file_max_meassure_unit = substr($file_max,$file_max_str_leng - 1,1);
$file_max_meassure_unit = $file_max_meassure_unit == 'K' ? 'kb' : ($file_max_meassure_unit == 'M' ? 'mb' : ($file_max_meassure_unit == 'G' ? 'gb' : 'unidades'));
$file_max = substr($file_max,0,$file_max_str_leng - 1);
$file_max = intval($file_max);
//handle second case
if((empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'))
{ //catch file overload error...
//grab the size limits...
return json_encode(array('success'=>false, 'message'=>sprintf('The file size should be lower than %s%s.',$file_max,$file_max_meassure_unit)));
}
try{
if (!Input::hasFile('file'))
return;
$utils = App::make('utils');
$file = Input::file('file');
$name = Input::get('name');
$size = $file->getSize();
if ($size > $file_max)
return json_encode(array('success'=>false, 'message'=>sprintf('El tamaño del archivo debe ser menor que %smb.',$file_max)));
$original_file_name = $file->getClientOriginalName();
$destination_directory = "";
$final_file_name = $utils->copy_file_to_location($file);
return json_encode(array('success'=>true, 'file'=>$original_file_name));
}
catch (Exception $e)
{
//handle first case
return json_encode(array('success'=>false, 'message'=>sprintf('The file size should be lower than %s%s.',$file_max,$file_max_meassure_unit)));
}
}
</code></pre> |
38,825,008 | How to use ImageMagick command line on Windows? | <p>My goal is to determine the compression parameters of the jpeg image that I have. As I understood from <a href="https://stackoverflow.com/questions/2024947/is-it-possible-to-tell-the-quality-level-of-a-jpeg/18378080#18378080">this answer</a>, it's possible using the ImageMagick function <em>identity</em>. I downloaded from the official site and installed <strong>ImageMagick-7.0.2-7-Q16-x64-dll.exe</strong>. Now, I have an application with GUI called ImageMagick Display that seems useless. Where can I find an IM command line to type this:</p>
<pre><code>identify -format '%Q' yourimage.jpg
</code></pre> | 41,094,852 | 5 | 4 | null | 2016-08-08 08:58:22.847 UTC | 5 | 2021-06-30 11:36:00.74 UTC | 2018-07-14 18:20:58.673 UTC | null | 7,355,741 | null | 5,214,345 | null | 1 | 13 | windows|image|imagemagick|jpeg | 40,199 | <p>Since it is version 7.x, there is a checkbox at the time of installation that says '<em>Install legacy utilities (e.g. convert)</em>'. You need to select that checkbox during installation.</p>
<p>Screenshot: <a href="https://i.stack.imgur.com/eJsFb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJsFb.png" alt="enter image description here" /></a></p>
<p>Once done, you will be able to use the commands from command line.</p>
<p>Another option is to use the command <code>magick identify --version</code></p>
<p>For version 6.x, it is not necessary.</p> |
38,950,802 | How to display line numbers in side by side diff in unix? | <p>The scenario is that i have 2 files which i want to diff side by side using the following command with the line numbers:</p>
<pre><code>diff -y file1.txt file2.txt
</code></pre>
<p>and</p>
<pre><code>sdiff file1.txt file2.txt
</code></pre>
<p>The above command just prints the side by side diff but doesn't display the line numbers. Is there any way to do it ? I searched a lot but couldn't find any solutions. I can't use third party tools FYI. <strong>Any genius ideas from anyone ?</strong> </p>
<p><strong>Update:</strong></p>
<p><em>I want the file numbers present of the file itself and not the line numbers generated by piping to cat -n etc.. Lets say, i am doing diff using "--suppress-common-lines" then the line numbers should be omitted which are not shown in the diff.</em></p> | 38,966,656 | 4 | 4 | null | 2016-08-15 07:17:34.573 UTC | 5 | 2022-05-14 12:30:30.413 UTC | 2017-06-30 00:42:25.467 UTC | null | 3,195,477 | null | 6,628,246 | null | 1 | 44 | file|unix|diff|sdiff | 41,681 | <p>Below code can be used to display the uncommon fields in two files, side by side.</p>
<pre><code>sdiff -l file1 file2 | cat -n | grep -v -e '($'
</code></pre>
<p>Below code will display common fields along with line numbers in the output.</p>
<pre><code>diff -y file1 file2 | cat -n | grep -v -e '($'
</code></pre> |
31,740,042 | No start database manager command was issued. SQLSTATE=57019 | <p>I am new to DB2 and I have installed DB2 9.7. </p>
<p>I created an instance which is shown below</p>
<pre><code>[sathish@oc3855733574 ~]$ db2ilist
sathish
</code></pre>
<p>Settings of /etc/services is shown below</p>
<pre><code>DB2_sathish 60000/tcp
DB2_sathish_1 60001/tcp
DB2_sathish_2 60002/tcp
DB2_sathish_END 60003/tcp
DB2_TMINST 50000/tcp
</code></pre>
<p>But, when I start using 'db2start' it throws the following error</p>
<pre><code>07/31/2015 10:26:20 0 0 SQL1042C An unexpected system error occurred.
SQL1032N No start database manager command was issued. SQLSTATE=57019
</code></pre>
<p>I installed DB2 using 'root' and starting 'DB2' from 'instance' (sathish in this case)</p>
<p>Any help or URL link will be of great use</p>
<p>Thanks
Sathish Kumar</p> | 31,992,105 | 4 | 0 | null | 2015-07-31 07:05:22.643 UTC | 2 | 2022-05-27 14:05:21.373 UTC | null | null | null | null | 5,048,561 | null | 1 | 10 | database|db2|database-administration | 62,879 | <p>I had a look into db2diag.log file and I got a unusual hack from one of the website</p>
<p>I followed the steps mentioned below and it worked</p>
<pre><code>a) db2trc on -f db2trace.out
b) db2start
c) db2trc off
</code></pre> |
46,355,454 | How to fix error: The markup in the document following the root element must be well-formed | <p>I put my code in the XML validation website and it gives me this error: </p>
<blockquote>
<p>Line 8: 4 The markup in the document following the root element must be well-formed.</p>
</blockquote>
<p>The line that is having an issue is the <code><xsl:output method = "html" doctype-system = "about:legacy-compat"/></code>, line.</p>
<h2>XML</h2>
<pre><code><?xml version="1.0"?>
<!-- Fig. 15.21: sorting.xsl -->
<xsl:stylesheet version = "1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/>
<!-- write XML declaration and DOCTYPE DTD information -->
*<xsl:output method = "html" doctype-system = "about:legacy-compat" />*
<!-- match document root -->
<xsl:template match="/"> -<html> <xsl:apply-templates/> </html>
</xsl:template>
</code></pre> | 46,355,526 | 2 | 0 | null | 2017-09-22 01:20:09.177 UTC | 5 | 2022-04-26 09:24:49.057 UTC | 2017-09-22 01:43:41.307 UTC | null | 290,085 | null | 8,521,845 | null | 1 | 22 | xml|xslt|xml-parsing|xml-validation | 150,951 | <h2>General case</h2>
<blockquote>
<p>The markup in the document following the root element must be well-formed.</p>
</blockquote>
<p>This error indicates that your XML has markup following the root element.
In order to be <a href="https://stackoverflow.com/a/25830482/290085">well-formed</a>, XML <a href="https://www.w3.org/TR/REC-xml/#dt-root" rel="noreferrer">must have <strong><em>exactly one</em></strong> root element</a>, and there can be no further markup following the single root element.</p>
<p><strong>One root element example (GOOD)</strong></p>
<pre><code><r>
<a/>
<b/>
<c/>
</r>
</code></pre>
<p>The most common sources for this error are:</p>
<ol>
<li><p><strong>Including stray or extra close tags (BAD):</strong></p>
<pre><code><r>
<a/>
<b/>
<c/>
</r>
</r> <!-- shouldn't be here -->
</code></pre></li>
<li><p><strong>Intentionally having multiple root elements (BAD):</strong></p>
<pre><code><a/>
<b/> <!-- second root element shouldn't be here -->
<c/> <!-- third root element shouldn't be here -->
</code></pre></li>
<li><p><strong>Unintentionally having multiple root elements (BAD):</strong></p>
<pre><code><r/> <!-- shouldn't be self-closing -->
<a/>
<b/>
<c/>
</r>
</code></pre></li>
<li><p><strong>Parsing different XML than you think (BAD):</strong></p>
<p>Log the XML immediately before providing to the parse that's
failing in order to make sure that the XML that the parser is
seeing is the same as the XML you think it's seeing. Common
errors here include:</p>
<ul>
<li>The filename of the XML document being passed to the
parser differs from what you believe it is.</li>
<li>The buffer of the XML being dirty. Make sure it's been
cleared prior to adding your XML.</li>
<li>An earlier program from a prior stage in your pipeline
changing the XML prior to the parsing that's yielding
this error message.</li>
</ul></li>
</ol>
<hr>
<h2>Your particular problem</h2>
<p>In your particular case, your XML appears to have multiple root elements because the <code>xsl:stylesheet</code> element is closed prematurely (case <strong>#3</strong> above).</p>
<p>Change</p>
<pre><code> xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/>
</code></pre>
<p>to</p>
<pre><code> xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
</code></pre>
<p>to fix your immediate problem, and add a closing tag,</p>
<pre><code></xsl:stylesheet>
</code></pre>
<p>if one does not already exist in your real document.</p> |
40,484,900 | How do I handle deletes in react-apollo | <p>I have a mutation like</p>
<pre><code>mutation deleteRecord($id: ID) {
deleteRecord(id: $id) {
id
}
}
</code></pre>
<p>and in another location I have a list of elements.</p>
<p>Is there something better I could return from the server, and how should I update the list?</p>
<p>More generally, what is best practice for handling deletes in apollo/graphql?</p> | 40,729,074 | 6 | 3 | null | 2016-11-08 10:45:43.367 UTC | 11 | 2022-09-01 13:37:55.363 UTC | 2022-09-01 13:37:55.363 UTC | null | 10,158,227 | null | 1,259,779 | null | 1 | 34 | javascript|graphql|apollo-server|react-apollo | 27,877 | <p>I am not sure it is <em>good practise style</em> but here is how I handle the deletion of an item in react-apollo with updateQueries:</p>
<pre><code>import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import update from 'react-addons-update';
import _ from 'underscore';
const SceneCollectionsQuery = gql `
query SceneCollections {
myScenes: selectedScenes (excludeOwner: false, first: 24) {
edges {
node {
...SceneCollectionScene
}
}
}
}`;
const DeleteSceneMutation = gql `
mutation DeleteScene($sceneId: String!) {
deleteScene(sceneId: $sceneId) {
ok
scene {
id
active
}
}
}`;
const SceneModifierWithStateAndData = compose(
...,
graphql(DeleteSceneMutation, {
props: ({ mutate }) => ({
deleteScene: (sceneId) => mutate({
variables: { sceneId },
updateQueries: {
SceneCollections: (prev, { mutationResult }) => {
const myScenesList = prev.myScenes.edges.map((item) => item.node);
const deleteIndex = _.findIndex(myScenesList, (item) => item.id === sceneId);
if (deleteIndex < 0) {
return prev;
}
return update(prev, {
myScenes: {
edges: {
$splice: [[deleteIndex, 1]]
}
}
});
}
}
})
})
})
)(SceneModifierWithState);
</code></pre> |
37,482,907 | Firebase : Differences between realtime database and file storage | <p>I learnt about real-time data storage and hosting storage from this post <a href="https://stackoverflow.com/questions/28450455/difference-between-data-storage-and-hosting-storage">Difference between Data Storage and Hosting Storage?</a></p>
<p>But i am still not clear about real time Database and and newly introduced file storage.</p>
<p>Does anybody have some brief explanation about it ?</p>
<p>Thanks in advance .</p>
<p>(As per the concern about duplicated with <a href="https://stackoverflow.com/questions/28450455/difference-between-data-storage-and-hosting-storage">Difference between Data Storage and Hosting Storage?</a> what the problem solves and what i am asking are two different things and hosting storage and file storage are different in case of google firebase )</p> | 37,483,948 | 2 | 1 | null | 2016-05-27 11:56:12.577 UTC | 13 | 2018-10-06 00:33:43.517 UTC | 2017-05-23 12:03:06.937 UTC | null | -1 | null | 2,581,314 | null | 1 | 40 | firebase|firebase-realtime-database|firebase-storage | 19,116 | <p>Firebase now offers these places to store your data:</p>
<ul>
<li><a href="https://firebase.google.com/docs/database/" rel="noreferrer">Realtime Database</a></li>
<li><a href="https://firebase.google.com/docs/remote-config/" rel="noreferrer">Remote Config</a></li>
<li><a href="https://firebase.google.com/docs/hosting/" rel="noreferrer">Hosting</a></li>
<li><a href="https://firebase.google.com/docs/storage/" rel="noreferrer">Storage</a></li>
<li><a href="https://firebase.google.com/docs/firestore/" rel="noreferrer">Cloud Firestore</a></li>
</ul>
<p>The best place to store your data, depends on the type of data you want to store and the way you want to consume it.</p>
<p>The <a href="https://firebase.google.com/docs/database/#implementation_path" rel="noreferrer">Firebase documentation</a> says this about it:</p>
<blockquote>
<ul>
<li><p>The Firebase Realtime Database stores JSON application data, like game state or chat messages, and synchronizes changes instantly across all connected devices.</p>
</li>
<li><p>Firebase Remote Config stores developer-specified key-value pairs to change the behavior and appearance of your app without requiring users to download an update.</p>
</li>
<li><p>Firebase Hosting hosts the HTML, CSS, and JavaScript for your website as well as other developer-provided assets like graphics, fonts, and icons.</p>
</li>
<li><p>Firebase Storage stores files such as images, videos, and audio as well as other user-generated content.</p>
</li>
</ul>
</blockquote>
<p>On choosing between Cloud Firestore and the Firebase Realtime Database, the <a href="https://firebase.google.com/docs/database/rtdb-vs-firestore" rel="noreferrer">Firebase documentation says</a>:</p>
<blockquote>
<p>Firebase offers two cloud-based, client-accessible database solutions that support realtime data syncing:</p>
<p><strong>Realtime Database</strong> is Firebase's original database. It's an efficient, low-latency solution for mobile apps that require synced states across clients in realtime.</p>
<p><strong>Cloud Firestore</strong> is Firebase's new flagship database for mobile app development. It improves on the successes of the Realtime Database with a new, more intuitive data model. Cloud Firestore also features richer, faster queries and scales better than the Realtime Database.</p>
</blockquote> |
37,567,148 | Unable to verify the first certificate in Node.js | <p>I have a Nodejs API and it uses ssl and https, so i'm trying to consume it on a different server to build a web app using express-js.</p>
<p>I receive the following error when making a GET request:</p>
<pre><code>events.js:141
throw er; // Unhandled 'error' event
^
Error: unable to verify the first certificate
at Error (native)
at TLSSocket.<anonymous> (_tls_wrap.js:1017:38)
at emitNone (events.js:67:13)
at TLSSocket.emit (events.js:166:7)
at TLSSocket._init.ssl.onclienthello.ssl.oncertcb.TLSSocket._finishInit (_tls_wrap.js:582:8)
at TLSWrap.ssl.onclienthello.ssl.oncertcb.ssl.onnewsession.ssl.onhandshakedone (_tls_wrap.js:424:38)
</code></pre>
<p>I've tried the following, with no success:</p>
<ul>
<li><p>Adding <code>require('ssl-root-cas').inject();</code> and <code>rejectUnauthorized: false,</code> on the request. </p></li>
<li><p>Adding <code>process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";</code> on my main file, which gave me a <code>Error: socket hang up</code></p></li>
</ul>
<p>The request code:</p>
<pre><code>var service_bus = require('service_bus');
var error_engine = require('error_engine');
exports.get = function(call_back){
function request_service() {
require('ssl-root-cas').inject();
var end_point = {
host: "www.xxxx.com",
port: "4433",
path: "/api/xxx/xx/",
method: "GET",
headers: {
"Content-Type": "application/json",
"X-app-key": "xxxxxxxxxxxxxxxxxxxxxxxxxx"
},
is_ssl: true
};
service_bus.call(end_point, {}, function (error, result) {
console.log(error);
if (!error) {
return call_back(result);
}
else {
return call_back(error_engine.get_error_by_code('1500', ''));
}
});
}
request_service();
};
</code></pre>
<p>and the main file for the web app:</p>
<pre><code>var express = require('express');
var exphbs = require('express-handlebars');
var path = require('path');
var passport = require('passport');
var session = require('express-session');
var uuid = require("node-uuid");
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(cors());
app.use(express.static(__dirname + '/public'));
app.use('img',express.static(path.join(__dirname, 'public/images')));
app.use('js',express.static(path.join(__dirname, 'public/js')));
app.use('css',express.static(path.join(__dirname, 'public/css')));
app.use('fonts',express.static(path.join(__dirname, 'public/fonts')));
//app.use(exphbs.registerHelper('paginate', paginate));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
proxy: true,
resave: true,
saveUninitialized: true,
uuid: function(req) {
return uuid()
},
secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}));
require("./xxxxxxx/endpoints")(app);
require("./xxxxxxxx/endpoints")(app);
require("./xxxxxxxx/endpoints")(app, passport);
mongoose.connect("mongodb://localhost/database");
app.listen(8080);
</code></pre>
<p>Any suggestions as to why this error occurs are highly appreciated. </p> | 38,366,087 | 1 | 2 | null | 2016-06-01 11:17:57.683 UTC | 5 | 2017-02-17 20:02:06.68 UTC | 2017-02-17 20:02:06.68 UTC | null | 1,259,510 | null | 2,131,096 | null | 1 | 13 | node.js|express|ssl|request|ssl-certificate | 47,193 | <p>I solve this problem by using another package it's called "request" also don't forget to add </p>
<pre><code>process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
</code></pre>
<p>before calling the API.</p> |
53,738,919 | Emit event with parameters in vue | <p>i'm trying to emit function with parameters like that.</p>
<pre><code>template: `
<div class="searchDropDown">
<div class="dropdown is-active">
<div class="dropdown-trigger">
<button class="button" aria-haspopup="true" aria-controls="dropdown-menu">
<span>{{selectedItem}}</span>
</button>
</div>
<div class="dropdown-menu" id="dropdown-menu" role="menu">
<div class="dropdown-content">
<a class="dropdown-item" v-for="item in drop" @click="$emit('select-menu-item($event)')">
{{item.name}}
</a>
</div>
</div>
</div>
</div>
`
</code></pre>
<p>here is the i'm trying to pass item to method like a parameter.</p>
<p>here is my component which i try to emit function: </p>
<pre><code><search-component v-bind="searchProps" @select-menu-item="selectedITem($event)"></search-component>
</code></pre>
<p>and here is my method: </p>
<pre><code>selectedITem(arg1) {
console.log("cl")
console.log(arg1)
}
</code></pre>
<p>here is if i'm not trying to pass parameter everything well work so my method <strong>selectedITem</strong> is working. When i try to pass parameter like that nothing happened and i'm not getting some error.</p> | 53,739,018 | 2 | 3 | null | 2018-12-12 08:30:28.82 UTC | 7 | 2020-10-21 09:36:22.153 UTC | null | null | null | null | 3,348,410 | null | 1 | 70 | javascript|vue.js|components | 111,338 | <p>The following argument(s) in <code>$emit()</code> are the arguments in your emitted function.</p>
<pre><code>$emit('select-menu-item', $event, 1, 2, 3, 4, "cupcakes")
</code></pre>
<p>and in your component method.</p>
<pre><code>selectMenuItem: function(evt, num1, num2, num3, num4, food){
}
</code></pre>
<p>And in your actual component markup, you don't need to add arguments, just write the reference to the method <strong>without parenthesis</strong>.</p>
<pre><code><search-component v-bind="searchProps" @select-menu-item="selectMenuItem">
</code></pre>
<hr>
<p>SAMPLE</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>window.onload = function(){
const component = function() {
return {
template: `
<div>
<button @click="$emit('click-me', 'foobar')">
Click Me
</button>
</div>
`,
props: ["data"]
}
}
new Vue({
el: container,
data: {},
components: { "my-component": component(), },
methods: {
clickMe: function(str){
console.log(str);
}
}
});
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="container">
<my-component :data=$data @click-me="clickMe"></my-component>
</div></code></pre>
</div>
</div>
</p> |
53,422,407 | Different CUDA versions shown by nvcc and NVIDIA-smi | <p>I am very confused by the different CUDA versions shown by running <code>which nvcc</code> and <code>nvidia-smi</code>. I have both cuda9.2 and cuda10 installed on my ubuntu 16.04. Now I set the PATH to point to cuda9.2. So when I run</p>
<pre class="lang-sh prettyprint-override"><code>$ which nvcc
/usr/local/cuda-9.2/bin/nvcc
</code></pre>
<p>However, when I run</p>
<pre><code>$ nvidia-smi
Wed Nov 21 19:41:32 2018
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 410.72 Driver Version: 410.72 CUDA Version: 10.0 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GeForce GTX 106... Off | 00000000:01:00.0 Off | N/A |
| N/A 53C P0 26W / N/A | 379MiB / 6078MiB | 2% Default |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 1324 G /usr/lib/xorg/Xorg 225MiB |
| 0 2844 G compiz 146MiB |
| 0 15550 G /usr/lib/firefox/firefox 1MiB |
| 0 19992 G /usr/lib/firefox/firefox 1MiB |
| 0 23605 G /usr/lib/firefox/firefox 1MiB |
</code></pre>
<p>So am I using cuda9.2 as <code>which nvcc</code> suggests, or am I using cuda10 as <code>nvidia-smi</code> suggests? I <a href="https://stackoverflow.com/questions/34319877/nvcc-has-different-version-than-cuda">saw this answer</a> but it does not provide direct answer to the confusion, it just asks us to reinstall the CUDA Toolkit, which I already did.</p> | 53,504,578 | 5 | 4 | null | 2018-11-22 00:44:01.01 UTC | 89 | 2022-09-04 09:51:48.103 UTC | 2021-08-28 04:05:20.667 UTC | null | 3,728,901 | null | 3,736,306 | null | 1 | 232 | cuda | 152,076 | <p>CUDA has 2 primary APIs, the runtime and the driver API. Both have a corresponding version (e.g. 8.0, 9.0, etc.)</p>
<p>The necessary support for the driver API (e.g. <code>libcuda.so</code> on linux) is installed by the GPU driver installer.</p>
<p>The necessary support for the runtime API (e.g. <code>libcudart.so</code> on linux, and also <code>nvcc</code>) is installed by the CUDA toolkit installer (which may also have a GPU driver installer bundled in it).</p>
<p>In any event, the (installed) driver API version may not always match the (installed) runtime API version, especially if you install a GPU driver independently from installing CUDA (i.e. the CUDA toolkit).</p>
<p>The <code>nvidia-smi</code> tool gets installed by the GPU driver installer, and generally has the GPU driver in view, not anything installed by the CUDA toolkit installer.</p>
<p>Recently (somewhere between 410.48 and 410.73 driver version on linux) the powers-that-be at NVIDIA decided to add reporting of the CUDA Driver API version installed by the driver, in the output from <code>nvidia-smi</code>.</p>
<p>This has no connection to the installed CUDA runtime version.</p>
<p><code>nvcc</code>, the CUDA compiler-driver tool that is installed with the CUDA toolkit, will always report the CUDA runtime version that it was built to recognize. It doesn't know anything about what driver version is installed, or even if a GPU driver is installed.</p>
<p>Therefore, by design, these two numbers don't necessarily match, as they are reflective of two different things.</p>
<p>If you are wondering why <code>nvcc -V</code> displays a version of CUDA you weren't expecting (e.g. it displays a version other than the one you think you installed) or doesn't display anything at all, version wise, it may be because you haven't followed the mandatory instructions in step 7 (prior to CUDA 11) (or step 6 in the CUDA 11 linux install guide) of the <a href="https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#post-installation-actions" rel="nofollow noreferrer">cuda linux install guide</a></p>
<p>Note that although this question mostly has linux in view, the same concepts apply to <strong>windows</strong> CUDA installs. The driver has a CUDA driver version associated with it (which can be queried with <code>nvidia-smi</code>, for example). The CUDA runtime also has a CUDA runtime version associated with it. The two will not necessarily match in all cases.</p>
<p>In most cases, if <code>nvidia-smi</code> reports a CUDA version that is numerically equal to or higher than the one reported by <code>nvcc -V</code>, this is not a cause for concern. That is a defined compatibility path in CUDA (newer drivers/driver API support "older" CUDA toolkits/runtime API). For example if <code>nvidia-smi</code> reports CUDA 10.2, and <code>nvcc -V</code> reports CUDA 10.1, that is generally not cause for concern. It should just work, and it does not necessarily mean that you "actually installed CUDA 10.2 when you meant to install CUDA 10.1"</p>
<p>If <code>nvcc</code> command doesn't report anything at all (e.g. <code>Command 'nvcc' not found...</code>) or if it reports an unexpected CUDA version, this may also be due to an incorrect CUDA install, i.e the mandatory steps mentioned above were not performed correctly. You can start to figure this out by using a linux utility like <code>find</code> or <code>locate</code> (use man pages to learn how, please) to find your <code>nvcc</code> executable. Assuming there is only one, the path to it can then be used to fix your PATH environment variable. The <a href="https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#mandatory-post" rel="nofollow noreferrer">CUDA linux install guide</a> also explains how to set this. You may need to adjust the CUDA version in the PATH variable to match your actual CUDA version desired/installed.</p>
<p>Similarly, when using docker, the <code>nvidia-smi</code> command will generally report the driver version installed on the base machine, whereas other version methods like <code>nvcc --version</code> will report the CUDA version installed inside the docker container.</p>
<p>Similarly, if you have used another installation method for the CUDA "toolkit" such as Anaconda, you may discover that the version indicated by Anaconda does not "match" the version indicated by <code>nvidia-smi</code>. However, the above comments still apply. Older CUDA toolkits installed by Anaconda can be used with newer versions reported by <code>nvidia-smi</code>, and the fact that <code>nvidia-smi</code> reports a newer/higher CUDA version than the one installed by Anaconda does not mean you have an installation problem.</p>
<p><a href="https://stackoverflow.com/questions/70048525/why-does-python-show-a-wrong-cuda-version">Here</a> is another question that covers similar ground. The above treatment does not in any way indicate that this answer is only applicable if you have installed multiple CUDA versions intentionally or unintentionally. The situation presents itself <em>any time you install CUDA</em>. The version reported by <code>nvcc</code> and <code>nvidia-smi</code> may not match, and that is <strong>expected</strong> behavior and in most cases quite normal.</p> |
36,372,571 | IntelliJ IDEA and Gradle: Why there are 3 modules per sub-module? | <p>I am rather confused by IntelliJ IDEA's gradle integration and the mapping of gradle subprojects to IDEA's modules.</p>
<ul>
<li>Why are there 3 modules for every gradle subproject (client, client_main and client_test)?</li>
<li>Is there a way to get rid of the "parent" module? Every time I delete it my build breaks in confusing ways.</li>
</ul>
<p><a href="https://i.stack.imgur.com/nhxlH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nhxlH.png" alt="Project Structure"></a></p>
<p><strong>UPDATE</strong></p>
<ul>
<li>The content root of the third module ("server") is always set to the entire folder like seen below. This means I can't mark directories in build as generated sources, since the are excluded by default.</li>
</ul>
<p><a href="https://i.stack.imgur.com/FnTB4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FnTB4.png" alt="enter image description here"></a></p> | 36,372,940 | 2 | 4 | null | 2016-04-02 11:21:01.283 UTC | 16 | 2019-08-15 06:36:47.137 UTC | 2018-04-01 01:15:40.92 UTC | null | 2,458,310 | null | 342,947 | null | 1 | 23 | java|intellij-idea|gradle | 17,317 | <p>It is now possible to deselect that option when importing the gradle project in IDEA, checked in 2016.1.2 Ultimate IDE. First go to the import gradle option and select your gradle file.</p>
<p><a href="https://i.stack.imgur.com/bZtPT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bZtPT.png" alt="Project Import Dialog"></a></p>
<p>Then in the dialog that appears, make sure you deselect the option that says <strong>create separate module per source set</strong>. This is selected by default. Now continue with importing the project as you normally would.</p>
<p><a href="https://i.stack.imgur.com/uVEgo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uVEgo.png" alt="Gradle configuration dialog"></a></p>
<p>And that's it, you can enjoy your project, just one module will be created for each sub project in the multi project gradle build.</p>
<p>This option is only useful if you are having a separate sub project in gradle for the tests like me. Otherwise, the default way works pretty much good, as I found it more easy to launch unit tests.</p>
<p><a href="https://i.stack.imgur.com/3bV62.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3bV62.png" alt="Imported project, package view"></a></p>
<p>Hope this helps.</p> |
25,150,404 | How can I see print() statements in behave (BDD) | <p>Context: I am using Python with Behave (BDD).</p>
<p>Whether I run my tests from the command line (behave) or from a custom main(), the behavior is the same: the test runs and the only output that I see in the console is the standard BDD report.</p>
<p>My tests include print() statements that help me debug my code. However, none of these print statements are being displayed in the console output when I run behave.</p>
<p>Is there any way we can <b>have "behave" display the print statements in our code?</b></p>
<p>My Main()</p>
<pre><code>config = Configuration()
if not config.format:
default_format = config.defaults["default_format"]
config.format = [ default_format ]
config.verbose = True
r = runner.Runner(config)
r.run()
if config.show_snippets and r.undefined_steps:
print_undefined_step_snippets(r.undefined_steps)
</code></pre>
<p>My test.feature file:</p>
<pre><code>Feature: My test feature with the Behave BDD
Scenario: A simple test
Given you are happy
When someone says hi
Then you smile
</code></pre>
<p>My test_steps.py file:</p>
<pre><code>from behave import given, when, then, step, model
@given('you are happy')
def step_impl(context):
pass
@when ('someone says {s}')
def step_impl(context, s):
context.message = s
print("THIS IS NEVER DISPLAYED IN THE CONSOLE")
pass
@then ('you smile')
def step_impl(context):
assert(context.message == "hi")
</code></pre> | 25,291,321 | 8 | 3 | null | 2014-08-06 00:17:47.393 UTC | 11 | 2022-09-19 21:44:53.23 UTC | null | null | null | null | 2,566,758 | null | 1 | 51 | python|bdd|python-behave | 32,374 | <p>I figured it out after spending more time reading the documentation. It is actually quite simple. By default, <code>behave</code> does <strong>not</strong> display any output (i.e. by using <code>print()</code>) unless there is a failure in the test.
To force displaying all output regardless of the outcome of the test (pass/fail), all you need is to change some of the default settings. The easiest way to achieve that is to create a file named <code>behave.ini</code> in the root of your project's directory and put the following:</p>
<p>Filename: <strong><code>behave.ini</code></strong></p>
<pre><code>[behave]
stderr_capture=False
stdout_capture=False
</code></pre>
<p>Next time you run your behave tests, you will see all outputs from your debug statements whether your tests pass or fail.</p> |
39,504,180 | Escaping Closures in Swift | <p>I'm new to Swift and I was reading the manual when I came across escaping closures. I didn't get the manual's description at all. Could someone please explain to me what escaping closures are in Swift in simple terms.</p> | 39,504,347 | 7 | 2 | null | 2016-09-15 06:13:32.377 UTC | 17 | 2022-07-09 15:43:34.22 UTC | 2017-05-23 10:19:02.683 UTC | null | 128,886 | null | 6,616,619 | null | 1 | 49 | swift|closures | 18,215 | <p>Consider this class:</p>
<pre><code>class A {
var closure: (() -> Void)?
func someMethod(closure: @escaping () -> Void) {
self.closure = closure
}
}
</code></pre>
<p><code>someMethod</code> assigns the closure passed in, to a property in the class.</p>
<p>Now here comes another class:</p>
<pre><code>class B {
var number = 0
var a: A = A()
func anotherMethod() {
a.someMethod { self.number = 10 }
}
}
</code></pre>
<p>If I call <code>anotherMethod</code>, the closure <code>{ self.number = 10 }</code> will be stored in the instance of <code>A</code>. Since <code>self</code> is captured in the closure, the instance of <code>A</code> will also hold a strong reference to it.</p>
<p>That's basically an example of an escaped closure!</p>
<p>You are probably wondering, "what? So where did the closure escaped from, and to?"</p>
<p>The closure escapes from the scope of the method, to the scope of the class. And it can be called later, even on another thread! This could cause problems if not handled properly.</p>
<p>By default, Swift doesn't allow closures to escape. You have to add <code>@escaping</code> to the closure type to tell the compiler "Please allow this closure to escape". If we remove <code>@escaping</code>:</p>
<pre><code>class A {
var closure: (() -> Void)?
func someMethod(closure: () -> Void) {
}
}
</code></pre>
<p>and try to write <code>self.closure = closure</code>, it doesn't compile!</p> |
48,847,613 | purrr map equivalent of nested for loop | <p>What is the purrr::map equivalent of:</p>
<pre><code>for (i in 1:4) {
for (j in 1:6) {
print(paste(i, j, sep = "-"))
}
}
</code></pre>
<p>OR </p>
<pre><code>lapply(1:4, function(i)
lapply(1:6, function(j)
print(paste(i, j, sep = "-"))))
</code></pre>
<p>Conceptually, what I'm not getting is how to refer to the <em>outer</em> loop in the <em>inner</em> map function.</p>
<pre><code>map(1:4, ~ map(1:6, ~ print(paste(.x, ????, sep = "-")))
</code></pre> | 48,853,460 | 4 | 3 | null | 2018-02-18 01:31:32.14 UTC | 24 | 2021-10-05 14:45:27.707 UTC | null | null | null | null | 9,375,330 | null | 1 | 39 | r|purrr | 10,372 | <p>As @r2evans points out, the <code>.x</code> from your first call is masked. however you can create a lambda function that takes 2 parameters <code>.x</code> and <code>.y</code>, and assign the previous <code>.x</code> to the new <code>.y</code> through the <code>...</code> argument.</p>
<p>I'll use <code>walk</code> rather than <code>map</code> as in this case you're only interested in side effects (printing)</p>
<pre><code>walk(1:4,~ walk(1:6, ~ print(paste(.x, .y, sep = "-")),.y=.x))
</code></pre>
<p>Another option is to use <code>expand.grid</code> to lay out the combinations, and then iterate on those with <code>pwalk</code> (or <code>pmap</code> in other circumstances)</p>
<pre><code>purrr::pwalk(expand.grid(1:4,1:6),~print(paste(.x, .y, sep = "-")))
</code></pre>
<p>Output in both cases:</p>
<pre><code>[1] "1-1"
[1] "2-1"
[1] "3-1"
[1] "4-1"
[1] "5-1"
[1] "6-1"
[1] "1-2"
[1] "2-2"
[1] "3-2"
[1] "4-2"
[1] "5-2"
[1] "6-2"
[1] "1-3"
[1] "2-3"
[1] "3-3"
[1] "4-3"
[1] "5-3"
[1] "6-3"
[1] "1-4"
[1] "2-4"
[1] "3-4"
[1] "4-4"
[1] "5-4"
[1] "6-4"
</code></pre> |
19,883,505 | Reset "called" Count on Sinon Spy | <p>How do I reset the "called" count on a Sinon spy before each test?</p>
<p>Here's what I'm doing now:</p>
<pre><code>beforeEach(function() {
this.spied = sinon.spy(Obj.prototype, 'spiedMethod');
});
afterEach(function() {
Obj.prototype.spiedMethod.restore();
this.spied.reset();
});
</code></pre>
<p>But when I check the call count in a test:</p>
<pre><code>it('calls the method once', function() {
$.publish('event:trigger');
expect(this.spied).to.have.been.calledOnce;
});
</code></pre>
<p>...the test fails and reports that the method was called X number of times (once for each previous test that also triggered the same event).</p> | 29,660,061 | 1 | 1 | null | 2013-11-09 21:47:32.943 UTC | 3 | 2018-03-22 08:31:08.147 UTC | null | null | null | null | 723,007 | null | 1 | 48 | javascript|unit-testing|mocha.js|sinon|chai | 29,229 | <p>This question was asked a while back but may still be interesting, especially for people who are new to sinon. </p>
<p><strike><code>this.spied.reset()</code> is not needed as <code>Obj.prototype.spiedMethod.restore();</code> removes the spy.</strike></p>
<p><strong>Update 2018-03-22</strong>:</p>
<p>As pointed out in some of the comments below my answer, <a href="http://sinonjs.org/releases/v4.4.8/stubs/#stubreset" rel="noreferrer">stub.reset</a> will do two things:</p>
<ol>
<li>Remove the stub behaviour</li>
<li>Remove the stub history (callCount).</li>
</ol>
<p>According to the <a href="http://sinonjs.org/releases/v4.4.8/stubs/#stubreset" rel="noreferrer">docs</a> this behaviour was added in [email protected].</p>
<p><strong>The updated answer to the question would be to use <a href="http://sinonjs.org/releases/v4.4.8/stubs/#stubresethistory" rel="noreferrer">stub.resetHistory()</a></strong>.</p>
<p>Example from the docs:</p>
<pre><code>var stub = sinon.stub();
stub.called // false
stub();
stub.called // true
stub.resetHistory();
stub.called // false
</code></pre>
<p><strong>Update:</strong> </p>
<ul>
<li>If you just want to <strong>reset the call count</strong>, use <code>reset</code>. This keeps the spy. </li>
<li>To <strong>remove the spy</strong> use <code>restore</code>.</li>
</ul>
<p>When working with sinon you can use the <a href="http://sinonjs.org/docs/#assertions" rel="noreferrer">sinon assertions</a> for enhanced testing. So instead of writing <code>expect(this.spied).to.have.been.calledOnce;</code> one could write:</p>
<pre><code>sinon.assert.calledOnce(Obj.prototype.spiedMethod);
</code></pre>
<p>This would work as well with <code>this.spied</code>:</p>
<pre><code>sinon.assert.calledOnce(this.spied);
</code></pre>
<p>There are a lot of other sinon assertion methods. Next to <code>calledOnce</code> there are also <code>calledTwice</code>, <code>calledWith</code>, <code>neverCalledWith</code> and a lot more on <a href="http://sinonjs.org/docs/#assertions" rel="noreferrer">sinon assertions</a>.</p> |
6,654,157 | How to get a platform independent directory separator in PHP? | <p>I'm building a path string in PHP. I need it to work across platforms (i.e., Linux, Windows, OS X).
I'm doing this:</p>
<pre><code>$path = $someDirectory.'/'.$someFile;
</code></pre>
<p>Assume <code>$someDirectory</code> and <code>$someFile</code> are formatted correctly at run-time on the various platforms. This works beautifully on Linux and OS X, but not on Windows. The issue is the <code>/</code> character, which I thought would work for Windows.</p>
<p>Is there a PHP function or some other trick to switch this to <code>\</code> at runtime on Windows?</p>
<p><b>EDIT:</b> Just to be clear, the resultant string is </p>
<pre><code>c:\Program Files (x86)\Sitefusion\Sitefusion.org\Defaults\pref/user.preferences
</code></pre>
<p>on Windows. Obviously the mix of slashes confuses Windows.</p> | 6,654,194 | 2 | 3 | null | 2011-07-11 17:43:44.13 UTC | 9 | 2015-05-05 08:59:15.22 UTC | 2015-05-05 08:58:33.57 UTC | null | 1,091,386 | null | 675,285 | null | 1 | 73 | php|directory|filepath | 60,689 | <p>Try this one</p>
<p>DIRECTORY_SEPARATOR</p>
<pre><code>$patch = $somePath. DIRECTORY_SEPARATOR .$someFile
</code></pre>
<p>or you can define yours </p>
<pre><code>PHP_OS == "Windows" ||
PHP_OS == "WINNT" ? define("SEPARATOR", "\\") : define("SEPARATOR", "/");
</code></pre> |
7,512,425 | How to use my Entities and Entity Managers in Symfony 2 Console Command? | <p>I want to a few terminal commands to my Symfony2 application. I've gone through the <a href="http://symfony.com/doc/2.0/cookbook/console.html">example in the cookbook</a>, but I couldn't find out how to access my settings, my entity manager and my entities here. In the constructor, I get the container (which should yield me access to settings and entities) using</p>
<pre><code>$this->container = $this->getContainer();
</code></pre>
<p>But this call generates an error:</p>
<blockquote>
<p>Fatal error: Call to a member function getKernel() on a non-object in /Users/fester/Sites/thinkblue/admintool/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.php on line 38</p>
</blockquote>
<p>Basically, in ContainerAwareCommand->getContainer() the call to</p>
<pre><code>$this->getApplication()
</code></pre>
<p>returns NULL and not an object as expected. I guess that I left some important step out, but which one? And how will I finally be able to use my settings and entities?</p> | 7,517,803 | 3 | 1 | null | 2011-09-22 09:20:12.663 UTC | 6 | 2018-01-16 22:49:14.33 UTC | 2011-09-22 11:12:54.717 UTC | null | 468,744 | null | 468,744 | null | 1 | 42 | php|console|symfony | 38,591 | <p>I think you should not retrieve the container in the constructor directly. Instead, retrieve it in the <code>configure</code> method or in the <code>execute</code> method. In my case, I get my entity manager just at the start of the <code>execute</code> method like this and everything is working fine (tested with Symfony 2.1).</p>
<pre><code>protected function execute(InputInterface $input, OutputInterface $output)
{
$entityManager = $this->getContainer()->get('doctrine')->getEntityManager();
// Code here
}
</code></pre>
<p>I think that the instantiation of the application object is not done yet when you are calling <code>getContainer</code> in your constructor which result in this error. The error comes from the <code>getContainer</code> method tyring to do:</p>
<pre><code>$this->container = $this->getApplication()->getKernel()->getContainer();
</code></pre>
<p>Since <code>getApplication</code> is not an object yet, you get the a error saying or are calling a method <code>getKernel</code> on a non-object.</p>
<p><strong>Update</strong>: In newer version of Symfony, <code>getEntityManager</code> has been deprecated (and could have been removed altogether by now). Use <code>$entityManager = $this->getContainer()->get('doctrine')->getManager();</code> instead. Thanks to <a href="https://stackoverflow.com/users/1445160/chausser">Chausser</a> for pointing it.</p>
<p><strong>Update 2</strong>: In Symfony 4, auto-wiring can be used to reduce amount of code needed.</p>
<p>Create a <code>__constructor</code> with a <code>EntityManagerInterface</code> variable. This variable will be accessible in the rest of your commands. This follows the auto-wiring Dependency Injection scheme.</p>
<pre><code>class UserCommand extends ContainerAwareCommand {
private $em;
public function __construct(?string $name = null, EntityManagerInterface $em) {
parent::__construct($name);
$this->em = $em;
}
protected function configure() {
**name, desc, help code here**
}
protected function execute(InputInterface $input, OutputInterface $output) {
$this->em->getRepository('App:Table')->findAll();
}
}
</code></pre>
<p>Credits to @profm2 for providing the comment and the code sample.</p> |
7,992,726 | How to get H1,H2,H3,... using a single xpath expression | <p>How can I get H1,H2,H3 contents in one single xpath expression?</p>
<p>I know I could do this.</p>
<pre><code>//html/body/h1/text()
//html/body/h2/text()
//html/body/h3/text()
</code></pre>
<p>and so on. </p> | 7,995,095 | 1 | 0 | null | 2011-11-03 09:38:32.757 UTC | 4 | 2011-11-04 00:52:27.487 UTC | 2011-11-03 09:44:13.133 UTC | null | 372,935 | null | 372,935 | null | 1 | 29 | xpath | 29,304 | <p><strong>Use</strong>:</p>
<pre><code>/html/body/*[self::h1 or self::h2 or self::h3]/text()
</code></pre>
<p><strong>The following expression is incorrect</strong>:</p>
<pre><code>//html/body/*[local-name() = "h1"
or local-name() = "h2"
or local-name() = "h3"]/text()
</code></pre>
<p>because it may select text nodes that are children of <code>unwanted:h1</code>, <code>different:h2</code>, <code>someWeirdNamespace:h3</code>.</p>
<p><strong>Another recommendation: Always avoid using <code>//</code></strong> when the structure of the XML document is statically known. Using <code>//</code> most often results in significant inefficiencies because it causes the complete document (sub)tree roted in the context node to be traversed.</p> |
8,134,960 | How to revert Master branch to upstream | <p>I have forked a git repository and setup upstream. I've made some changes in Master branch and committed and pushed to github.</p>
<p>Now what should I do to abandon all my changes in Master branch and make it identical to the upstream's master branch?</p> | 8,135,023 | 1 | 0 | null | 2011-11-15 10:34:48.467 UTC | 63 | 2015-02-19 17:55:30.703 UTC | 2014-08-01 18:48:04.713 UTC | null | 321,731 | null | 391,227 | null | 1 | 146 | git|github | 48,176 | <p>(I'm assuming that the changes that you now want to ignore are at your <code>origin</code> remote, you're on your <code>master</code> branch, and you want to revert to the contents of the <code>upstream</code> remote)</p>
<p>Firstly, reset your working copy to the upstream master:</p>
<pre><code>git remote update
# the double hyphen ensures that upstream/master is
# considered as a revision and not confused as a path
git reset --hard upstream/master --
</code></pre>
<p>Then push this new branch-head to your origin repository, ignoring the fact that it won't be a fast-forward:</p>
<pre><code>git push origin +master
</code></pre> |
2,023,239 | Subversion "Authorization failed" when creating repository | <p>I have previously had a repository on my computer for local use and removed it.</p>
<p>Now I am trying to set another one up. But keep getting "Authorization failed" even when entering a correct password, when I enter a wrong password it tells me so. This is exactly how I set it up the first time but now every time it fails. What am I doing wrong? It is the only repository on my computer. I have already tried a reinstall of subversion and removing the cache in my AppData folder but nothing has helped.</p>
<p>I am using this guide to set it up. <a href="https://blog.codinghorror.com/setting-up-subversion-on-windows/" rel="nofollow noreferrer">https://blog.codinghorror.com/setting-up-subversion-on-windows/</a></p>
<p>This is what I am doing</p>
<pre><code>C:\>svnadmin create "H:\SVN\Repository"
C:\>sc create svnserver binpath= "C:\Program Files (x86)\Subversion\svnserve.exe
--service -r H:\SVN\Repository" displayname= "SubVersion" depend= Tcpip start=
auto
[SC] CreateService SUCCESS
C:\>set SVN_EDITOR=c:\windows\system32\notepad.exe
C:\>net start svnserver
The SubVersion service is starting.
The SubVersion service was started successfully.
C:\>svn mkdir svn://localhost/myProject
Log message unchanged or not specified
(a)bort, (c)ontinue, (e)dit:
c
Authentication realm: <svn://localhost:3690> myProject
c
Password for 'Admin':
Authentication realm: <svn://localhost:3690> myProject
c
Username: user
Password for 'user': ********
svn: Authorization failed
C:\>
</code></pre>
<p>My svnserve.conf file</p>
<pre><code>[general]
anon-access = read
auth-access = write
password-db = passwd
authz-db = authz
realm = myProject
</code></pre>
<p>And my passwd file</p>
<pre><code>[users]
user = password
</code></pre> | 2,023,501 | 4 | 0 | null | 2010-01-07 19:59:03.637 UTC | 4 | 2018-10-21 12:49:01.627 UTC | 2018-10-21 12:49:01.627 UTC | null | 1,033,581 | null | 213,519 | null | 1 | 8 | svn|authorization | 39,073 | <p>The error message says "Authorization failed", not "Authentication failed". Which means you successfully authenticated (i.e., your username and password is ok), but the user as whom you authenticated doesn't have the rights to execute the command (i.e., you're not authorized to create the directory).</p>
<p>That either means that you're not connecting to the correct svnserve instance (you said you already have one set up and this is the second one you're trying to set up), or the svnservice doesn't use the correct svnserve.conf file, or the 'authz' file is not the correct one (maybe specify a full path to the auth files in your svnserve.conf file).</p> |
10,706,466 | How does malloc work in a multithreaded environment? | <p>Does the typical <code>malloc</code> (for x86-64 platform and Linux OS) naively lock a mutex at the beginning and release it when done, or does it lock a mutex in a more clever way at a finer level, so that lock contention is reduced? If it indeed does it the second way, how does it do it?</p> | 10,706,725 | 2 | 2 | null | 2012-05-22 16:50:08.19 UTC | 20 | 2012-05-23 15:14:38.537 UTC | 2012-05-23 15:14:38.537 UTC | null | 785,541 | null | 1,018,562 | null | 1 | 55 | c|linux|gcc|malloc|x86-64 | 21,711 | <p><code>glibc 2.15</code> operates multiple allocation <em>arenas</em>. Each arena has its own lock. When a thread needs to allocate memory, <code>malloc()</code> picks an arena, locks it, and allocates memory from it.</p>
<p>The mechanism for choosing an arena is somewhat elaborate and is aimed at reducing lock contention:</p>
<pre><code>/* arena_get() acquires an arena and locks the corresponding mutex.
First, try the one last locked successfully by this thread. (This
is the common case and handled with a macro for speed.) Then, loop
once over the circularly linked list of arenas. If no arena is
readily available, create a new one. In this latter case, `size'
is just a hint as to how much memory will be required immediately
in the new arena. */
</code></pre>
<p>With this in mind, <code>malloc()</code> basically looks like this (edited for brevity):</p>
<pre><code> mstate ar_ptr;
void *victim;
arena_lookup(ar_ptr);
arena_lock(ar_ptr, bytes);
if(!ar_ptr)
return 0;
victim = _int_malloc(ar_ptr, bytes);
if(!victim) {
/* Maybe the failure is due to running out of mmapped areas. */
if(ar_ptr != &main_arena) {
(void)mutex_unlock(&ar_ptr->mutex);
ar_ptr = &main_arena;
(void)mutex_lock(&ar_ptr->mutex);
victim = _int_malloc(ar_ptr, bytes);
(void)mutex_unlock(&ar_ptr->mutex);
} else {
/* ... or sbrk() has failed and there is still a chance to mmap() */
ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
(void)mutex_unlock(&main_arena.mutex);
if(ar_ptr) {
victim = _int_malloc(ar_ptr, bytes);
(void)mutex_unlock(&ar_ptr->mutex);
}
}
} else
(void)mutex_unlock(&ar_ptr->mutex);
return victim;
</code></pre>
<p>This allocator is called <a href="http://www.malloc.de/en/" rel="noreferrer"><code>ptmalloc</code></a>. It is based on <a href="http://g.oswego.edu/dl/html/malloc.html" rel="noreferrer">earlier work</a> by Doug Lea, and is maintained by Wolfram Gloger.</p> |
26,421,475 | Cannot find id_rsa.pub in the unix server. Can I regenerate it? Id_sra (private key) exists | <p>What I want to do is to copy key to another host.</p>
<pre><code>ssh-copy-id -i ~/.ssh/id_rsa user@host
</code></pre>
<p>I get error:</p>
<p>/usr/bin/ssh-copy-id: ERROR: failed to open ID file '[homedir].ssh/id_rsa.pub':</p>
<p>So there is no public key. So where is it? I tried to use command </p>
<pre><code>sudo find / -name id_rsa.pub
</code></pre>
<p>but it only found one which I generated experimentally in my test directory. I tried sending the experimental from the test directory, but then it keeps infinitely asking paraphrase and does not send when I keep pasting.</p>
<p>So there is something wrong.</p>
<p>I could regenerate using</p>
<pre><code>ssh-keygen -t rsa
</code></pre>
<p>but then it tries to use ~./.ssh directory</p>
<p>and wants to overwrite private id_rsa key. I am afraid this might brake something.</p>
<p>So how do I get my public key file?</p> | 26,422,114 | 2 | 1 | null | 2014-10-17 09:00:18.303 UTC | 4 | 2020-04-05 06:08:25.92 UTC | 2014-10-17 10:49:24.963 UTC | null | 1,194,854 | null | 1,194,854 | null | 1 | 9 | ssh|public-key | 42,082 | <p>RSA keys work on pairs. You can generate ssh private and public keys any number of times..it does not break anything. It simply replaces the old one with a newly generated keys. This only requires you to copy the newly generated public key id_rsa.pub to your remote machine's ~/.ssh/authorized_keys file in order for you to access secure shell using rsa keys. </p>
<p>So generate new rsa keys on your home's .ssh directory (your old keys are replaced by new ones) and copy to the remote host's .ssh directory</p>
<pre><code>cd /home/<your_username>/.ssh
ssh-keygen -t rsa
scp ~/.ssh/id_rsa.pub remote_username@host:~/.ssh/authorized_keys
</code></pre>
<p>then </p>
<pre><code>ssh remote_username@host
</code></pre>
<p>Keep passphrase empty while generating your new keys unless you want to enter passphrase every time you try to make a ssh connection. </p>
<p>NOTE: you need to append your public key to authorized_keys file in remote host's ~/.ssh directory if it already exists holding other client's public keys. </p> |
36,683,770 | How to get the value of an input field using ReactJS? | <p>I have the following React component:</p>
<pre><code>export default class MyComponent extends React.Component {
onSubmit(e) {
e.preventDefault();
var title = this.title;
console.log(title);
}
render(){
return (
...
<form className="form-horizontal">
...
<input type="text" className="form-control" ref={(c) => this.title = c} name="title" />
...
</form>
...
<button type="button" onClick={this.onSubmit} className="btn">Save</button>
...
);
}
};
</code></pre>
<p>The console is giving me <code>undefined</code> - any ideas what's wrong with this code?</p> | 54,759,362 | 18 | 8 | null | 2016-04-18 00:34:08.797 UTC | 89 | 2022-09-20 16:45:39.29 UTC | 2018-10-15 10:01:26.743 UTC | null | 608,639 | null | 3,111,255 | null | 1 | 297 | javascript|reactjs | 724,403 | <p>You should use constructor under the class MyComponent extends React.Component</p>
<pre><code>constructor(props){
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
</code></pre>
<p>Then you will get the result of title</p> |
7,474,762 | Php get how many days and hours left from a date | <p>I have a created_at date saved liked this "2011-09-23 19:10:18" And I want to get the days and hours left
until the date is reached. How do I do that? and column name in database remain days automatically update daily with remain days, please solve this</p> | 7,474,854 | 6 | 0 | null | 2011-09-19 17:19:31.513 UTC | 5 | 2021-06-22 09:28:58.327 UTC | 2018-11-19 10:21:45.493 UTC | null | 8,365,390 | null | 953,202 | null | 1 | 14 | php|date|laravel-5.7 | 48,655 | <p>PHP fragment: </p>
<pre><code><?php
//Convert to date
$datestr="2011-09-23 19:10:18";//Your date
$date=strtotime($datestr);//Converted to a PHP date (a second count)
//Calculate difference
$diff=$date-time();//time returns current time in seconds
$days=floor($diff/(60*60*24));//seconds/minute*minutes/hour*hours/day)
$hours=round(($diff-$days*60*60*24)/(60*60));
//Report
echo "$days days $hours hours remain<br />";
?>
</code></pre>
<p>Note the hour-round and no minutes/seconds consideration means it can be slightly inaccurate.</p> |
7,362,952 | Mocking a Django Queryset in order to test a function that takes a queryset | <p>I have a utility function in my Django project, it takes a queryset, gets some data from it and returns a result. I'd like to write some tests for this function. Is there anyway to 'mock' a QuerySet? I'd like to create an object that doesn't touch the database, and i can provide it with a list of values to use (i.e. some fake rows) and then it'll act just like a queryset, and will allow someone to do field lookups on it/filter/get/all etc.</p>
<p>Does anything like this exist already?</p> | 7,363,032 | 9 | 0 | null | 2011-09-09 14:10:42.497 UTC | 8 | 2019-04-09 19:03:18.463 UTC | null | null | null | null | 161,922 | null | 1 | 38 | python|django|unit-testing|django-queryset|django-testing | 26,283 | <p>Not that I know of, but why not use an actual queryset? The test framework is all set up to allow you to create sample data within your test, and the database is re-created on every test, so there doesn't seem to be any reason not to use the real thing.</p> |
7,547,567 | How to start Azure Storage Emulator from within a program | <p>I have some unit tests that use Azure Storage. When running these locally, I want them to use the Azure Storage emulator which is part of the Azure SDK v1.5. If the emulator isn't running, I want it to be started.</p>
<p>To start the emulator from the command line, I can use this:</p>
<pre><code>"C:\Program Files\Windows Azure SDK\v1.5\bin\csrun" /devstore
</code></pre>
<p>This works fine.</p>
<p>When I try to start it using this C# code, it crashes:</p>
<pre><code>using System.IO;
using System.Diagnostics;
...
ProcessStartInfo processToStart = new ProcessStartInfo()
{
FileName = Path.Combine(SDKDirectory, "csrun"),
Arguments = "/devstore"
};
Process.Start(processToStart);
</code></pre>
<p>I've tried fiddling with a number of ProcessStartInfo settings, but nothing seems to work. Is anybody else having this problem?</p>
<p>I've checked the Application Event Log and found the following two entries:</p>
<p><strong>Event ID: 1023</strong>
.NET Runtime version 2.0.50727.5446 - Fatal Execution Engine Error (000007FEF46B40D2) (80131506)</p>
<p><strong>Event ID: 1000</strong>
Faulting application name: DSService.exe, version: 6.0.6002.18312, time stamp: 0x4e5d8cf3
Faulting module name: mscorwks.dll, version: 2.0.50727.5446, time stamp: 0x4d8cdb54
Exception code: 0xc0000005
Fault offset: 0x00000000001de8d4
Faulting process id: 0x%9
Faulting application start time: 0x%10
Faulting application path: %11
Faulting module path: %12
Report Id: %13</p> | 7,611,247 | 10 | 0 | null | 2011-09-25 18:20:00.397 UTC | 9 | 2022-07-12 20:12:00.977 UTC | 2011-09-25 19:23:34.36 UTC | null | 340,568 | null | 340,568 | null | 1 | 23 | c#|azure|azure-storage | 17,496 | <p>I uninstalled all of the Windows Azure bits:</p>
<ul>
<li>WA SDK v1.5.20830.1814</li>
<li>WA Tools for Visual Studio: v1.5.40909.1602</li>
<li>WA AppFabric: v1.5.37</li>
<li>WA AppFabric: v2.0.224</li>
</ul>
<p>Then, I downloaded and installed everything using the unified installer. Everything came back except the AppFabric v2. All the version numbers are the same. Reran my tests and still having a problem.</p>
<p>And then...(this is weird)...it would work every now and then. Rebooted the machine and now it works. Have shutdown and rebooted a number of times now...and it just works. (sigh)</p>
<p>Thanks to everyone who provided feedback and/or ideas!</p>
<p>The final code is:</p>
<pre><code> static void StartAzureStorageEmulator()
{
ProcessStartInfo processStartInfo = new ProcessStartInfo()
{
FileName = Path.Combine(SDKDirectory, "csrun.exe"),
Arguments = "/devstore",
};
using (Process process = Process.Start(processStartInfo))
{
process.WaitForExit();
}
}
</code></pre> |
14,194,702 | Replace substring with sed | <p>I have a string like this :</p>
<pre><code>test:blabla
</code></pre>
<p>And with sed, I want to replace what's after the ':' with something else.</p>
<p>I can manage to replace a word, but not the one after the ':'. I searched on the internet for the answer, but I didn't found anything.</p>
<p>Any help ?</p> | 14,194,744 | 2 | 0 | null | 2013-01-07 11:10:59.027 UTC | 4 | 2013-01-07 20:05:23.243 UTC | 2013-01-07 11:18:19.873 UTC | null | 1,066,031 | null | 1,562,183 | null | 1 | 7 | shell|sed|sh | 42,936 | <p>Use: <code>sed 's/:.*/:replaceword/'</code></p>
<pre><code>$ echo test:blabla | sed 's/:.*/:replaceword/'
test:replaceword
</code></pre>
<p>Or for the situation <code>test test:blabla test</code> where you only want to replace the word following <code>:</code> use <code>sed 's/:[^ ]*/:replaceword/'</code>:</p>
<pre><code>$ echo "test test:blabla test" | sed 's/:[^ ]*/:replaceword/'
test test:replaceword test
# Use the g flag for multiple matches on a line
$ echo "test test:blabla test test:blah2" | sed 's/:[^ ]*/:replaceword/g'
test test:replaceword test test:replaceword
</code></pre> |
13,975,733 | How to create an executable command prompt script | <p>I usually perform actions in the 7zip command line program. I was thinking about creating a small script to do everything automatically, but I have never written any Windows shell script before and therefore don't even know where to begin.</p>
<p>I would like to make an executable script file which, when a user double-clicks on it, will call the 7zip command line and perform some actions.</p>
<p>First of all, is this possible? And if it is, what is the best way to do this?</p> | 13,975,835 | 2 | 0 | null | 2012-12-20 15:47:52.237 UTC | 1 | 2018-04-27 13:21:05.1 UTC | null | null | null | null | 1,301,428 | null | 1 | 10 | windows|command-line|executable | 81,946 | <p>You can create a batch script to do this.</p>
<p>It's basically command line commands that run one after another so you don't have to keep typing them in :)</p>
<p>Put the commands you would normally use for 7zip in a notepad file and save it with the extension <code>.bat</code>, then run it.</p>
<pre><code>7z blah blah params
7z more params and args
</code></pre>
<p>All your commands will be executed automatically when the previous one finishes.</p>
<p>There are other programming languages you could do this in (or even VBScript) but batch would be perfectly suited to this, and you don't need to install anything extra.</p> |
14,115,893 | Render raw HTML | <p>I want to render raw <code>.html</code> pages using Express 3 as follows:</p>
<pre><code>server.get('/', function(req, res) {
res.render('login.html');
}
</code></pre>
<p>This is how I have configured the server to render raw HTML pages (inspired from <a href="https://stackoverflow.com/questions/4529586/render-basic-html-view-in-node-js-express">this outdated question</a>):</p>
<pre><code>server
.set('view options', {layout: false})
.set('views', './../')
.engine('html', function(str, options) {
return function(locals) {
return str;
};
});
</code></pre>
<p>Unfortunately, with this configuration the page hangs and is never rendered properly. What have I done wrong? How can I render raw HTLM using Express 3 without fancy rendering engines such as Jade and EJS?</p> | 14,116,547 | 11 | 7 | null | 2013-01-02 01:22:14.077 UTC | 13 | 2018-09-04 12:22:07.03 UTC | 2017-05-23 12:02:50.75 UTC | null | -1 | null | 707,381 | null | 1 | 26 | javascript|node.js|express | 69,203 | <p>If you don't actually need to inject data into templates, the simplest solution in express is to use the static file server (<code>express.static()</code>).</p>
<p>However, if you still want to wire up the routes to the pages manually (eg your example mapping '/' to 'login.html'), you might try <code>res.sendFile()</code> to send your html docs over:</p>
<p><a href="http://expressjs.com/api.html#res.sendfile">http://expressjs.com/api.html#res.sendfile</a></p> |
13,812,136 | How do I validate a JSON Schema schema, in Python? | <p>I am programmatically generating a JSON-Schema schema. I wish to ensure that the schema is valid. Is there a schema I can validate my schema against?</p>
<p>Please note my use of schema twice in that sentence and the title. I don't want to validate data against my schema, I want to validate my schema.</p> | 13,826,826 | 1 | 0 | null | 2012-12-11 01:18:05.223 UTC | 6 | 2016-09-30 19:35:55.237 UTC | null | null | null | null | 402,605 | null | 1 | 30 | python|jsonschema | 16,935 | <p>Using <a href="http://pypi.python.org/pypi/jsonschema/0.7" rel="noreferrer">jsonschema</a>, you can validate a schema against the meta-schema. The core meta-schema is <a href="http://json-schema.org/" rel="noreferrer">here</a>, but jsonschema bundles it so downloading it is unnecessary.</p>
<pre><code>from jsonschema import Draft3Validator
my_schema = json.loads(my_text_file) #or however else you end up with a dict of the schema
Draft3Validator.check_schema(my_schema)
</code></pre> |
29,953,743 | What exactly is Visual Studio Code? | <p>Recently I've read about Microsoft Visual Studio Code. I work primarily with C and C++ languages on GNU/Linux. My question is whether Visual Studio Code is just a simple editor which uses whatever compiler exist in the platform, <code>gcc</code> in my case, as a background compiler or does it come with its own VS compiler? </p> | 29,953,859 | 9 | 6 | null | 2015-04-29 20:19:17.417 UTC | 3 | 2018-02-08 22:43:01.423 UTC | 2015-09-12 18:02:45.923 UTC | null | 64,046 | null | 2,795,296 | null | 1 | 44 | compiler-construction|visual-studio-code | 63,240 | <p>Visual Studio Code is just an editor, which features their intellisense thingy and some git and debugger integration.</p>
<p>EDIT: more info here: <a href="https://code.visualstudio.com/Docs">https://code.visualstudio.com/Docs</a></p> |
29,913,805 | Visual Studio warning about copies of files with different contents | <p>When I go to debug my C++ project in Visual Studio, up pops a little warning dialogue box that tells me:</p>
<pre><code>A copy of datum.h was found in
c:/users/brad/desktop/source/binary/datum.h, but the current
source code is different from the version built into
c:/users/brad/desktop/source/binary/datum.h.
</code></pre>
<p>I'm having trouble understanding what this is even trying to tell me, let alone how to fix it. At first I thought it might be complaining that I'd accidentally duplicated a file in the directory, which I checked, and found nothing of the sort, which leaves me pretty stumped. I also tried excluding the file from the solution and adding it again, which didn't fix the problem either.</p>
<p>The warning doesn't appear to actually hinder the development of my project, but I suppose warnings exist for a reason, so if anyone knows what's gone wrong, any advice would be greatly appreciated. To my knowledge, I didn't change anything to cause the message to appear, it just popped up one time I went to debug the solution and has kept on appearing ever since.</p>
<p>Also, more copies of the same warning have started popping up, pertaining to other header files in my solution (I haven't recieved any about .cpp files yet, but it could be a coincidence, because it's only been going on for about 20 minutes).</p> | 29,913,994 | 14 | 6 | null | 2015-04-28 08:08:13.333 UTC | 5 | 2022-04-19 16:53:03.547 UTC | null | null | null | null | 4,541,936 | null | 1 | 52 | c++|visual-studio | 20,452 | <p>Could you by any chance be debugging another executable (not the one actually built?). This is a common issue in scenarios where Visual Studio builds the binaries in one directory but then they are copied over to some other directory for debugging. I'd suggest you compare the target path under the debugging settings and the output directory under the general settings in Visual Studio.</p>
<p><img src="https://i.stack.imgur.com/zj03c.png" alt="TargetPath" /></p>
<p>This would explain the issue, since you are actually debugging some older version of the binary (not the one built currently) and thus the warning, since Visual Studio can't find the version of the source files for that version of the binary.</p> |
9,526,626 | Add an Array to a Dictionary in C# | <p>I have tried reading the other posts on this subject and can't quite figure this out. </p>
<p>I have a list in C# that I want to put in a dictionary with all of the same keys. The list is this</p>
<pre><code>string[] IN ={"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For"
,"Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"};
</code></pre>
<p>I want to create and populate a dictionary with the key being "IN" (the name of the array) and then having each string for the array in the dictionary.</p>
<p>This is what I wrote to create the dictionary (which I am not sure is correct):</p>
<pre><code>Dictionary<string, List<string>> wordDictionary = new Dictionary<string, List<string>> ()
</code></pre>
<p>But I am not sure how to populate the dictionary.</p>
<p>Any help would be greatly appreciated as this is the first time I have tried to use a dictionary and I am new to C#</p> | 9,526,653 | 5 | 1 | null | 2012-03-02 01:05:33.873 UTC | null | 2012-03-02 01:20:28.423 UTC | null | null | null | null | 1,244,051 | null | 1 | 8 | c#|arrays|dictionary | 49,245 | <p>An array is <code>string[]</code>, not <code>List<string></code>, so just do this:</p>
<pre><code>Dictionary<string, string[]> wordDictionary = new Dictionary<string, string[]>();
</code></pre>
<p>Now you can add your array as usual.</p>
<pre><code>wordDictionary.Add("IN", IN);
</code></pre>
<p>Or:</p>
<pre><code>wordDictionary.Add("IN", new string[] {"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For","Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"});
</code></pre> |
9,573,178 | D3 force directed layout with bounding box | <p>I am new to D3 and having trouble setting the bounds for my force directed layout. I have managed to piece together (from examples) what I would like, but I need the graph to be contained. In the tick function, a transform/translate will display my graph correctly, but when i use cx and cy with Math.max/min (See commented code), the nodes are pinned to the
top left corner while the lines are contained properly.</p>
<p>Here is what I have below... what am I doing wrong??</p>
<pre><code>var w=960, h=500, r=8, z = d3.scale.category20();
var color = d3.scale.category20();
var force = d3.layout.force()
.linkDistance( function(d) { return (d.value*180) } )
.linkStrength( function(d) { return (1/(1+d.value)) } )
.charge(-1000)
//.gravity(.08)
.size([w, h]);
var vis = d3.select("#chart").append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(" + w / 4 + "," + h / 3 + ")");
vis.append("svg:rect")
.attr("width", w)
.attr("height", h)
.style("stroke", "#000");
d3.json("miserables.json", function(json) {
var link = vis.selectAll("line.link")
.data(json.links);
link.enter().append("svg:line")
.attr("class", "link")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.source.x; })
.attr("y2", function(d) { return d.source.y; })
.style("stroke-width", function(d) { return (1/(1+d.value))*5 });
var node = vis.selectAll("g.node")
.data(json.nodes);
var nodeEnter = node.enter().append("svg:g")
.attr("class", "node")
.on("mouseover", fade(.1))
.on("mouseout", fade(1))
.call(force.drag);
nodeEnter.append("svg:circle")
.attr("r", r)
.style("fill", function(d) { return z(d.group); })
.style("stroke", function(d) { return
d3.rgb(z(d.group)).darker(); });
nodeEnter.append("svg:text")
.attr("text-anchor", "middle")
.attr("dy", ".35em")
.text(function(d) { return d.name; });
force
.nodes(json.nodes)
.links(json.links)
.on("tick", tick)
.start();
function tick() {
// This works
node.attr("transform", function(d) { return "translate(" + d.x + ","
+ d.y + ")"; });
// This contains the lines within the boundary, but the nodes are
stuck in the top left corner
//node.attr("cx", function(d) { return d.x = Math.max(r, Math.min(w
- r, d.x)); })
// .attr("cy", function(d) { return d.y = Math.max(r, Math.min(h -
r, d.y)); });
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
}
var linkedByIndex = {};
json.links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] ||
linkedByIndex[b.index + "," + a.index] || a.index == b.index;
}
function fade(opacity) {
return function(d) {
node.style("stroke-opacity", function(o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
this.setAttribute('fill-opacity', thisOpacity);
return thisOpacity;
});
link.style("stroke-opacity", opacity).style("stroke-opacity",
function(o) {
return o.source === d || o.target === d ? 1 : opacity;
});
};
}
});
</code></pre> | 9,577,224 | 3 | 1 | null | 2012-03-05 20:04:31.473 UTC | 18 | 2022-02-12 23:56:16.843 UTC | 2014-01-25 21:23:59.913 UTC | null | 3,052,751 | null | 1,250,682 | null | 1 | 37 | d3.js|force-layout | 32,098 | <p>There's a <a href="https://mbostock.github.io/d3/talk/20110921/bounding.html" rel="nofollow noreferrer">bounding box example</a> in my <a href="https://vimeo.com/29458354" rel="nofollow noreferrer">talk on force layouts</a>. The position Verlet integration allows you to define geometric constraints (such as bounding boxes and <a href="https://mbostock.github.io/d3/talk/20110921/collision.html" rel="nofollow noreferrer">collision detection</a>) inside the "tick" event listener; simply move the nodes to comply with the constraint and the simulation will adapt accordingly.</p>
<p>That said, gravity is definitely a more flexible way to deal with this problem, since it allows users to drag the graph outside the bounding box temporarily and then the graph will recover. Depend on the size of the graph and the size of the displayed area, you should experiment with different relative strengths of gravity and charge (repulsion) to get your graph to fit.</p> |
32,943,526 | Asp.Net 5 MVC 6 detect mobile browser | <p>How is it possible in <strong>Asp.Net 5 MVC 6</strong> to detect if the user is on a mobile device?</p>
<p>In previous version of <code>Asp MVC</code> it could be done like this:</p>
<pre><code>Request.Browser.IsMobileDevice
</code></pre>
<p>The problem is that the namespace <code>System.Web</code> is not used by <code>Asp.Net 5</code>. </p>
<p>The <code>Request</code> variable in the controller actions is now of type <code>Microsoft.AspNet.Http.HttpRequest</code>, the old version was of type <a href="https://msdn.microsoft.com/en-us/library/system.web.httprequestbase%28v=vs.110%29.aspx"><code>System.Web.HttpRequestBase</code></a>. </p>
<p><code>Microsoft.AspNet.Http.HttpRequest</code> does not contain the <code>Browser</code> property. I tried looking through other properties, but didn't find anything. </p>
<p><strong>EDIT:</strong> as requested some resources that prove that <code>Asp.Net 5</code> does not use <code>System.Web</code> anymore.
From the <a href="http://docs.asp.net/en/latest/conceptual-overview/aspnet.html">Asp.Net documentation</a></p>
<blockquote>
<p>ASP.NET 5 is no longer based on System.Web.dll, but is instead based
on a set of granular and well factored NuGet packages allowing you to
optimize your app to have just what you need.</p>
</blockquote> | 32,947,785 | 1 | 5 | null | 2015-10-05 07:43:50.19 UTC | 11 | 2016-12-27 19:39:23.27 UTC | 2016-12-27 19:39:23.27 UTC | null | 6,541,157 | null | 3,107,430 | null | 1 | 49 | c#|asp.net-core|asp.net-core-mvc | 32,337 | <p>The <a href="https://stackoverflow.com/questions/1829089/how-does-ismobiledevice-work">implementation</a> of <code>Request.Browser.IsMobileDevice</code> relied on the <strong>.browser files</strong>, which AFAIK are not part of ASP.Net 5. </p>
<blockquote>
<p>Let's see if someone from the team can shed some light on how they plan to implement this. There is an entry in <a href="http://docs.asp.net/en/latest/mobile/index.html" rel="noreferrer">the asp docs</a> about mobile specific views, so they must have some plans for it.</p>
</blockquote>
<p>In the meantime I guess you can create your own helper method parsing the query string, for example using the regex from <a href="http://detectmobilebrowsers.com/" rel="noreferrer">detectmobilebrowsers.com</a>. For an alternative (and less extensive) regex see <a href="https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser">detecting a mobile browser</a> in SO.</p>
<p>Following this idea, a temporal solution like this extension method might help while the asp team provides their solution:</p>
<pre><code>public static class RequestExtensions
{
//regex from http://detectmobilebrowsers.com/
private static readonly Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
private static readonly Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
public static bool IsMobileBrowser(this HttpRequest request)
{
var userAgent = request.UserAgent();
if ((b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
{
return true;
}
return false;
}
public static string UserAgent(this HttpRequest request)
{
return request.Headers["User-Agent"];
}
}
</code></pre> |
19,729,710 | Parsing nested JSON data | <p>This JSON output is from a MongoDB aggregate query. I essentially need to parse the nested data JSON down to the following to the '<code>total'</code> and <code>'_id'</code> values.</p>
<pre><code>{
'ok': 1.0,
'result': [
{
'total': 142250.0,
'_id': 'BC'
},
{
'total': 210.88999999999996,
'_id': 'USD'
},
{
'total': 1065600.0,
'_id': 'TK'
}
]
}
</code></pre>
<p>I've tried 5 different techniques to get what I need from it, however I've run into issues using the <code>json</code> and <code>simplejson</code> modules.</p>
<p>Ideally, the output will be something like this:</p>
<pre class="lang-none prettyprint-override"><code>142250.0, BC
210.88999999999996, USD
1065600.0, TK
</code></pre> | 19,729,976 | 5 | 2 | null | 2013-11-01 15:20:36.3 UTC | 3 | 2022-02-14 18:20:42.75 UTC | 2017-11-12 15:31:34.74 UTC | null | 355,230 | null | 2,917,381 | null | 1 | 9 | python|json | 87,420 | <p>NOTE: Your JSON response from MongoDB is not actually valid. JSON requires double-quotes (<code>"</code>), not single-quotes (<code>'</code>).</p>
<p>I'm not sure why your response has single-quotes instead of double-quotes but from the looks of it you can replace them and then just use the built-in <code>json</code> module:</p>
<pre><code>from __future__ import print_function
import json
response = """{
'ok': 1.0,
'result': [
{
'total': 142250.0,
'_id': 'BC'
},
{
'total': 210.88999999999996,
'_id': 'USD'
},
{
'total': 1065600.0,
'_id': 'TK'
}
]
}"""
# JSON requires double-quotes, not single-quotes.
response = response.replace("'", '"')
response = json.loads(response)
for doc in response['result']:
print(doc['_id'], doc['total'])
</code></pre> |
332,703 | NHibernate Eager Fetching Over Multiple Levels | <p>I have a 3-leveled hierarchy of entities: Customer-Order-Line, which I would like to retrieve in entirety for a given customer, using ISession.Get(id). I have the following XML fragments:</p>
<p>customer.hbm.xml:</p>
<pre><code><bag name="Orders" cascade="all-delete-orphan" inverse="false" fetch="join">
<key column="CustomerID" />
<one-to-many class="Order" />
</bag>
</code></pre>
<p>order.hbm.xml:</p>
<pre><code><bag name="Lines" cascade="all-delete-orphan" inverse="false" fetch="join">
<key column="OrderID" />
<one-to-many class="Line" />
</bag>
</code></pre>
<p>I have used the fetch="join" attribute to indicate that I want to fetch the child entities for each parent, and this has constructed the correct SQL:</p>
<pre><code>SELECT
customer0_.ID AS ID8_2_,
customer0_.Name AS Name8_2_,
orders1_.CustomerID AS CustomerID__4_,
orders1_.ID AS ID4_,
orders1_.ID AS ID9_0_,
orders1_.PostalAddress AS PostalAd2_9_0_,
orders1_.OrderDate AS OrderDate9_0_,
lines2_.OrderID AS OrderID__5_,
lines2_.ID AS ID5_,
lines2_.ID AS ID10_1_,
lines2_.[LineNo] AS column2_10_1_,
lines2_.Quantity AS Quantity10_1_,
lines2_.ProductID AS ProductID10_1_
FROM Customer customer0_
LEFT JOIN [Order] orders1_
ON customer0_.ID=orders1_.CustomerID
LEFT JOIN Line lines2_
ON orders1_.ID=lines2_.OrderID
WHERE customer0_.ID=1
</code></pre>
<p>So far, this looks good - SQL returns the correct set of records (with only one distinct orderid), but when I run a test to confirm the correct number of entities (from NH) for Orders and Lines, I get the wrong results</p>
<p>I <em>should</em> be getting (from my test data), 1xOrder and 4xLine, however, I am getting 4xOrder and 4xLine. It appears that NH is not recognising the 'repeating' group of Order information in the result set, nor correctly 'reusing' the Order entity.</p>
<p>I am using all integer IDs (PKs), and I've tried implementing IComparable of T and IEquatable of T using this ID, in the hope that NH will see the equality of these entities. I've also tried overridding Equals and GetHashCode to use the ID. Neither of these 'attempts' have succeeded.</p>
<p>Is "multiple leveled fetch" a supported operation for NH, and if so, is there an XML setting required (or some other mechanism) to support it?</p>
<hr>
<p>NB: I used sirocco's solution with a few changes to my own code to finally solve this one. the xml needs to be changed from bag to set, for all collections, and the entitities themselves were changed to implement IComparable<>, which is a requirement of a set for uniqueness to be established.</p>
<pre><code>public class BaseEntity : IComparable<BaseEntity>
{
...
private Guid _internalID { get; set; }
public virtual Guid ID { get; set; }
public BaseEntity()
{
_internalID = Guid.NewGuid();
}
#region IComparable<BaseEntity> Members
public int CompareTo( BaseEntity other )
{
if ( ID == Guid.Empty || other.ID == Guid.Empty )
return _internalID.CompareTo( other._internalID );
return ID.CompareTo( other.ID );
}
#endregion
...
}
</code></pre>
<p>Note the use of an InternalID field. This is required for new (transient) entities, other wise they won't have an ID initially (my model has them supplied when saved).</p> | 368,259 | 5 | 1 | null | 2008-12-02 00:44:08.73 UTC | 16 | 2011-11-24 23:54:21.247 UTC | 2009-01-07 22:03:00.113 UTC | Ben Laan | 2,918 | Ben Laan | 2,918 | null | 1 | 19 | nhibernate|fetching-strategy | 16,621 | <p>You're getting 4XOrder and 4XLines because the join with lines doubles the results . You can set a Transformer on the ICriteria like :</p>
<pre><code>.SetResultTransformer(new DistinctRootEntityResultTransformer())
</code></pre> |
985,893 | what are sparse voxel octrees? | <p>I have reading a lot about the potential use of sparse voxel octrees in future graphics engines.</p>
<p>However I have been unable to find technical information on them.</p>
<p>I understand what a voxel is, however I dont know what sparse voxel octrees are or how are they any more efficient than the polygonal techniques in use now.</p>
<p>Could somebody explain or point me to an explanation for this?</p> | 12,256,141 | 5 | 0 | null | 2009-06-12 09:48:44.907 UTC | 17 | 2019-10-13 02:04:47.847 UTC | null | null | null | null | 14,316 | null | 1 | 32 | graphics|voxels | 34,018 | <p>A NVIDIA whitepaper named <strong>Efficient Sparse Voxel Octrees – Analysis, Extensions, and Implementation</strong>
describes it very detailed <a href="https://www.nvidia.com/docs/IO/88972/nvr-2010-001.pdf" rel="nofollow noreferrer">here</a></p> |
727,507 | How can I convert Unicode to uppercase to print it? | <p>I have this:</p>
<pre><code>>>> print 'example'
example
>>> print 'exámple'
exámple
>>> print 'exámple'.upper()
EXáMPLE
</code></pre>
<p>What I need to do to print:</p>
<pre><code>EXÁMPLE
</code></pre>
<p><em>(Where the 'a' gets its accute accent, but in uppercase.)</em></p>
<p>I'm using Python 2.6.</p> | 727,517 | 5 | 0 | null | 2009-04-07 20:41:46.517 UTC | 3 | 2018-03-31 08:09:03.563 UTC | 2015-11-11 04:35:20.397 UTC | Roger Pate | 202,229 | null | 18,300 | null | 1 | 38 | python|unicode|python-2.x|case-sensitive|uppercase | 34,385 | <p>I think it's as simple as <strong>not</strong> converting to ASCII first.</p>
<pre><code> >>> print u'exámple'.upper()
EXÁMPLE
</code></pre> |
1,115,563 | What is zip (functional programming?) | <p>I recently saw some Clojure or Scala (sorry I'm not familiar with them) and they did zip on a list or something like that. What is zip and where did it come from ?</p> | 1,115,570 | 5 | 0 | null | 2009-07-12 08:28:34.417 UTC | 13 | 2017-10-11 07:45:08.787 UTC | 2016-07-22 21:45:20.16 UTC | null | 7,671 | null | 15,124 | null | 1 | 50 | clojure|functional-programming|zip | 27,027 | <p>Zip is when you take two input sequences, and produce an output sequence in which every two elements from input sequences at the same position are combined using some function. An example in Haskell:</p>
<p>Input:</p>
<pre><code>zipWith (+) [1, 2, 3] [4, 5, 6]
</code></pre>
<p>Output:</p>
<pre><code>[5, 7, 9]
</code></pre>
<p>The above is a more generic definition; sometimes, <code>zip</code> specifically refers to combining elements as tuples. E.g. in Haskell again:</p>
<p>Input:</p>
<pre><code>zip [1, 2, 3] [4, 5, 6]
</code></pre>
<p>Output:</p>
<pre><code>[(1, 4), (2, 5), (3, 6)]
</code></pre>
<p>And the more generic version is called "zip with". You may consider "zip" as a special case of "zipWith":</p>
<pre><code>zip xs ys = zipWith (\x y -> (xs, ys)) xs ys
</code></pre> |
841,339 | Having trouble adding a linked SQL server | <p>I'm trying to pull in data from a remote SQL Server. I can access the remote server using SQL authentication; I haven't had any luck using the same credentials with sp_addlinkedserver.</p>
<p>I'm trying something like this:</p>
<pre><code>Exec sp_dropserver 'Remote', 'droplogins'
go
EXEC sp_addlinkedserver
@server='Remote',
@srvproduct='',
@provider='SQLNCLI',
@datasrc='0.0.0.0'
EXEC sp_addlinkedsrvlogin
@useself='FALSE',
@rmtsrvname='Remote',
@rmtuser='User',
@rmtpassword='Secret'
Select Top 10 * from Remote.DatabaseName.dbo.TableName
</code></pre>
<p>Here's what I get:</p>
<pre>
OLE DB provider "SQLNCLI" for linked server "Remote" returned message
"Login timeout expired".
OLE DB provider "SQLNCLI" for linked server "Remote" returned message
"An error has occurred while establishing a connection to the server.
When connecting to SQL Server 2005, this failure may be caused by the
fact that under the default settings SQL Server does not allow remote
connections.".
Msg 53, Level 16, State 1, Line 0
Named Pipes Provider: Could not open a connection to SQL Server [53].
</pre>
<p>Again, I can access the server directly (in SQL Management Studio) using these exact credentials, so it's not a problem with my network or credentials.</p>
<p>Most of the examples I've seen online seem to involve Windows domain accounts, as opposed to SQL security logins. Does this not work with SQL authentication?</p> | 841,454 | 6 | 0 | null | 2009-05-08 19:08:31.953 UTC | 1 | 2010-08-11 15:16:39.32 UTC | 2009-05-09 19:13:58.23 UTC | null | 239,663 | null | 239,663 | null | 1 | 9 | sql-server|linked-server | 46,345 | <p>It does work with sql authentication. In fact its easier, as you don't have to set up Kerberos if you use SQL authentication.</p>
<p>One thing is confusing about your error messages, your address is an IP address : 123.45.678.90</p>
<p>your error message is talking about Named Pipes. Could this be a clue?</p>
<p>You don't have to reference the server in TSQL by it's IP address. If you add an <a href="http://support.microsoft.com/kb/265808" rel="noreferrer">alias on the local server</a>, pointing to the remote server, you can give a more sensible name. Refering to it by IP address is obviously unsatisfactory.</p> |
1,070,526 | How to return anonymous type from c# method that uses LINQ to SQL | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/534690/linq-to-sql-return-anonymous-type">LINQ to SQL: Return anonymous type?</a> </p>
</blockquote>
<p>I have a standard LINQ to SQL query, which returns the data as an anonymous type (containing about 6 columns of data of various datatypes).</p>
<p>I would like to make this returned object available to other parts of the program, either by returning it to the method-caller, or by assigning it to a property of the object containing the method.</p>
<p>How can I do this given that it is an anonymous type ("var")?</p>
<p>EDIT - Here is the code:</p>
<pre><code> using (ormDataContext context = new ormDataContext(connStr))
{
var electionInfo = from t1 in context.elections
join t2 in context.election_status
on t1.statusID equals t2.statusID
select new { t1, t2 };
}
</code></pre> | 1,070,557 | 6 | 3 | null | 2009-07-01 18:03:52.577 UTC | 15 | 2009-07-01 19:30:17.163 UTC | 2017-05-23 11:54:10.703 UTC | null | -1 | null | 61,639 | null | 1 | 44 | c#|linq|linq-to-sql|anonymous-types | 79,700 | <p>Make the anonymous type into a class...</p>
<pre><code>public class Person
{
public Person() {
}
public String Name { get; set; }
public DateTime DOB { get; set; }
}
Person p =
from person in db.People
where person.Id = 1
select new Person {
Name = person.Name,
DOB = person.DateOfBirth
}
</code></pre> |
605,124 | Fixed point math in C# | <p>Are there some good resources for fixed point math in C#?</p>
<p>I've seen things like this (<a href="http://2ddev.72dpiarmy.com/viewtopic.php?id=156" rel="nofollow noreferrer">http://2ddev.72dpiarmy.com/viewtopic.php?id=156</a>) and this (<em><a href="https://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math">What's the best way to do fixed-point math?</a></em>), and a number of discussions about whether decimal is really fixed point or actually floating point (update: responders have confirmed that it's definitely floating point), but I haven't seen a solid C# library for things like calculating cosine and sine.</p>
<p>My needs are simple -- I need the basic operators, plus cosine, sine, arctan2, <a href="https://en.wikipedia.org/wiki/Pi" rel="nofollow noreferrer">π</a>, etc. I think that's about it. Maybe sqrt. I'm programming a two-dimensional <a href="https://en.wikipedia.org/wiki/Real-time_strategy" rel="nofollow noreferrer">RTS</a> game, which I have largely working, but the unit movement when using floating-point math (doubles) has very small inaccuracies over time (10-30 minutes) across multiple machines, leading to desyncs. This is presently only between a 32-bit OS and a 64-bit OS. All the 32-bit machines seem to stay in sync without issue, which is what makes me think this is a floating point issue.</p>
<p>I was aware from this as a possible issue from the outset, and so have limited my use of non-integer position math as much as possible, but for smooth diagonal movement at varying speeds I'm calculating the angle between points in radians, then getting the x and y components of movement with sin and cos. That's the main issue. I'm also doing some calculations for line segment intersections, line-circle intersections, circle-rect intersections, etc, that also probably need to move from floating-point to fixed-point to avoid cross-machine issues.</p>
<p>If there's something open source in Java or <a href="https://en.wikipedia.org/wiki/Visual_Basic" rel="nofollow noreferrer">Visual Basic</a> or another comparable language, I could probably convert the code for my uses. The main priority for me is accuracy, although I'd like as little speed loss over present performance as possible. This whole fixed point math thing is very new to me, and I'm surprised by how little practical information on it there is on Google -- most stuff seems to be either theory or dense C++ header files.</p>
<p>Anything you could do to point me in the right direction is much appreciated; if I can get this working, I plan to open-source the math functions I put together so that there will be a resource for other C# programmers out there.</p>
<p>I could definitely make a cosine/sine lookup table work for my purposes, but I don't think that would work for arctan2, since I'd need to generate a table with about 64,000x64,000 entries (yikes). If you know any programmatic explanations of efficient ways to calculate things like arctan2, that would be awesome. My math background is all right, but the advanced formulas and traditional math notation are very difficult for me to translate into code.</p> | 616,015 | 6 | 14 | null | 2009-03-03 04:33:01.197 UTC | 59 | 2022-06-03 14:15:11.467 UTC | 2022-06-03 14:15:11.467 UTC | x4000 | 63,550 | null | 73,066 | null | 1 | 56 | c#|math|fixed-point | 39,419 | <p>Ok, here's what I've come up with for a fixed-point struct, based on the link in my original question but also including some fixes to how it was handling division and multiplication, and added logic for modules, comparisons, shifts, etc:</p>
<pre><code>public struct FInt
{
public long RawValue;
public const int SHIFT_AMOUNT = 12; //12 is 4096
public const long One = 1 << SHIFT_AMOUNT;
public const int OneI = 1 << SHIFT_AMOUNT;
public static FInt OneF = FInt.Create( 1, true );
#region Constructors
public static FInt Create( long StartingRawValue, bool UseMultiple )
{
FInt fInt;
fInt.RawValue = StartingRawValue;
if ( UseMultiple )
fInt.RawValue = fInt.RawValue << SHIFT_AMOUNT;
return fInt;
}
public static FInt Create( double DoubleValue )
{
FInt fInt;
DoubleValue *= (double)One;
fInt.RawValue = (int)Math.Round( DoubleValue );
return fInt;
}
#endregion
public int IntValue
{
get { return (int)( this.RawValue >> SHIFT_AMOUNT ); }
}
public int ToInt()
{
return (int)( this.RawValue >> SHIFT_AMOUNT );
}
public double ToDouble()
{
return (double)this.RawValue / (double)One;
}
public FInt Inverse
{
get { return FInt.Create( -this.RawValue, false ); }
}
#region FromParts
/// <summary>
/// Create a fixed-int number from parts. For example, to create 1.5 pass in 1 and 500.
/// </summary>
/// <param name="PreDecimal">The number above the decimal. For 1.5, this would be 1.</param>
/// <param name="PostDecimal">The number below the decimal, to three digits.
/// For 1.5, this would be 500. For 1.005, this would be 5.</param>
/// <returns>A fixed-int representation of the number parts</returns>
public static FInt FromParts( int PreDecimal, int PostDecimal )
{
FInt f = FInt.Create( PreDecimal, true );
if ( PostDecimal != 0 )
f.RawValue += ( FInt.Create( PostDecimal ) / 1000 ).RawValue;
return f;
}
#endregion
#region *
public static FInt operator *( FInt one, FInt other )
{
FInt fInt;
fInt.RawValue = ( one.RawValue * other.RawValue ) >> SHIFT_AMOUNT;
return fInt;
}
public static FInt operator *( FInt one, int multi )
{
return one * (FInt)multi;
}
public static FInt operator *( int multi, FInt one )
{
return one * (FInt)multi;
}
#endregion
#region /
public static FInt operator /( FInt one, FInt other )
{
FInt fInt;
fInt.RawValue = ( one.RawValue << SHIFT_AMOUNT ) / ( other.RawValue );
return fInt;
}
public static FInt operator /( FInt one, int divisor )
{
return one / (FInt)divisor;
}
public static FInt operator /( int divisor, FInt one )
{
return (FInt)divisor / one;
}
#endregion
#region %
public static FInt operator %( FInt one, FInt other )
{
FInt fInt;
fInt.RawValue = ( one.RawValue ) % ( other.RawValue );
return fInt;
}
public static FInt operator %( FInt one, int divisor )
{
return one % (FInt)divisor;
}
public static FInt operator %( int divisor, FInt one )
{
return (FInt)divisor % one;
}
#endregion
#region +
public static FInt operator +( FInt one, FInt other )
{
FInt fInt;
fInt.RawValue = one.RawValue + other.RawValue;
return fInt;
}
public static FInt operator +( FInt one, int other )
{
return one + (FInt)other;
}
public static FInt operator +( int other, FInt one )
{
return one + (FInt)other;
}
#endregion
#region -
public static FInt operator -( FInt one, FInt other )
{
FInt fInt;
fInt.RawValue = one.RawValue - other.RawValue;
return fInt;
}
public static FInt operator -( FInt one, int other )
{
return one - (FInt)other;
}
public static FInt operator -( int other, FInt one )
{
return (FInt)other - one;
}
#endregion
#region ==
public static bool operator ==( FInt one, FInt other )
{
return one.RawValue == other.RawValue;
}
public static bool operator ==( FInt one, int other )
{
return one == (FInt)other;
}
public static bool operator ==( int other, FInt one )
{
return (FInt)other == one;
}
#endregion
#region !=
public static bool operator !=( FInt one, FInt other )
{
return one.RawValue != other.RawValue;
}
public static bool operator !=( FInt one, int other )
{
return one != (FInt)other;
}
public static bool operator !=( int other, FInt one )
{
return (FInt)other != one;
}
#endregion
#region >=
public static bool operator >=( FInt one, FInt other )
{
return one.RawValue >= other.RawValue;
}
public static bool operator >=( FInt one, int other )
{
return one >= (FInt)other;
}
public static bool operator >=( int other, FInt one )
{
return (FInt)other >= one;
}
#endregion
#region <=
public static bool operator <=( FInt one, FInt other )
{
return one.RawValue <= other.RawValue;
}
public static bool operator <=( FInt one, int other )
{
return one <= (FInt)other;
}
public static bool operator <=( int other, FInt one )
{
return (FInt)other <= one;
}
#endregion
#region >
public static bool operator >( FInt one, FInt other )
{
return one.RawValue > other.RawValue;
}
public static bool operator >( FInt one, int other )
{
return one > (FInt)other;
}
public static bool operator >( int other, FInt one )
{
return (FInt)other > one;
}
#endregion
#region <
public static bool operator <( FInt one, FInt other )
{
return one.RawValue < other.RawValue;
}
public static bool operator <( FInt one, int other )
{
return one < (FInt)other;
}
public static bool operator <( int other, FInt one )
{
return (FInt)other < one;
}
#endregion
public static explicit operator int( FInt src )
{
return (int)( src.RawValue >> SHIFT_AMOUNT );
}
public static explicit operator FInt( int src )
{
return FInt.Create( src, true );
}
public static explicit operator FInt( long src )
{
return FInt.Create( src, true );
}
public static explicit operator FInt( ulong src )
{
return FInt.Create( (long)src, true );
}
public static FInt operator <<( FInt one, int Amount )
{
return FInt.Create( one.RawValue << Amount, false );
}
public static FInt operator >>( FInt one, int Amount )
{
return FInt.Create( one.RawValue >> Amount, false );
}
public override bool Equals( object obj )
{
if ( obj is FInt )
return ( (FInt)obj ).RawValue == this.RawValue;
else
return false;
}
public override int GetHashCode()
{
return RawValue.GetHashCode();
}
public override string ToString()
{
return this.RawValue.ToString();
}
}
public struct FPoint
{
public FInt X;
public FInt Y;
public static FPoint Create( FInt X, FInt Y )
{
FPoint fp;
fp.X = X;
fp.Y = Y;
return fp;
}
public static FPoint FromPoint( Point p )
{
FPoint f;
f.X = (FInt)p.X;
f.Y = (FInt)p.Y;
return f;
}
public static Point ToPoint( FPoint f )
{
return new Point( f.X.IntValue, f.Y.IntValue );
}
#region Vector Operations
public static FPoint VectorAdd( FPoint F1, FPoint F2 )
{
FPoint result;
result.X = F1.X + F2.X;
result.Y = F1.Y + F2.Y;
return result;
}
public static FPoint VectorSubtract( FPoint F1, FPoint F2 )
{
FPoint result;
result.X = F1.X - F2.X;
result.Y = F1.Y - F2.Y;
return result;
}
public static FPoint VectorDivide( FPoint F1, int Divisor )
{
FPoint result;
result.X = F1.X / Divisor;
result.Y = F1.Y / Divisor;
return result;
}
#endregion
}
</code></pre>
<p>Based on the comments from ShuggyCoUk, I see that this is in <a href="https://en.wikipedia.org/wiki/Q_%28number_format%29#Texas_Instruments_version" rel="nofollow noreferrer">Q12</a> format. That's reasonably precise for my purposes. Of course, aside from the bugfixes, I already had this basic format before I asked my question. What I was looking for were ways to calculate Sqrt, Atan2, Sin, and Cos in C# using a structure like this. There aren't any other things that I know of in C# that will handle this, but in Java I managed to find the <a href="http://home.comcast.net/%7Eohommes/MathFP/" rel="nofollow noreferrer">MathFP</a> library by Onno Hommes. It's a liberal source software license, so I've converted some of his functions to my purposes in C# (with a fix to atan2, I think). Enjoy:</p>
<pre><code> #region PI, DoublePI
public static FInt PI = FInt.Create( 12868, false ); //PI x 2^12
public static FInt TwoPIF = PI * 2; //radian equivalent of 260 degrees
public static FInt PIOver180F = PI / (FInt)180; //PI / 180
#endregion
#region Sqrt
public static FInt Sqrt( FInt f, int NumberOfIterations )
{
if ( f.RawValue < 0 ) //NaN in Math.Sqrt
throw new ArithmeticException( "Input Error" );
if ( f.RawValue == 0 )
return (FInt)0;
FInt k = f + FInt.OneF >> 1;
for ( int i = 0; i < NumberOfIterations; i++ )
k = ( k + ( f / k ) ) >> 1;
if ( k.RawValue < 0 )
throw new ArithmeticException( "Overflow" );
else
return k;
}
public static FInt Sqrt( FInt f )
{
byte numberOfIterations = 8;
if ( f.RawValue > 0x64000 )
numberOfIterations = 12;
if ( f.RawValue > 0x3e8000 )
numberOfIterations = 16;
return Sqrt( f, numberOfIterations );
}
#endregion
#region Sin
public static FInt Sin( FInt i )
{
FInt j = (FInt)0;
for ( ; i < 0; i += FInt.Create( 25736, false ) ) ;
if ( i > FInt.Create( 25736, false ) )
i %= FInt.Create( 25736, false );
FInt k = ( i * FInt.Create( 10, false ) ) / FInt.Create( 714, false );
if ( i != 0 && i != FInt.Create( 6434, false ) && i != FInt.Create( 12868, false ) &&
i != FInt.Create( 19302, false ) && i != FInt.Create( 25736, false ) )
j = ( i * FInt.Create( 100, false ) ) / FInt.Create( 714, false ) - k * FInt.Create( 10, false );
if ( k <= FInt.Create( 90, false ) )
return sin_lookup( k, j );
if ( k <= FInt.Create( 180, false ) )
return sin_lookup( FInt.Create( 180, false ) - k, j );
if ( k <= FInt.Create( 270, false ) )
return sin_lookup( k - FInt.Create( 180, false ), j ).Inverse;
else
return sin_lookup( FInt.Create( 360, false ) - k, j ).Inverse;
}
private static FInt sin_lookup( FInt i, FInt j )
{
if ( j > 0 && j < FInt.Create( 10, false ) && i < FInt.Create( 90, false ) )
return FInt.Create( SIN_TABLE[i.RawValue], false ) +
( ( FInt.Create( SIN_TABLE[i.RawValue + 1], false ) - FInt.Create( SIN_TABLE[i.RawValue], false ) ) /
FInt.Create( 10, false ) ) * j;
else
return FInt.Create( SIN_TABLE[i.RawValue], false );
}
private static int[] SIN_TABLE = {
0, 71, 142, 214, 285, 357, 428, 499, 570, 641,
711, 781, 851, 921, 990, 1060, 1128, 1197, 1265, 1333,
1400, 1468, 1534, 1600, 1665, 1730, 1795, 1859, 1922, 1985,
2048, 2109, 2170, 2230, 2290, 2349, 2407, 2464, 2521, 2577,
2632, 2686, 2740, 2793, 2845, 2896, 2946, 2995, 3043, 3091,
3137, 3183, 3227, 3271, 3313, 3355, 3395, 3434, 3473, 3510,
3547, 3582, 3616, 3649, 3681, 3712, 3741, 3770, 3797, 3823,
3849, 3872, 3895, 3917, 3937, 3956, 3974, 3991, 4006, 4020,
4033, 4045, 4056, 4065, 4073, 4080, 4086, 4090, 4093, 4095,
4096
};
#endregion
private static FInt mul( FInt F1, FInt F2 )
{
return F1 * F2;
}
#region Cos, Tan, Asin
public static FInt Cos( FInt i )
{
return Sin( i + FInt.Create( 6435, false ) );
}
public static FInt Tan( FInt i )
{
return Sin( i ) / Cos( i );
}
public static FInt Asin( FInt F )
{
bool isNegative = F < 0;
F = Abs( F );
if ( F > FInt.OneF )
throw new ArithmeticException( "Bad Asin Input:" + F.ToDouble() );
FInt f1 = mul( mul( mul( mul( FInt.Create( 145103 >> FInt.SHIFT_AMOUNT, false ), F ) -
FInt.Create( 599880 >> FInt.SHIFT_AMOUNT, false ), F ) +
FInt.Create( 1420468 >> FInt.SHIFT_AMOUNT, false ), F ) -
FInt.Create( 3592413 >> FInt.SHIFT_AMOUNT, false ), F ) +
FInt.Create( 26353447 >> FInt.SHIFT_AMOUNT, false );
FInt f2 = PI / FInt.Create( 2, true ) - ( Sqrt( FInt.OneF - F ) * f1 );
return isNegative ? f2.Inverse : f2;
}
#endregion
#region ATan, ATan2
public static FInt Atan( FInt F )
{
return Asin( F / Sqrt( FInt.OneF + ( F * F ) ) );
}
public static FInt Atan2( FInt F1, FInt F2 )
{
if ( F2.RawValue == 0 && F1.RawValue == 0 )
return (FInt)0;
FInt result = (FInt)0;
if ( F2 > 0 )
result = Atan( F1 / F2 );
else if ( F2 < 0 )
{
if ( F1 >= 0 )
result = ( PI - Atan( Abs( F1 / F2 ) ) );
else
result = ( PI - Atan( Abs( F1 / F2 ) ) ).Inverse;
}
else
result = ( F1 >= 0 ? PI : PI.Inverse ) / FInt.Create( 2, true );
return result;
}
#endregion
#region Abs
public static FInt Abs( FInt F )
{
if ( F < 0 )
return F.Inverse;
else
return F;
}
#endregion
</code></pre>
<p>There are a number of other functions in Dr. Hommes' MathFP library, but they were beyond what I needed, and so I have not taken the time to translate them to C# (that process was made extra difficult by the fact that he was using a long, and I am using the FInt struct, which makes the conversion rules are a bit challenging to see immediately).</p>
<p>The accuracy of these functions as they are coded here is more than enough for my purposes, but if you need more you can increase the SHIFT AMOUNT on FInt. Just be aware that if you do so, the constants on Dr. Hommes' functions will then need to be divided by 4096 and then multiplied by whatever your new SHIFT AMOUNT requires. You're likely to run into some bugs if you do that and aren't careful, so be sure to run checks against the built-in Math functions to make sure that your results aren't being put off by incorrectly adjusting a constant.</p>
<p>So far, this FInt logic seems as fast, if not perhaps a bit faster, than the equivalent built in .NET functions. That would obviously vary by machine, since the floating point coprocessor would determine that, so I have not run specific benchmarks. But they are integrated into my game now, and I've seen a slight decrease in processor utilization compared to before (this is on a <a href="https://en.wikipedia.org/wiki/Kentsfield_%28microprocessor%29" rel="nofollow noreferrer">Q6600</a> quad core -- about a 1% drop in usage on average).</p> |
391,710 | In Vim, what is the simplest way to join all lines in a file into a single line? | <p>I want to join all lines in a file into a single line. What is the simplest way of doing this? I've had poor luck trying to use substitution (<code>\r\n</code> or <code>\n</code> doesn't seem to get picked up correctly in the case of <code>s/\r\n//</code> on Windows). Using <code>J</code> in a range expression doesn't seem to work either (probably because the range is no longer in 'sync' after the first command is executed).</p>
<p>I tried <code>:1,$norm! J</code> but this only did half of the file - which makes sense because it just joins each line once.</p> | 391,719 | 6 | 1 | null | 2008-12-24 15:51:56.81 UTC | 18 | 2019-01-30 05:54:16.75 UTC | 2014-06-19 13:30:43.217 UTC | null | 198,738 | j0rd4n | 20,133 | null | 1 | 64 | windows|vim | 33,800 | <p>Ah, I found the answer.</p>
<pre><code>:1,$join
</code></pre>
<p>Works like a charm.</p>
<p><strong>EDIT</strong>: As pointed out in the comment:</p>
<pre><code>:%join -or- :%j
</code></pre>
<p>...removes the range.</p> |
1,066,453 | MySQL "Group By" and "Order By" | <p>I want to be able to select a bunch of rows from a table of e-mails and group them by the from sender. My query looks like this:</p>
<pre><code>SELECT
`timestamp`, `fromEmail`, `subject`
FROM `incomingEmails`
GROUP BY LOWER(`fromEmail`)
ORDER BY `timestamp` DESC
</code></pre>
<p>The query almost works as I want it — it selects records grouped by e-mail. The problem is that the subject and timestamp don't correspond to the most recent record for a particular e-mail address.</p>
<p>For example, it might return:</p>
<pre><code>fromEmail: [email protected], subject: hello
fromEmail: [email protected], subject: welcome
</code></pre>
<p>When the records in the database are:</p>
<pre><code>fromEmail: [email protected], subject: hello
fromEmail: [email protected], subject: programming question
fromEmail: [email protected], subject: welcome
</code></pre>
<p>If the "programming question" subject is the most recent, how can I get MySQL to select that record when grouping the e-mails?</p> | 9,797,138 | 6 | 0 | null | 2009-06-30 22:40:38.463 UTC | 38 | 2022-08-04 09:40:16.463 UTC | 2019-06-28 20:42:03.03 UTC | null | 42,223 | null | 55,732 | null | 1 | 113 | mysql|sql|group-by|sql-order-by|aggregate-functions | 250,616 | <p>A simple solution is to wrap the query into a subselect with the ORDER statement <em>first</em> and applying the GROUP BY <em>later</em>:</p>
<pre><code>SELECT * FROM (
SELECT `timestamp`, `fromEmail`, `subject`
FROM `incomingEmails`
ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)
</code></pre>
<p>This is similar to using the join but looks much nicer.</p>
<p><strong>Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard.</strong> MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.</p>
<p><strong>IMPORTANT UPDATE</strong>
Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the <a href="https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html" rel="nofollow noreferrer">MySQL documentation</a> "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is <strong>free to choose any value</strong> from each group, so <strong>unless they are the same, the values chosen are indeterminate</strong>."</p>
<p>As of <a href="https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html" rel="nofollow noreferrer">5.7.5</a> ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)</p>
<p>As @mikep points out below the solution is to use <a href="https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value" rel="nofollow noreferrer">ANY_VALUE()</a> from 5.7 and above</p>
<p>See
<a href="http://www.cafewebmaster.com/mysql-order-sort-group" rel="nofollow noreferrer">http://www.cafewebmaster.com/mysql-order-sort-group</a>
<a href="https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html" rel="nofollow noreferrer">https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html</a>
<a href="https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html" rel="nofollow noreferrer">https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html</a>
<a href="https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value" rel="nofollow noreferrer">https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value</a></p> |
37,970,424 | What is the difference between drawing plots using plot, axes or figure in matplotlib? | <p>I'm kind of confused what is going at the backend when I draw plots in matplotlib, tbh, I'm not clear with the hierarchy of plot, axes and figure. I read the documentation and it was helpful but I'm still confused...</p>
<p>The below code draws the same plot in three different ways - </p>
<pre><code>#creating the arrays for testing
x = np.arange(1, 100)
y = np.sqrt(x)
#1st way
plt.plot(x, y)
#2nd way
ax = plt.subplot()
ax.plot(x, y)
#3rd way
figure = plt.figure()
new_plot = figure.add_subplot(111)
new_plot.plot(x, y)
</code></pre>
<p>Now my question is -</p>
<ol>
<li><p>What is the difference between all the three, I mean what is going under the hood when any of the 3 methods are called? </p></li>
<li><p>Which method should be used when and what are the pros and cons of using any on those? </p></li>
</ol> | 37,970,713 | 2 | 3 | null | 2016-06-22 14:04:10.127 UTC | 87 | 2020-12-20 17:43:51.837 UTC | null | null | null | null | 5,540,305 | null | 1 | 150 | python|matplotlib | 52,721 | <p><strong>Method 1</strong></p>
<pre><code>plt.plot(x, y)
</code></pre>
<p>This lets you plot just one figure with (x,y) coordinates. If you just want to get one graphic, you can use this way.</p>
<p><strong>Method 2</strong></p>
<pre><code>ax = plt.subplot()
ax.plot(x, y)
</code></pre>
<p>This lets you plot one or several figure(s) in the same window. As you write it, you will plot just one figure, but you can make something like this:</p>
<pre><code>fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
</code></pre>
<p>You will plot 4 figures which are named ax1, ax2, ax3 and ax4 each one but on the same window. This window will be just divided in 4 parts with my example.</p>
<p><strong>Method 3</strong></p>
<pre><code>fig = plt.figure()
new_plot = fig.add_subplot(111)
new_plot.plot(x, y)
</code></pre>
<p>I didn't use it, but you can find documentation.</p>
<p><strong>Example:</strong> </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
# Method 1 #
x = np.random.rand(10)
y = np.random.rand(10)
figure1 = plt.plot(x,y)
# Method 2 #
x1 = np.random.rand(10)
x2 = np.random.rand(10)
x3 = np.random.rand(10)
x4 = np.random.rand(10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
y3 = np.random.rand(10)
y4 = np.random.rand(10)
figure2, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.plot(x1,y1)
ax2.plot(x2,y2)
ax3.plot(x3,y3)
ax4.plot(x4,y4)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/zCAEL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zCAEL.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/LNRsa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LNRsa.png" alt="enter image description here"></a></p>
<p><strong>Other example:</strong></p>
<p><a href="https://i.stack.imgur.com/ArvNL.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ArvNL.jpg" alt="enter image description here"></a></p> |
37,815,641 | Visual Studio 2015 “non-standard syntax; use '&' to create a pointer to member” | <p>I am learning C++ and try to make a small game of Tic Tac Toe. But I keep on getting C3867, non-standard syntax; use '&' to create a pointer to remember.</p>
<p>This is my TicTacToe.h :</p>
<pre><code>#pragma once
#include <iostream>
using namespace std;
class TicTacToe
{
public:
TicTacToe();
string getName1();
string getName2();
void printBoard();
void clearBoard();
void setName1(string player1Name);
void setName2(string player2Name);
void setSign1(string player1Sign);
void setSign2(string player2Sign, string player1Sign);
void playGame(string player1Name, string player2Name,string player1Sign,string player2Sign);
void player1Move(string coordX);
void player1Turn();
void player2Turn();
private:
char Board[3][3];
string _player1Name;
string _player2Name;
string _player1Sign;
string _player2Sign;
string _coordX;
string _coordY;
};
</code></pre>
<p>And here is my TicTacToe.cpp :</p>
<pre><code>#include "TicTacToe.h"
#include <iostream>
#include <string>
TicTacToe::TicTacToe() {}
void TicTacToe::playGame(string player1Name, string player2Name,
string player1Sign, string player2Sign) {
TicTacToe Board;
Board.setName1(player1Name);
Board.setSign1(player1Sign);
Board.setName2(player2Name);
Board.setSign2(player1Sign, player2Sign);
Board.clearBoard();
Board.printBoard();
}
void TicTacToe::printBoard() {
cout << " |1|2|3|\n";
for (int i = 0; i < 3; i++) {
cout << "--------\n";
cout << i + 1 << "|" << Board[i][0] << "|" << Board[i][1] << "|"
<< Board[i][2] << "|" << endl;
}
}
void TicTacToe::clearBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Board[i][j] = ' ';
}
}
}
void TicTacToe::setName1(string player1Name) {
cout << "Enter your name, player 1: \n";
cin >> player1Name;
_player1Name = player1Name;
}
void TicTacToe::setName2(string player2Name) {
cout << "Enter your name, player 2: \n";
cin >> player2Name;
_player2Name = player2Name;
}
string TicTacToe::getName1() { return _player1Name; }
string TicTacToe::getName2() { return _player2Name; }
void TicTacToe::setSign1(string player1Sign) {
cout << "What will you sign be?(X/O)\n";
cin >> player1Sign;
if (player1Sign != "X" && player1Sign != "O" && player1Sign != "x" &&
player1Sign != "o") {
cout << "Invalid input, try again.\n";
cin >> player1Sign;
}
_player1Sign = player1Sign;
}
void TicTacToe::setSign2(string player2Sign, string player1Sign) {
cout << "What will you sign be?(X/O)\n";
cin >> player2Sign;
if (player2Sign != "X" && player2Sign != "O" && player2Sign != "x" &&
player2Sign != "o" ||
player2Sign == player1Sign) {
cout << "Invalid input, try again.\n";
cin >> player2Sign;
}
_player2Sign = player2Sign;
}
void TicTacToe::player1Move(string coordX) // ERROR
{
cout << "Enter X: " << endl;
cin >> coordX;
_coordX = coordX;
}
void TicTacToe::player1Turn() {
cout << "Player 1 turn !\n";
TicTacToe Board;
Board.player1Move;
}
void TicTacToe::player2Turn() {
cout << "Player 2 turn !\n";
TicTacToe Board;
Board.player1Move;
}
</code></pre>
<p>I have tried everything in other questions about this error but they didn't work. How do you fix this error?</p> | 37,815,886 | 3 | 5 | null | 2016-06-14 15:00:54.027 UTC | 2 | 2018-05-19 09:03:51.833 UTC | 2018-05-19 09:03:51.833 UTC | null | 9,193,372 | null | 6,465,124 | null | 1 | 19 | c++|visual-studio-2015 | 94,387 | <p>The problem is with the lines which contain the following (it appears twice in your code):</p>
<pre><code>Board.player1Move;
</code></pre>
<p>Player one move is a function which receive an std::string parameter as an input. In order to call it you'll need to create an std::string object and pass it as an argument for the function. You can use the following syntax if you want the string to be given as an input:</p>
<pre><code>std::string move;
cin >> move;
Board.player1Move(move);
</code></pre>
<p>Also, notice that player2Turn should call Board.player2Move instead of Board.player1Move.</p> |
33,257,344 | How to remove special characers from a column of dataframe using module re? | <p>Hey I have seen that link but nowhere there they have used <code>re</code> module that's why I have posted here. Hope you understand and remove the duplicate.</p>
<p>Here is the <a href="https://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python">Link</a>. I want to use <code>re</code> module.</p>
<p>Table:</p>
<pre><code>A B C D
1 Q! W@ 2
2 1$ E% 3
3 S2# D! 4
</code></pre>
<p>here I want to remove the special characters from <code>column</code> <code>B</code> and <code>C</code>. I have used <code>.transform()</code> but I want to do it using <code>re</code> if possible but I am getting errors.</p>
<p>Output:</p>
<pre><code>A B C D E F
1 Q! W@ 2 Q W
2 1$ E% 3 1 E
3 S2# D! 4 S2 D
</code></pre>
<p>My Code:</p>
<pre><code>df['E'] = df['B'].str.translate(None, ",!.; -@!%^&*)(")
</code></pre>
<p>It's working only if I know what are the special characters.</p>
<p>But I want to use <code>re</code> which would be the best way.</p>
<pre><code>import re
#re.sub(r'\W+', '', your_string)
df['E'] = re.sub(r'\W+', '', df['B'].str)
</code></pre>
<p>Here I am getting error:</p>
<pre><code>TypeError: expected string or buffer
</code></pre>
<p>So how should I pass the value to get the correct output.</p> | 33,258,365 | 2 | 5 | null | 2015-10-21 10:49:29.997 UTC | 10 | 2020-05-02 11:53:40.21 UTC | 2018-05-23 07:12:09.81 UTC | null | 4,909,087 | null | 4,794,848 | null | 1 | 19 | python|string|pandas | 89,622 | <p>As <a href="https://stackoverflow.com/questions/13682044/pandas-dataframe-remove-unwanted-parts-from-strings-in-a-column">this answer</a> shows, you can use <code>map()</code> with a <code>lambda</code> function that will assemble and return any expression you like:</p>
<pre><code>df['E'] = df['B'].map(lambda x: re.sub(r'\W+', '', x))
</code></pre>
<p><code>lambda</code> simply defines anonymous functions. You can leave them anonymous, or assign them to a reference like any other object. <code>my_function = lambda x: x.my_method(3)</code> is equivalent to <code>def my_function(x): return x.my_method(3)</code>.</p> |
1,739,013 | Find all htaccess files on server | <p>I'm looking for a Linux command to go through all the directories on my server and find all .htaccess files. The output would be a list of all those files with full path, creation/modification date and filesize.</p> | 1,739,028 | 5 | 2 | null | 2009-11-15 22:06:14.613 UTC | 5 | 2013-10-07 21:01:08.803 UTC | 2009-11-19 05:08:11.467 UTC | null | 1,288 | null | 78,297 | null | 1 | 18 | linux|.htaccess | 68,756 | <p><code>find / -name ".htaccess" -print</code></p>
<p>Replace <code>/</code> with the root folder you like to start searching, in case you don't want to search the whole file system.</p>
<p>Wikipedia has an article about <a href="http://en.wikipedia.org/wiki/Find" rel="noreferrer">find</a>, which also links to its man page.</p> |
1,574,877 | Identifying all rows within a table <tbody> element using jQuery | <p>I am trying to retrieve all rows from within a <code><tbody></code> section of a table, but am unsure of the syntax for doing so. I've included a dummy table extract below and my latest attempt for achieving the task with jQuery!</p>
<p><strong>Table extract:</strong></p>
<pre><code><tbody>
<tr>
<th id="emergency" colspan="2">Emergency</th>
</tr>
<tr>
<td>Emergency data</td>
<td>Emergency data</td>
</tr>
<tr>
<td>Emergency data</td>
<td>Emergency data</td>
</tr>
</tbody>
<tbody>
<tr>
<th id="urgent" colspan="2">Urgent</th>
</tr>
<tr>
<td>Urgent Data</td>
<td>Urgent Data</td>
</tr>
<tr>
<td>Urgent Data</td>
<td>Urgent Data</td>
</tr>
</tbody>
</code></pre>
<p><strong>jQuery code:</strong></p>
<pre><code>var emergencyRows = $table.find('#emergency').children().get();
</code></pre> | 1,574,947 | 6 | 0 | null | 2009-10-15 20:35:53.2 UTC | 2 | 2017-01-14 10:41:36.437 UTC | 2017-01-14 10:41:36.437 UTC | null | 4,370,109 | null | 86,424 | null | 1 | 8 | jquery|html-table | 80,179 | <p>My suggestions is to place the ID attributes on the tbody rather than the first row of each one.</p>
<p><strong>HTML</strong></p>
<pre><code><table>
<tbody id="emergency">
<tr>
<th colspan="2">Emergency</th>
</tr>
<tr>
<td>Emergency data</td>
<td>Emergency data</td>
</tr>
<tr>
<td>Emergency data</td>
<td>Emergency data</td>
</tr>
</tbody>
<tbody id="urgent">
<tr>
<th colspan="2">Urgent</th>
</tr>
<tr>
<td>Urgent Data</td>
<td>Urgent Data</td>
</tr>
<tr>
<td>Urgent Data</td>
<td>Urgent Data</td>
</tr>
</tbody>
</table>
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>var emergencyRows = $("tbody#emergency").find("tr:gt(0)");
var urgentRows = $("tbody#urgent").find("tr:gt(0)");
</code></pre>
<p>The jQuery snippet will get all the respective rows with the exception of the first rows.</p> |
1,978,517 | Where can I browse the sourcecode for libc online (like doxygen) | <p>Sometimes I want to look up the implementations of functions in the stdlib, I've downloaded the sourcecode, but it's quite messy.</p>
<p>Just greping is not really suitable because of the many hits.</p>
<p>Does anyone know a webpage doxygen style that has the documentation.</p>
<p>The same goes for the linux kernel.</p>
<p>Thanks</p> | 1,978,566 | 6 | 4 | null | 2009-12-30 05:10:51.2 UTC | 9 | 2020-03-15 15:34:22.653 UTC | null | null | null | null | 237,472 | null | 1 | 31 | documentation|kernel|libc | 17,790 | <p>How about <a href="http://developer.novell.com/wiki/index.php/Libraries_for_C_(LibC)_Documentation" rel="nofollow noreferrer">this</a> for libc documentation? And perhaps <a href="http://kernel.org/doc/man-pages/" rel="nofollow noreferrer">this</a> for the kernel? There is also Google Code search; <a href="http://www.google.com/codesearch/p?hl=en#BuFT5TyPBak/pub/linux/kernel/v2.4/linux-2.4.34.tar.bz2|hh9JStbEQIo/linux-2.4.34/include/acpi/acconfig.h&q=kernel&d=2" rel="nofollow noreferrer">here</a> is an example search.</p>
<p>More on <a href="http://www.google.com/codesearch" rel="nofollow noreferrer">Google Code Search</a> You can enter search queries like this: package:linux-2.6 malloc for any references to malloc in the linux-2.6 kernel.</p>
<p>Edit: Google Code search is now shut down. But you can access the git repo at <a href="http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git" rel="nofollow noreferrer">http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git</a> and it has search as well.</p> |
1,835,440 | jQuery changing css class to div | <p>If I have one div element for example and class 'first' is defined with many css properties. Can I assign css class 'second' which also has many properties differently defined to this same div just on some event without writing each property in line.</p> | 1,835,454 | 6 | 0 | null | 2009-12-02 20:05:44.873 UTC | 7 | 2015-01-03 13:30:46.867 UTC | 2012-01-29 00:17:19.457 UTC | null | 746,010 | null | 144,140 | null | 1 | 47 | jquery|css|html | 199,796 | <pre><code>$(".first").addClass("second");
</code></pre>
<p>If you'd like to add it on an event, you can do so easily as well. An example with the click event:</p>
<pre><code>$(".first").click(function() {
$(this).addClass("second");
});
</code></pre> |
1,698,275 | WCF ChannelFactory vs generating proxy | <p>Just wondering under what circumstances would you prefer to generate a proxy from a WCF service when you can just invoke calls using the ChannelFactory?</p>
<p>This way you won't have to generate a proxy and worry about regenerating a proxy when the server is updated?</p>
<p>Thanks</p> | 2,583,403 | 6 | 1 | null | 2009-11-08 23:16:08.047 UTC | 48 | 2015-04-18 14:23:53.703 UTC | 2014-10-10 10:02:07.953 UTC | null | 27,756 | null | 195,024 | null | 1 | 82 | wcf|proxy|channelfactory | 46,347 | <p>There are 3 basic ways to create a WCF client:</p>
<ol>
<li><p>Let Visual Studio generate your proxy. This auto generates code that connects to the service by reading the WSDL. If the service changes for any reason you have to regenerate it. The big advantage of this is that it is easy to set up - VS has a wizard and it's all automatic. The disadvantage is that you're relying on VS to do all the hard work for you, and so you lose control.</p></li>
<li><p>Use <code>ChannelFactory</code> with a known interface. This relies on you having local interfaces that describe the service (the service contract). The big advantage is that can manage change much more easily - you still have to recompile and fix changes, but now you're not regenerating code, you're referencing the new interfaces. Commonly this is used when you control both server and client as both can be much more easily mocked for unit testing. However the interfaces can be written for any service, even REST ones - take a look at <a href="http://vertigotwitter.codeplex.com/Wikipage" rel="noreferrer">this Twitter API</a>.</p></li>
<li><p>Write your own proxy - this is fairly easy to do, especially for REST services, using the <code>HttpClient</code> or <code>WebClient</code>. This gives you the most fine grain control, but at the cost of lots of service API being in strings. For instance: <code>var content = new HttpClient().Get("http://yoursite.com/resource/id").Content;</code> - if the details of the API change you won't encounter an error until runtime.</p></li>
</ol>
<p>Personally I've never liked option 1 - relying on the auto generated code is messy and loses too much control. Plus it often creates serialisation issues - I end up with two identical classes (one in the server code, one auto generated) which can be tided up but is a pain.</p>
<p>Option 2 should be perfect, but Channels are a little too limiting - for instance they <a href="https://stackoverflow.com/questions/2516914/getting-error-detail-from-wcf-rest">completely lose the content of HTTP errors</a>. That said having interfaces that describe the service is much easier to code with and maintain.</p> |
1,352,600 | Free SQL comparison tool | <p>I have been using SQL Compare by Redgate at my company and was very satisfied with it. Are there any free comparison tools that are similar? Or what would be my best shot for synchronizing two SQL db's without a paid application</p> | 1,352,652 | 8 | 2 | null | 2009-08-29 23:01:18.83 UTC | 11 | 2013-06-24 23:36:53.56 UTC | null | null | null | null | 145,143 | null | 1 | 21 | sql|database | 23,362 | <p>I’ve gone through this and couldn’t find anything comparable, free or otherwise. $395 is a very small price to pay for the value the tool brings and it will almost certainly pay for itself very quickly in productivity gains and risk minimisation.</p> |
1,920,615 | Field initialization | <p>Are there any differences between the following two ways of field initialization? When to use which one?</p>
<h3>First way</h3>
<pre><code>public class Class1
{
private SomeClass someclass;
public Class1()
{
someclass = new SomeClass(some arg);
}
}
</code></pre>
<h3>Second way</h3>
<pre><code>public class Class1
{
private SomeClass someclass = new SomeClass(some arg);
}
</code></pre>
<p>The field in the second example could be readonly.</p> | 1,920,814 | 9 | 0 | null | 2009-12-17 09:53:55.933 UTC | 14 | 2017-05-07 14:11:46.923 UTC | 2017-05-07 14:11:46.923 UTC | null | 63,550 | null | 137,348 | null | 1 | 28 | c#|.net|oop | 14,874 | <p>You cannot make use of the <code>this</code> keyword when initializing fields inline. The reason for this is the order in which the code is executed: for all intents and purposes, the code to initialize a field inline is run before the constructor for the class (i.e. the C# compiler will prevent access to the <code>this</code> keyword). Basically what that means is this will not compile:</p>
<pre><code>public class Class1
{
private SomeClass someclass = new SomeClass(this);
public Class1()
{
}
}
</code></pre>
<p>but this will:</p>
<pre><code>public class Class1
{
private SomeClass someclass;
public Class1()
{
someclass = new SomeClass(this);
}
}
</code></pre>
<p>It's a subtle difference, but one worth making a note of.</p>
<p>The other differences between the two versions are only really noticeable when using inheritance. If you have two classes which inherit from each other, the fields in the derived class will be initialized first, then the fields in the base class will be initialized, then the constructor for the base class will be invoked, and finally, the constructor for the derived class will be invoked. There are some cases where you need to be very careful with this, as it could cause a fruit salad of complications if you don't realise what is going on (one of which involves calling a virtual method inside the base class constructor, but that is almost never a wise move). Heres an example:</p>
<pre><code>class BaseClass
{
private readonly object objectA = new object(); // Second
private readonly object objectB;
public BaseClass()
{
this.objectB = new object(); // Third
}
}
class DerivedClass : BaseClass
{
private object objectC = new object(); // First
private object objectD;
public DerivedClass()
{
this.objectD = new object(); // Forth
}
}
</code></pre>
<p>You will need to set breakpoints on all of the lines that initialize fields to be able to see the correct sequence.</p> |
1,494,631 | How do I use my .vimrc file in Cygwin? | <p>I just installed Cygwin on my work machine and would like to use the .vimrc file I use on my Linux box at home.</p>
<ul>
<li>Is that possible, or does it need to have Cygwin-specific settings?</li>
<li>Where would I put the .vimrc file?</li>
</ul>
<p>I'm a little unsure of what directory I'm being dropped into at the bash prompt under Cygwin, but I think I'd create a subdirectory called .vim there, right?</p> | 1,494,647 | 10 | 2 | null | 2009-09-29 20:04:41.68 UTC | 6 | 2022-07-15 07:29:24.25 UTC | null | null | null | null | 4,376 | null | 1 | 27 | cygwin|vim | 38,358 | <p>1) Yes it is possible. It doesnt need any cygwin specific settings, though you can add some windows specific ones. Just make sure to install vi (vim gvim equivalent) properly.</p>
<p>2) the same place as on *nix -- user home directory</p> |
1,945,213 | What is Eclipse's Ctrl+O (Show Outline) shortcut equivalent in IntelliJ IDEA? | <p>I like to use Eclipse's shortcut <kbd>Ctrl</kbd> + <kbd>O</kbd> which outlines the current source. Is there an equivalent shortcut in IntelliJ IDEA?</p>
<p>It opens a dialog which allows for quick search of methods and fields in a class.</p> | 1,945,231 | 19 | 1 | null | 2009-12-22 09:34:30.457 UTC | 52 | 2021-08-26 08:58:49.977 UTC | 2017-05-04 11:31:01.743 UTC | null | 32,090 | null | 32,090 | null | 1 | 295 | java|eclipse|ide|keyboard-shortcuts|intellij-idea | 73,950 | <p>I haven't used Eclipse for years, so I'm not that familiar with the behaviour you're after - but I believe <kbd>Ctrl</kbd> + <kbd>F12</kbd> may do what you want: it is the shortcut for the <em>File structure Popup</em> in the default mapping.</p>
<p>For macOS <kbd>fn</kbd> + <kbd>cmd</kbd> + <kbd>F12</kbd></p> |
2,271,131 | Display the current time and date in an Android application | <p>How do I display the current date and time in an Android application?</p> | 2,271,305 | 23 | 0 | null | 2010-02-16 07:02:47.09 UTC | 52 | 2020-09-11 02:14:34.553 UTC | 2019-12-16 14:47:58.293 UTC | null | 5,772,882 | null | 263,325 | null | 1 | 208 | android|datetime|android-date | 579,106 | <p>Okay, not that hard as there are several methods to do this. I assume you want to put the current date & time into a <code>TextView</code>.</p>
<pre><code>String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());
// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
</code></pre>
<p>There is more to read in the documentation that can easily be found <a href="http://developer.android.com/reference/java/text/DateFormat.html#getDateTimeInstance%28%29" rel="noreferrer">here</a>
. There you'll find more information on how to change the format used for conversion.</p> |
8,541,733 | syntax error, unexpected ',', expecting ')' | <p>I just installed Ruby 1.9.2 after having used 1.8.7, as there is a feature I need. I had called many of my methods like this:</p>
<pre><code>do_something (arg0, arg1)
</code></pre>
<p>With 1.9.2, i get the following error, <code>syntax error, unexpected ',', expecting ')'</code> and the fix seems to be:</p>
<pre><code>do_something arg0, arg1
</code></pre>
<p>But this could take me hours to fix all the cases. Is there a way around this? Why is it an error in the first place? thanks</p> | 8,541,761 | 1 | 2 | null | 2011-12-17 00:32:04.583 UTC | 8 | 2011-12-17 01:31:42.897 UTC | 2011-12-17 01:31:42.897 UTC | null | 38,765 | null | 612,275 | null | 1 | 15 | ruby|syntax-error|ruby-1.9 | 42,935 | <p>The extra space is the culprit. Use:</p>
<pre><code>do_something(arg0, arg1)
</code></pre> |
18,002,747 | Best practices for handling changes to the UINavigationItem of child view controllers in a container controller? | <p>Suppose I have a container controller that accepts an array of UIViewControllers and lays them out so the user can swipe left and right to transition between them. This container controller is wrapped inside a navigation controller and is made the root view controller of the application's main window.</p>
<p>Each child controller makes a request to the API and loads a list of items that are displayed in a table view. Based on the items that are displayed a button may be added to the navigation bar that allows the user to act on all the items in the table view.</p>
<p>Because UINavigationController only uses the UINavigationItems of its child view controllers, the container controller needs to update its UINavigationItem to be in sync with the UINavigationItem of its children.</p>
<p>There appear to be two scenarios that the container controller needs to handle:</p>
<ol>
<li>The selected view controller of the container controller changes and therefore the UINavigationItem of the container controller should update itself to mimic the UINavigationItem of the selected view controller.</li>
<li>A child controller updates its UINavigationItem and the container controller must be made aware of the change and update its UINavigationItem to match.</li>
</ol>
<p>The best solutions I've come up with are:</p>
<ol>
<li>In the setSelectedViewController: method query the navigation item of the selected view controller and update the leftBarButtonItems, rightBarButtonItems and title properties of the container controller's UINavigationItem to be the same as the selected view controller's UINavigationItem.</li>
<li>In the setSelectedViewController method KVO onto the leftBarButtonItems, rightBarButtonItems and title property of the selected view controller's UINavigationItem and whenever one of those properties changes up the container controller's UINavigationItem.</li>
</ol>
<p>This is a recurring problem with many of the container controllers that I have written and I can't seem to find any documented solutions to these problems.</p>
<p>What are some solutions people have found to this problem?</p> | 18,192,780 | 5 | 4 | null | 2013-08-01 19:21:49.64 UTC | 10 | 2020-02-20 03:39:28.117 UTC | 2013-08-01 19:49:10.517 UTC | null | 603,977 | null | 1,666,298 | null | 1 | 28 | ios|cocoa-touch|uinavigationcontroller|uinavigationitem | 6,866 | <p>So the solution that I have currently implemented is to create a category on UIViewController with methods that allow you to set the right bar buttons of that controller's navigation item and then that controller posts a notification letting anyone who cares know that the right bar button items have been changed.</p>
<p>In my container controller I listen for this notification from the currently selected view controller and update the container controller's navigation item accordingly.</p>
<p>In my scenario the container controller overrides the method in the category so that it can keep a local copy of the right bar button items that have been assigned to it and if any notifications are raised it concatenates its right bar button items with its child's and then sends up a notification just incase it is also inside a container controller.</p>
<p>Here is the code that I am using.</p>
<p>UIViewController+ContainerNavigationItem.h</p>
<pre><code>#import <UIKit/UIKit.h>
extern NSString *const UIViewControllerRightBarButtonItemsChangedNotification;
@interface UIViewController (ContainerNavigationItem)
- (void)setRightBarButtonItems:(NSArray *)rightBarButtonItems;
- (void)setRightBarButtonItem:(UIBarButtonItem *)rightBarButtonItem;
@end
</code></pre>
<p>UIViewController+ContainerNavigationItem.m</p>
<pre><code>#import "UIViewController+ContainerNavigationItem.h"
NSString *const UIViewControllerRightBarButtonItemsChangedNotification = @"UIViewControllerRightBarButtonItemsChangedNotification";
@implementation UIViewController (ContainerNavigationItem)
- (void)setRightBarButtonItems:(NSArray *)rightBarButtonItems
{
[[self navigationItem] setRightBarButtonItems:rightBarButtonItems];
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:UIViewControllerRightBarButtonItemsChangedNotification object:self];
}
- (void)setRightBarButtonItem:(UIBarButtonItem *)rightBarButtonItem
{
if(rightBarButtonItem != nil)
[self setRightBarButtonItems:@[ rightBarButtonItem ]];
else
[self setRightBarButtonItems:nil];
}
@end
</code></pre>
<p>ContainerController.m</p>
<pre><code>- (void)setRightBarButtonItems:(NSArray *)rightBarButtonItems
{
_rightBarButtonItems = rightBarButtonItems;
[super setRightBarButtonItems:_rightBarButtonItems];
}
- (void)setSelectedViewController:(UIViewController *)selectedViewController
{
if(_selectedViewController != selectedViewController)
{
if(_selectedViewController != nil)
{
// Stop listening for right bar button item changed notification on the view controller.
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:UIViewControllerRightBarButtonItemsChangedNotification object:_selectedViewController];
}
_selectedViewController = selectedViewController;
if(_selectedViewController != nil)
{
// Listen for right bar button item changed notification on the view controller.
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:@selector(_childRightBarButtonItemsChanged) name:UIViewControllerRightBarButtonItemsChangedNotification object:_selectedViewController];
}
}
}
- (void)_childRightBarButtonItemsChanged
{
NSArray *childRightBarButtonItems = [[_selectedViewController navigationItem] rightBarButtonItems];
NSMutableArray *rightBarButtonItems = [NSMutableArray arrayWithArray:_rightBarButtonItems];
[rightBarButtonItems addObjectsFromArray:childRightBarButtonItems];
[super setRightBarButtonItems:rightBarButtonItems];
}
</code></pre> |
6,987,611 | How to search through a JSON Array in PHP | <p>I have a JSON array </p>
<pre><code>{
"people":[
{
"id": "8080",
"content": "foo"
},
{
"id": "8097",
"content": "bar"
}
]
}
</code></pre>
<p>How would I search for 8097 and get the content?</p> | 6,987,642 | 3 | 3 | null | 2011-08-08 19:39:40.16 UTC | 11 | 2019-10-07 17:59:03.603 UTC | 2011-08-08 20:16:50.493 UTC | null | 259,014 | null | 884,706 | null | 1 | 20 | php|arrays|json | 88,583 | <p>Use the <a href="http://php.net/json_decode" rel="noreferrer"><code>json_decode</code></a> function to convert the JSON string to an array of object, then iterate through the array until the desired object is found:</p>
<pre><code>$str = '{
"people":[
{
"id": "8080",
"content": "foo"
},
{
"id": "8097",
"content": "bar"
}
]
}';
$json = json_decode($str);
foreach ($json->people as $item) {
if ($item->id == "8097") {
echo $item->content;
}
}
</code></pre> |
6,646,244 | MVC 3: How to learn how to test with NUnit, Ninject, and Moq? | <p><strong>Short version of my questions:</strong></p>
<ol>
<li>Can anyone point me toward some good, detailed sources from which I
can learn how to implement testing in my MVC 3 application, using
NUnit, Ninject 2, and Moq?</li>
<li>Can anyone here help clarify for me how Controller-Repository
decoupling, mocking, and dependency injection work together?</li>
</ol>
<hr>
<p><strong>Longer version of my questions:</strong></p>
<p><strong>What I'm trying to do ...</strong></p>
<p>I am currently beginning to create an MVC 3 application, which will use Entity Framework 4, with a database first approach. I want to do this right, so I am trying to design the classes, layers, etc., to be highly testable. But, I have little to no experience with unit testing or integration testing, other than an academic understanding of them.</p>
<p>After lots of research, I've settle on using </p>
<ul>
<li><strong>NUnit</strong> as my testing framework</li>
<li><strong>Ninject 2</strong> as my dependency injection framework</li>
<li><strong>Moq</strong> as my mocking framework.</li>
</ul>
<p>I know the topic of which framework is best, etc., could enter into this, but at this point I really don't know enough about any of it to form a solid opinion. So, I just decided to go with these free solutions which seem to be well liked and well maintained. </p>
<p><strong>What I've learned so far ...</strong></p>
<p>I've spent some time working through some of this stuff, reading resources such as:</p>
<ul>
<li><a href="http://www.asp.net/entity-framework/tutorials/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application" rel="noreferrer"><strong>Implementing the Repository and Unit of Work Patterns in an
ASP.NET MVC Application</strong></a></li>
<li><a href="http://msdn.microsoft.com/en-us/magazine/dd942838.aspx" rel="noreferrer"><strong>Building Testable ASP.NET MVC Applications</strong></a></li>
<li><a href="http://nerddinnerbook.s3.amazonaws.com/Part12.htm" rel="noreferrer"><strong>NerdDinner Step 12: Unit Testing</strong></a></li>
<li><a href="http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx" rel="noreferrer"><strong>Using Repository and Unit of Work patterns with Entity Framework
4.0</strong></a></li>
</ul>
<p>From these resources, I've managed to workout the need for a Repository pattern, complete with repository interfaces, in order to decouple my controllers and my data access logic. I have written some of that into my application already, but I admit I am not clear as to the mechanics of the whole thing, and whether I am doing this decoupling in support of mocking, or dependency injection, or both. As such, I certainly wouldn't mind hearing from you guys about this too. Any clarity I can gain on this stuff will help me at this point.</p>
<p><strong>Where things got muddy for me ...</strong></p>
<p>I thought I was grasping this stuff pretty well until I started trying to wrap my head around Ninject, as described in <a href="http://msdn.microsoft.com/en-us/magazine/dd942838.aspx" rel="noreferrer">Building Testable ASP.NET MVC Applications</a>, cited above. Specifically, I got completely lost around the point in which the author begins describing the implementation of a Service layer, about half way into the document.</p>
<p>Anyway, I am now looking for more resources to study, in order to try to get various perspectives around this stuff until it begins to make sense to me. </p>
<p>Summarizing all of this, boiling it down to specific questions, I am wondering the following:</p>
<ol>
<li>Can anyone point me toward some good, detailed sources from which I
can learn how to implement testing in my MVC 3 application, using
NUnit, Ninject 2, and Moq?</li>
<li>Can anyone here help clarify for me how Controller-Repository
decoupling, mocking, and dependency injection work together?</li>
</ol>
<p><strong>EDIT:</strong> </p>
<p>I just discovered the <a href="https://github.com/ninject/ninject/wiki" rel="noreferrer">Ninject official wiki</a> on Github, so I'm going to start working through that to see if it starts clarifying things for me. But, I'm still very interested in the SO community thoughts on all of this :)</p> | 6,646,591 | 3 | 0 | null | 2011-07-11 05:49:42.78 UTC | 33 | 2011-09-10 19:26:05.243 UTC | 2011-07-11 06:22:59.83 UTC | null | 272,219 | null | 272,219 | null | 1 | 50 | unit-testing|asp.net-mvc-3|nunit|moq|ninject-2 | 16,166 | <p>If you are using the <a href="http://nuget.org/List/Packages/Ninject.MVC3">Ninject.MVC3</a> nuget package, then some of the article you linked that was causing confusion will not be required. That package has everything you need to start injecting your controllers which is probably the biggest pain point.</p>
<p>Upon installing that package, it will create a NinjectMVC3.cs file in the App_Start folder, inside that class is a RegisterServices method. This is where you should create the bindings between your interfaces and your implementations</p>
<pre><code>private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IRepository>().To<MyRepositoryImpl>();
kernel.Bind<IWebData>().To<MyWebDAtaImpl>();
}
</code></pre>
<p>Now in your controller you can use constructor injection.</p>
<pre><code>public class HomeController : Controller {
private readonly IRepository _Repo;
private readonly IWebData _WebData;
public HomeController(IRepository repo, IWebData webData) {
_Repo = repo;
_WebData = webData;
}
}
</code></pre>
<p>If you are after very high test coverage, then basically anytime one logical piece of code (say controller) needs to talk to another (say database) you should create an interface and implementation, add the definition binding to RegisterService and add a new constructor argument. </p>
<p>This applies not only to Controller, but any class, so in the example above if your repository implementation needed an instance of WebData for something, you would add the readonly field and the constructor to your repository implementation.</p>
<p>Then when it comes to testing, what you want to do is provide mocked version of all required interfaces, so that the only thing you are testing is the code in the method you are writing the test for. So in my example, say that IRepository has a </p>
<pre><code>bool TryCreateUser(string username);
</code></pre>
<p>Which is called by a controller method</p>
<pre><code>public ActionResult CreateUser(string username) {
if (_Repo.TryCreateUser(username))
return RedirectToAction("CreatedUser");
else
return RedirectToAction("Error");
}
</code></pre>
<p>What you are really trying to test here is that if statement and the return types, you do not want to have to create a real repository that will return true or false based on special values you give it. This is where you want to mock.</p>
<pre><code>public void TestCreateUserSucceeds() {
var repo = new Mock<IRepository>();
repo.Setup(d=> d.TryCreateUser(It.IsAny<string>())).Returns(true);
var controller = new HomeController(repo);
var result = controller.CreateUser("test");
Assert.IsNotNull(result);
Assert.IsOfType<RedirectToActionResult>(result)
Assert.AreEqual("CreatedUser", ((RedirectToActionResult)result).RouteData["Action"]);
}
</code></pre>
<p>^ That won't compile for you as I know xUnit better, and do not remember the property names on RedirectToActionResult from the top of my head.</p>
<p>So to sum up, if you want one piece of code to talk to another, whack an interface in between. This then allows you to mock the second piece of code so that when you test the first you can control the output and be sure you are testing only the code in question.<br>
I think it was this point that really made the penny drop for me with all this, you do this not necessarily becase the code demands it, but because the testing demands it.</p>
<p>One last piece of advice specific to MVC, any time you need to access the basic web objects, HttpContext, HttpRequest etc, wrap all these behind an interface as well (like the IWebData in my example) because while you can mock these using the *Base classes, it becomes painful very quickly as they have a lot of internal dependencies you also need to mock.<br>
Also with Moq, set the MockBehaviour to Strict when creating mocks and it will tell you if anything is being called that you have not provided a mock for.</p> |
6,956,747 | C# Missing MSVCR100.dll | <p>I'm developing an app that execute another app and I received this error:</p>
<blockquote>
<p>the program can't start because MSVCR100.dll is missing from your
computer</p>
</blockquote>
<p>with my C# app, can I fix this problem copying this .dll into windows/system32 folder?
Or exists another method to do this?</p> | 6,963,678 | 4 | 3 | null | 2011-08-05 13:05:33.247 UTC | 2 | 2015-06-03 10:45:09.593 UTC | 2015-06-03 10:45:09.593 UTC | null | 1,314,503 | null | 353,030 | null | 1 | 20 | c#|windows|dll|system32|msvcr100.dll | 39,269 | <p>This links below point to the proper downloads for the MSVCRT100 installer. This is likely what you want your customers to run before installing your app. This will properly install the MSVCRT DLLs in the proper directory such that all applications can use it.</p>
<p><a href="http://www.microsoft.com/download/en/details.aspx?id=5555">Microsoft Visual C++ 2010 Redistributable Package (x86)</a> (probably what you need for 32-bit and 64-bit os)</p>
<p><a href="http://www.microsoft.com/download/en/details.aspx?id=14632">Microsoft Visual C++ 2010 Redistributable Package (x64)</a> (Only if your app itself is 64-bit)</p>
<p>If you actually want to install the MSVCRT100 DLLs through a merge module within your own MSI - you can link your MSI to the MSMs that are located in the x86 version your "c:\program files\common files\merge modules" directory" (Assuming you have Visual Studio 2010 installed).</p>
<pre><code>C:\Program Files (x86)\Common Files\Merge Modules>dir *CRT*.msm
Volume in drive C has no label.
Volume Serial Number is 60A4-1718
Directory of C:\Program Files (x86)\Common Files\Merge Modules
04/22/2011 01:18 PM 584,192 Microsoft_VC100_CRT_x64.msm
04/22/2011 01:41 PM 571,904 Microsoft_VC100_CRT_x86.msm <-- This is likely the MSM you want if your app is 32-bit.
04/22/2011 01:14 PM 847,360 Microsoft_VC100_DebugCRT_x64.msm
04/22/2011 01:39 PM 801,792 Microsoft_VC100_DebugCRT_x86.msm
</code></pre>
<p>Two other alternatives:
Instead of copying MSVCRT100.dll into a system directory, copy it into the directory of the EXE app you are trying to launch that depends on this DLL. This isn't recommended, but won't run the risk of breaking other apps.</p>
<p>Another alternative. If you actually have the source code to the EXE that you are trying to launch, you can completely bypass all of this "install msvcrt100.dll" noise by just statically linking to it. In visual studio, it's the option in the project's propery dialog under C/C++ (under the Code Generation tab). Change "runtime library" from "Multi-threaded Dll" to just "Multi-threaded". This adds the /MT compiler switch.</p> |
57,048,978 | Failed to run jetifier React Native | <p>I tried to run react-native run-android and I got this error.</p>
<pre><code>info Running jetifier to migrate libraries to AndroidX. You can disable
it using "--no-jetifier" flag.
error Failed to run jetifier. Run CLI with --verbose flag for more details.
Error: spawnSync C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\jetifier\bin\jetify ENOENT
at Object.spawnSync (internal/child_process.js:1002:20)
at spawnSync (child_process.js:614:24)
at execFileSync (child_process.js:642:13)
at Object.runAndroid [as func] (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:101:41)
at Command.handleAction (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli\build\cliEntry.js:160:21)
at Command.listener (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:315:8)
at Command.emit (events.js:198:13)
at Command.parseArgs (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:651:12)
at Command.parse (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:474:21)
at setupAndRun (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli\build\cliEntry.js:210:24)
</code></pre> | 57,095,038 | 12 | 3 | null | 2019-07-16 01:31:28.023 UTC | 13 | 2022-02-10 07:54:32.377 UTC | null | null | null | null | 10,410,570 | null | 1 | 25 | reactjs|react-native | 64,408 | <p>Use this :</p>
<p>step 1: add these two lines in gradlew.properties <a href="https://developer.android.com/jetpack/androidx/migrate" rel="noreferrer">Visit for complete guideline</a></p>
<blockquote>
<p>android.useAndroidX=true <br />
android.enableJetifier=true</p>
</blockquote>
<p>step 2: use these commands</p>
<p>First of all remove node_modules folder and reinstall it using</p>
<pre class="lang-sh prettyprint-override"><code>npm install
</code></pre>
<p>or </p>
<pre class="lang-sh prettyprint-override"><code>yarn
</code></pre>
<p>and then</p>
<pre class="lang-sh prettyprint-override"><code>npm install --save-dev jetifier
npx jetify
npx react-native run-android
</code></pre>
<p>Call </p>
<pre class="lang-sh prettyprint-override"><code>npx jetify
</code></pre>
<p>every time when (your dependencies update or every time you install node_modules you have to jetify again)</p> |
45,798,899 | Preferred way of resetting a class in Python | <p>Based on <a href="https://codereview.stackexchange.com/a/173505/140805">this post on CodeReview</a>.</p>
<p>I have a class
<code>Foo</code> in Python (3), which of course includes a <code>__init__()</code> method. This class fires a couple of prompts and does its thing. Say I want to be able to reset <code>Foo</code> so I can start the procedure all over again.</p>
<p>What would be the preferred implementation?</p>
<p>Calling the <code>__init__()</code> method again</p>
<pre><code>def reset(self):
self.__init__()
</code></pre>
<p>or creating a new instance?</p>
<pre><code>def reset(self):
Foo()
</code></pre>
<p>I am not sure if creating a new instance of <code>Foo</code> leaves behind anything that might affect performance if <code>reset</code> is called many times. On the other hand <code>__init__()</code> might have side-effects if not all attributes are (re)defined in <code>__init__()</code>.</p>
<p>Is there a preferred way to do this?</p> | 45,801,366 | 4 | 8 | null | 2017-08-21 13:53:18.237 UTC | 9 | 2022-08-24 13:56:53.603 UTC | 2017-08-21 13:55:17.823 UTC | null | 2,689,986 | null | 6,822,618 | null | 1 | 30 | python|python-3.x|class | 40,177 | <p>Both are correct but the semantics are not implemented the same way.</p>
<p>To be able to reset an instance, I would write this (I prefere to call a custom method from <code>__init__</code> than the opposite, because <code>__init__</code> is a special method, but this is mainly a matter of taste):</p>
<pre><code>class Foo:
def __init__(self):
self.reset()
def reset(self):
# set all members to their initial value
</code></pre>
<p>You use it that way:</p>
<pre><code>Foo foo # create an instance
...
foo.reset() # reset it
</code></pre>
<p>Creating a new instance from scratch is in fact simpler because the class has not to implement any special method:</p>
<pre><code>Foo foo # create an instance
...
foo = Foo() # make foo be a brand new Foo
</code></pre>
<p>the old instance will be garbage collected if it is not used anywhere else</p>
<p>Both way can be used for <em>normal</em> classes where all initialization is done in <code>__init__</code>, but the second way is required for special classes that are customized at creation time with <code>__new__</code>, for example immutable classes.</p>
<hr>
<p>But beware, this code:</p>
<pre><code>def reset(self):
Foo()
</code></pre>
<p>will <strong>not</strong> do what you want: it will just create a new instance, and immediately delete it because it will go out of scope at the end of the method. Even <code>self = Foo()</code> would only set the local reference which would the same go out of scope (and the new instance destroyed) at the end of the methos.</p> |
18,683,750 | How to prepend classmethods | <p>This question directly relates to <a href="https://stackoverflow.com/questions/18682494/overriden-method-still-gets-called" title="complex couchbase question">this one</a>. But I tried to break it down to the base problem and I didn't want to enter even more text into the other question box. So here goes:</p>
<p>I know that I can include classmethods by extending the module ClassMethods and including it via the Module#include hook. But can I do the same with prepend? Here is my example:</p>
<p>class Foo:</p>
<pre><code>class Foo
def self.bar
'Base Bar!'
end
end
</code></pre>
<p>class Extensions:</p>
<pre><code>module Extensions
module ClassMethods
def bar
'Extended Bar!'
end
end
def self.prepended(base)
base.extend(ClassMethods)
end
end
# prepend the extension
Foo.send(:prepend, Extensions)
</code></pre>
<p>class FooE:</p>
<pre><code>require './Foo'
class FooE < Foo
end
</code></pre>
<p>and a simple startscript:</p>
<pre><code>require 'pry'
require './FooE'
require './Extensions'
puts FooE.bar
</code></pre>
<p>When I start the script I don't get <code>Extended Bar!</code> like I expect but rather <code>Base Bar!</code>. What do I need to change in order to work properly?</p> | 18,684,467 | 2 | 0 | null | 2013-09-08 12:38:15.003 UTC | 10 | 2015-09-01 14:37:11.41 UTC | 2017-05-23 12:03:02.377 UTC | null | -1 | null | 1,044,160 | null | 1 | 23 | ruby | 10,077 | <p>The problem is that even though you're prepending the module, <code>ClassMethods</code> is still getting <code>extend</code>ed in. You could do this to get what you want:</p>
<pre><code>module Extensions
module ClassMethods
def bar
'Extended Bar!'
end
end
def self.prepended(base)
class << base
prepend ClassMethods
end
end
end
</code></pre>
<p>Note that <code>Extensions</code> itself could be either prepended or included in <code>Foo</code>. The important part is prepending <code>ClassMethods</code>.</p> |
19,034,542 | How to open port in Linux | <p>I have installed and web application which is running on port 8080 on RHEL (centOS). I only have command line access to that machine. I have tried to access that application from my windows machine from which I am connected to server via command-line, but it is giving connection time out error.</p>
<p>Then I have tried to open port 8080. I have added following entry into the iptables.</p>
<blockquote>
<p>-A INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j ACCEPT</p>
</blockquote>
<p>After adding this into the iptables I have restarted it with -
<code>/etc/init.d/iptables restart</code></p>
<p>But still I am not able to access that application from my windows machine.</p>
<p>Am I doing any mistake or missing something?</p> | 19,034,727 | 2 | 3 | null | 2013-09-26 17:17:17.81 UTC | 28 | 2021-01-29 14:15:46.247 UTC | 2021-01-29 14:15:46.247 UTC | null | 2,399,470 | null | 2,399,470 | null | 1 | 67 | linux|tcp|centos|port | 275,234 | <p>First, you should disable <code>selinux</code>, edit file <code>/etc/sysconfig/selinux</code> so it looks like this:</p>
<pre><code>SELINUX=disabled
SELINUXTYPE=targeted
</code></pre>
<p>Save file and restart system.</p>
<p>Then you can add the new rule to <code>iptables</code>:</p>
<pre><code>iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
</code></pre>
<p>and restart iptables with <code>/etc/init.d/iptables restart</code></p>
<p>If it doesn't work you should check other network settings.</p> |
41,053,653 | Tomcat 8 is not able to handle get request with '|' in query parameters? | <p>I am using Tomcat 8. In one case I need to handle external request coming from external source where the request has a parameters where it is separated by <code>|</code>.</p>
<p>Request is looks like this:</p>
<p><code>http://localhost:8080/app/handleResponse?msg=name|id|</code></p>
<p>In this case I am getting following error.</p>
<pre><code>java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:467)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:667)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p><strong>EDIT 1</strong></p>
<p>It works with Apache Tomcat 8.0.30 but not with Tomcat 8.5</p> | 41,150,474 | 7 | 3 | null | 2016-12-09 05:27:28.063 UTC | 15 | 2020-09-23 14:08:57.363 UTC | 2016-12-14 22:45:32.007 UTC | null | 1,108,098 | null | 644,518 | null | 1 | 74 | java|tomcat|tomcat8|tomcat8.5 | 158,899 | <p>This behavior is introduced in all major Tomcat releases:</p>
<ul>
<li>Tomcat <strong>7.0.73</strong>, <strong>8.0.39</strong>, <strong>8.5.7</strong></li>
</ul>
<p>To fix, do one of the following:</p>
<ul>
<li>set <code>relaxedQueryChars</code> to allow this character
(recommended, <a href="https://stackoverflow.com/a/51212677/2757140">see Lincoln's answer</a>)</li>
<li>set <code>requestTargetAllow</code> option
(deprecated in Tomcat 8.5) (<a href="https://stackoverflow.com/a/44005213/2757140">see Jérémie's answer</a>).</li>
<li>you can downgrade to one of older versions (not recommended - security)</li>
</ul>
<hr>
<p>Based on <a href="https://tomcat.apache.org/tomcat-8.5-doc/changelog.html" rel="noreferrer">changelog</a>, those changes could affect this behavior:</p>
<p>Tomcat 8.5.3:</p>
<blockquote>
<p>Ensure that requests with HTTP method names that are not tokens (as required by RFC 7231) are rejected with a 400 response</p>
</blockquote>
<p>Tomcat 8.5.7:</p>
<blockquote>
<p>Add additional checks for valid characters to the HTTP request line parsing so invalid request lines are rejected sooner.</p>
</blockquote>
<hr>
<p><em>The best option (following the standard)</em> - you want to encode your URL on client:</p>
<pre><code>encodeURI("http://localhost:8080/app/handleResponse?msg=name|id|")
> http://localhost:8080/app/handleResponse?msg=name%7Cid%7C
</code></pre>
<p>or just query string:</p>
<pre><code>encodeURIComponent("msg=name|id|")
> msg%3Dname%7Cid%7C
</code></pre>
<p>It will secure you from other problematic characters (<a href="https://stackoverflow.com/a/13500078/2757140">list of invalid URI characters</a>).</p> |
40,835,953 | How to find AMI ID of CentOS 7 image in AWS Marketplace? | <p>I have been launching EC2 instances by logging in to the AWS site, hitting the "Launch" button and following the proscribed steps. Now I'd like to launch instance from an Ansible script, and to do this I (think I) need the AMI ID of the image I wish to launch.</p>
<p>The problem is that I am launching an image from the "Marketplace", and I cannot find the AMI ID. In particular I'm using the Centos 7 image. This is easy to find in the web interface, just go to the marketplace and search for "centos", the image I want is the first one found, but the information provided about the image doesn't seem to include the AMI ID that I need to launch it from a script. The workaround is to manually launch an image, and then when inspecting the running image, the AMI ID is given. But is there an easier way to find it?</p> | 40,836,165 | 4 | 4 | null | 2016-11-28 01:30:49.327 UTC | 16 | 2020-04-24 15:11:54.667 UTC | 2016-11-28 02:25:25.317 UTC | null | 775,544 | null | 1,425,406 | null | 1 | 30 | amazon-web-services|amazon-ec2|centos7|amazon-ami | 40,055 | <p>CentOS publishes their AMI product codes to their <a href="https://wiki.centos.org/Cloud/AWS" rel="noreferrer">wiki</a>. The wiki provides the following information for the latest CentOS 7 AMI:</p>
<ul>
<li>Owner: <code>aws-marketplace</code></li>
<li>Product Code: <code>aw0evgkw8e5c1q413zgy5pjce</code></li>
</ul>
<p>Using this information, we can query <a href="http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html" rel="noreferrer">describe-images</a> with the AWS CLI:</p>
<p><strong>Example:</strong></p>
<pre><code>aws ec2 describe-images \
--owners 'aws-marketplace' \
--filters 'Name=product-code,Values=aw0evgkw8e5c1q413zgy5pjce' \
--query 'sort_by(Images, &CreationDate)[-1].[ImageId]' \
--output 'text'
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>ami-6d1c2007
</code></pre>
<p>This query returns a single AMI ID, selected by sorting the collection by creation date and then selecting the last (most recent) element in the collection. </p>
<p>Per the CentOS wiki, <code>multiple AMI ids may be associated with a product key</code>, so while this query would currently only return a single AMI because only one matching this product currently exists... in the future if a new AMI is created for this product code for any reason this query will return it instead.</p> |
709,035 | DataTable to List<object> | <p>How do I take a DataTable and convert it to a List?</p>
<p>I've included some code below in both C# and VB.NET, the issue with both of these is that we create a new object to return the data, which is very costly. I need to return a reference to the object.</p>
<p>The DataSetNoteProcsTableAdapters.up_GetNoteRow object does implement the INote interface.</p>
<p>I am using ADO.NET, along with .NET 3.5</p>
<p>c# code</p>
<pre><code>public static IList<INote> GetNotes()
{
DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter adapter =
new DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter();
DataSetNoteProcs.up_GetNoteDataTable table =
new DataSetNoteProcs.up_GetNoteDataTable();
IList<INote> notes = new List<INote>();
adapter.Connection = DataAccess.ConnectionSettings.Connection;
adapter.Fill(table);
foreach (DataSetNoteProcs.up_GetNoteRow t in table) {
notes.Add((INote)t);
}
return notes;
}
</code></pre>
<p>VB.NET Code</p>
<pre><code>Public Shared Function GetNotes() As IList(Of INote)
Dim adapter As New DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter
Dim table As New DataSetNoteProcs.up_GetNoteDataTable
Dim notes As IList(Of INote) = New List(Of INote)
adapter.Connection = DataAccess.ConnectionSettings.Connection
adapter.Fill(table)
For Each t As DataSetNoteProcs.up_GetNoteRow In table
notes.Add(CType(t, INote))
Next
Return notes
End Function
</code></pre> | 709,702 | 7 | 4 | null | 2009-04-02 09:45:09.047 UTC | 5 | 2019-09-23 14:35:11.303 UTC | 2009-04-02 10:07:11.38 UTC | Luke | 55,847 | null | 58,309 | null | 1 | 7 | c#|dataset | 69,796 | <p>No, creating a list is not costly. Compared to creating the data table and fetching the data from the database, it's very cheap.</p>
<p>You can make it even cheaper by creating the list after populating the table, so that you can set the initial capacity to the number of rows that you will put in it:</p>
<pre><code>IList<INote> notes = new List<INote>(table.Rows.Count);
</code></pre> |
1,243,150 | php sessions to authenticate user on login form | <p>I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.</p>
<pre><code>session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
} else {
header('Location:http://website.com/fail.php');
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
</code></pre>
<p>Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong? </p>
<p><strong>NOTE</strong> the authed function worked fine before i added the session code.</p> | 1,244,097 | 7 | 0 | null | 2009-08-07 06:06:25.447 UTC | 10 | 2017-11-16 08:30:12.897 UTC | 2009-08-07 06:22:55.243 UTC | null | 138,475 | null | 115,949 | null | 1 | 8 | php|session | 49,903 | <p>what about using this to setup session </p>
<pre><code>session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}
</code></pre>
<p>and at the top of each "secure" page use this code:</p>
<pre><code>session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
</code></pre>
<p>this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:</p>
<pre><code>session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");
</code></pre> |
838,344 | Algorithm for finding nearby points? | <p>Given a set of several million points with x,y coordinates, what is the algorithm of choice for quickly finding the top 1000 nearest points from a location? "Quickly" here means about 100ms on a home computer.</p>
<p>Brute force would mean doing millions of multiplications and then sorting them. While even a simple Python app could do that in less than a minute, it is still too long for an interactive application.</p>
<p>The bounding box for the points will be known, so partitioning the space into a simple grid would be possible. However the points are distributed somewhat unevenly, so I suspect most grid squares would be empty and then suddenly some of them would contain a large portion of the points.</p>
<p>Edit: Does not have to be exact, actually can be quite inaccurate. It wouldn't be a huge deal if the top 1000 are actually just some random points from the top 2000 for example.</p>
<p>Edit: Set of points rarely changes.</p> | 838,358 | 7 | 2 | null | 2009-05-08 05:20:01.283 UTC | 14 | 2010-01-21 04:02:49.963 UTC | 2009-05-08 05:37:12.693 UTC | null | 8,005 | null | 8,005 | null | 1 | 22 | algorithm|gis|partitioning|distance|linear-algebra | 10,863 | <p>How about using <a href="http://en.wikipedia.org/wiki/Quadtree" rel="noreferrer">quadtree</a>?</p>
<p>You divide area to rectangles, if area has low density of points, rectangles are large, and if area has high density of points, rectangles will be small. You recursively subdivide each rectangle to four sub rectangles until rectangles are small enough or contain few enough points.</p>
<p>You can then start looking at points in rectangles near the location, and move outwards until you have found your 1000 points.</p>
<p>Code for this could get somewhat complex, so maybe you should try first with the simple grid and see if it is fast enough.</p> |
918,019 | .net UrlEncode - lowercase problem | <p>I'm working on a data transfer for a gateway which requires me to send data in UrlEncoded form. However, .net's UrlEncode creates lowercase tags, and it breaks the transfer (Java creates uppercase).</p>
<p>Any thoughts how can I force .net to do uppercase UrlEncoding?</p>
<p>update1:</p>
<p>.net out:</p>
<pre><code>dltz7UK2pzzdCWJ6QOvWXyvnIJwihPdmAioZ%2fENVuAlDQGRNCp1F
</code></pre>
<p>vs Java's:</p>
<pre><code>dltz7UK2pzzdCWJ6QOvWXyvnIJwihPdmAioZ%2FENVuAlDQGRNCp1F
</code></pre>
<p>(it is a base64d 3DES string, i need to maintain it's case).</p> | 918,162 | 7 | 4 | null | 2009-05-27 21:08:04.453 UTC | 6 | 2021-04-26 13:37:55.337 UTC | 2009-05-27 21:26:57.973 UTC | null | 65,189 | null | 65,189 | null | 1 | 30 | .net|urlencode | 19,054 | <p>I think you're stuck with what C# gives you, and getting errors suggests a poorly implemented UrlDecode function on the other end. </p>
<p>With that said, you should just need to loop through the string and uppercase only the two characters following a % sign. That'll keep your base64 data intact while massaging the encoded characters into the right format:</p>
<pre><code>public static string UpperCaseUrlEncode(string s)
{
char[] temp = HttpUtility.UrlEncode(s).ToCharArray();
for (int i = 0; i < temp.Length - 2; i++)
{
if (temp[i] == '%')
{
temp[i + 1] = char.ToUpper(temp[i + 1]);
temp[i + 2] = char.ToUpper(temp[i + 2]);
}
}
return new string(temp);
}
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.