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
48,558,681
Add custom header to apollo client polling request
<p>I am using the <code>apollo-client</code> library to query data from my <code>Graphql</code> server. Some of the queries are sent to the server every 5 seconds through apollo polling ability.</p> <p>Is there a generic way to add a custom header to all requests that are sent by my polling client?</p>
48,578,567
3
1
null
2018-02-01 08:53:17.973 UTC
12
2022-02-28 22:39:56.41 UTC
2020-02-26 19:59:30.477 UTC
null
319,969
null
7,360,870
null
1
28
javascript|graphql|apollo|apollo-client|graphql-js
42,538
<h1>Two Solutions</h1> <p>There are two ways to do that. One is <strong>quick and easy</strong> and will work for a specific query with some limitation, and the other is a <strong>general solution</strong> that is safer and can work for multiple queries.</p> <h2>Quick and Easy Solution</h2> <p><strong>Advantages</strong></p> <ul> <li>it's quick</li> <li>and... easy</li> </ul> <p>When you configure your query you can configure it using its <code>options</code> field, that has a <code>context</code> field. The value of <code>context</code> will be processed by the network chain. The <code>context</code> itself is not sent to the server, but if you add a <code>headers</code> field to it, it will be used in the HTTP request.</p> <p><strong>Example</strong>:</p> <pre><code>const someQuery = graphql(gql`query { ... }`, { options: { context: { headers: { "x-custom-header": "pancakes" // this header will reach the server } }, // ... other options } }) </code></pre> <h2>General Solution using a Network Link middleware</h2> <p>With Apollo you can add an Apollo Link that will act as a middleware and add a custom header to the request based on the <code>context</code> that was set by your query operation.</p> <p>From the docs:</p> <blockquote> <p>Apollo Client has a pluggable network interface layer, which can let you configure how queries are sent over HTTP</p> </blockquote> <p>Read more about <a href="https://www.apollographql.com/docs/react/networking/network-layer/" rel="noreferrer" title="Apollo GraphQL - Network layer (Apollo Link)">Apollo Link, the network link and Middleware concepts</a>.</p> <p><strong>Advantages</strong>:</p> <ul> <li>The middleware's logic can be used by any graphql operation (you set the condition)</li> <li>Your queries don't need to "care" or know about HTTP headers</li> <li>You can do more processing before deciding if and what headers to add to the request.</li> <li>and more..</li> </ul> <p><strong>Setting the context</strong></p> <p>Same as the quick and easy solution, only this time we don't set the <code>headers</code> directly:</p> <pre><code> { options: { context: { canHazPancakes: true //this will not reach the server } } } </code></pre> <p><strong>Adding the middleware</strong></p> <p>Apollo has a specific middleware for setting the context <code>apollo-link-context</code> (the same can be achieved with a more general middleware).</p> <pre><code>import {setContext} from 'apollo-link-context' //... const pancakesLink = setContext((operation, previousContext) =&gt; { const { headers, canHazPancakes } = previousContext if (!canHazPancakes) { return previousContext } return { ...previousContext, headers: { ...headers, "x-with-pancakes": "yes" //your custom header } } }) </code></pre> <p>Don't forget to concat it to the network chain somewhere before your http link</p> <pre><code>const client = new ApolloClient({ // ... link: ApolloLink.from([ pancakesLink, &lt;yourHttpLink&gt; ]) }) </code></pre> <p>There is another useful example in the docs: <a href="https://www.apollographql.com/docs/react/networking/network-layer/#middleware" rel="noreferrer">using a middleware for authentication</a>.</p> <p><strong>That's it!</strong> You should get some pancakes from the server now. Hope this helps.</p>
39,827,054
Spring JPA repository transactionality
<p>1 quick question on Spring JPA repositories transactionality. I have a service that is not marked as transactional and calls Spring JPA repository method</p> <pre><code>userRegistrationRepository.deleteByEmail(email); </code></pre> <p>And it is defined as</p> <pre><code>@Repository public interface UserRegistrationRepository extends JpaRepository&lt;UserRegistration, Long&gt; { UserRegistration findByEmail(String email); void deleteByEmail(String email); } </code></pre> <p>The problem is that it fails with "<em>No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call; nested exception is javax.persistence.TransactionRequiredException</em>" exception.</p> <p>Ok, I can solve it by marking the service <strong>or</strong> <em>deleteByEmail(..)</em> method as transactional, but I just can't understand why it crashes now. Spring documentation explicitly states that "<em>CRUD methods on repository instances are transactional by default.</em>" (<a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions" rel="noreferrer">http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions</a>), but apparently this one is not... So Is this statement related to only members of <code>CrudRepository</code>?</p> <p>ps: that's for Spring Data JPA 1.9.4</p>
39,829,964
1
0
null
2016-10-03 08:07:53.44 UTC
13
2019-08-27 23:27:05.27 UTC
null
null
null
null
3,195,653
null
1
33
java|jpa|spring-data|spring-transactions
31,787
<p>You are right. Only CRUD methods (<code>CrudRepository</code> methods) are by default marked as transactional. If you are using custom query methods you should explicitly mark it with <code>@Transactional</code> annotation. </p> <pre><code>@Repository public interface UserRegistrationRepository extends JpaRepository&lt;UserRegistration, Long&gt; { UserRegistration findByEmail(String email); @Transactional void deleteByEmail(String email); } </code></pre> <p>You should also be aware about consequences of marking repository interface methods instead of service methods. If you are using default transaction propagation configuration (<code>Propagation.REQUIRED</code>) then: </p> <blockquote> <p>The transaction configuration at the repositories will be neglected then as the outer transaction configuration determines the actual one used.</p> </blockquote> <p><a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions" rel="noreferrer">http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions</a></p> <p>If you want more information about how it is implemented, take a look at default <code>CrudRepository</code> / <code>JpaRepository</code> implementation - <code>SimpleJpaRepository</code> (which you are probably using):</p> <p><a href="https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java" rel="noreferrer">https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java</a> </p> <p>The interesting lines are here:</p> <pre class="lang-java prettyprint-override"><code>@Transactional(readOnly = true) public class SimpleJpaRepository&lt;T, ID&gt; implements JpaRepositoryImplementation&lt;T, ID&gt; { </code></pre> <p>and some of transactional methods here:</p> <pre class="lang-java prettyprint-override"><code>@Transactional public void deleteById(ID id) { </code></pre> <pre><code>@Transactional public &lt;S extends T&gt; S save(S entity) { </code></pre>
39,700,330
Handling very large data with mysql
<p>Sorry for the long post!</p> <p>I have a database containing ~30 tables (InnoDB engine). Only two of these tables, namely, "transaction" and "shift" are quite large (the first one have 1.5 million rows and shift has 23k rows). Now everything works fine and I don't have problem with the current database size. </p> <p>However, we will have a similar database (same datatypes, design ,..) but much larger, e.g., the "transaction" table will have about <strong>1 billion records</strong> (about 2,3 million transaction per day) and we are thinking about how we should deal with such volume of data in MySQL? (it is both read and write intensive). I read a lot of related posts to see if Mysql (and more specifically InnoDB engine) can perform well with billions of records, but still I have some questions. Some of those related posts that I've read are in the following:</p> <ul> <li><a href="https://dba.stackexchange.com/questions/20335/can-mysql-reasonably-perform-queries-on-billions-of-rows">Can MySQL reasonably perform queries on billions of rows?</a></li> <li><a href="https://stackoverflow.com/questions/6121905/is-innodb-mysql-5-5-8-the-right-choice-for-multi-billion-rows">Is InnoDB (MySQL 5.5.8) the right choice for multi-billion rows?</a></li> <li><a href="https://stackoverflow.com/questions/2794736/best-data-store-for-billions-of-rows?noredirect=1&amp;lq=1">Best data store for billions of rows</a></li> <li><a href="https://stackoverflow.com/questions/1276/how-big-can-a-mysql-database-get-before-performance-starts-to-degrade">How big can a MySQL database get before performance starts to degrade</a></li> <li><a href="https://www.percona.com/blog/2006/06/09/why-mysql-could-be-slow-with-large-tables/" rel="noreferrer">Why MySQL could be slow with large tables?</a></li> <li><a href="https://stackoverflow.com/questions/14733462/can-mysql-handle-tables-which-will-hold-about-300-million-records?noredirect=1&amp;lq=1">Can Mysql handle tables which will hold about 300 million records?</a></li> </ul> <p>What I've understood so far to improve the performance for very large tables:</p> <ol> <li>(for innoDB tables which is my case) increasing the <code>innodb_buffer_pool_size</code> (e.g., up to 80% of RAM). Also, I found some other MySQL performance tunning settings <a href="https://www.percona.com/blog/2014/01/28/10-mysql-performance-tuning-settings-after-installation/" rel="noreferrer">here in percona blog</a></li> <li>having proper indexes on the table (using EXPLAN on queries)</li> <li>partitioning the table</li> <li>MySQL Sharding or clustering</li> </ol> <p>Here are my questions/confusions:</p> <ul> <li><p>About partitioning, I have some doubts whether we should use it or not. On one hand many people suggested it to improve performance when table is very large. On the other hand, I've read many posts saying it does not improve query performance and it does not make queries run faster (e.g., <a href="https://stackoverflow.com/questions/4249073/partitioning-for-query-performance-in-sql-server-2008/4249447#4249447">here</a> and <a href="https://dba.stackexchange.com/questions/141175/partitioning-a-large-table-has-not-improved-performance-why">here</a>). Also, I read in <a href="https://dev.mysql.com/doc/refman/5.6/en/partitioning-limitations-storage-engines.html" rel="noreferrer">MySQL Reference Manual</a> that <strong>InnoDB foreign keys and MySQL partitioning are not compatible</strong> (we have foreign keys). </p></li> <li><p>Regarding indexes, right now they perform well, but as far as I understood, for very large tables indexing is more restrictive (as Kevin Bedell mentioned in his answer <a href="https://dba.stackexchange.com/questions/20335/can-mysql-reasonably-perform-queries-on-billions-of-rows">here</a>). Also, indexes speed up reads while slow down write (insert/update). So, for the new similar project that we will have this large DB, should we first insert/load all the data and then create indexes? (to speed up the insert) </p></li> <li><p>If we cannot use partitioning for our big table ("transaction" table), what is an alternative option to improve the performance? (except MySQl variable settings such as <code>innodb_buffer_pool_size</code>). Should we use Mysql clusters? (we have also lots of joins)</p></li> </ul> <h1>EDIT</h1> <p>This is the <code>show create table</code> statement for our largest table named "transaction": </p> <pre><code> CREATE TABLE `transaction` ( `id` int(11) NOT NULL AUTO_INCREMENT, `terminal_transaction_id` int(11) NOT NULL, `fuel_terminal_id` int(11) NOT NULL, `fuel_terminal_serial` int(11) NOT NULL, `xboard_id` int(11) NOT NULL, `gas_station_id` int(11) NOT NULL, `operator_id` text NOT NULL, `shift_id` int(11) NOT NULL, `xboard_total_counter` int(11) NOT NULL, `fuel_type` int(11) NOT NULL, `start_fuel_time` int(11) NOT NULL, `end_fuel_time` int(11) DEFAULT NULL, `preset_amount` int(11) NOT NULL, `actual_amount` int(11) DEFAULT NULL, `fuel_cost` int(11) DEFAULT NULL, `payment_cost` int(11) DEFAULT NULL, `purchase_type` int(11) NOT NULL, `payment_ref_id` text, `unit_fuel_price` int(11) NOT NULL, `fuel_status_id` int(11) DEFAULT NULL, `fuel_mode_id` int(11) NOT NULL, `payment_result` int(11) NOT NULL, `card_pan` text, `state` int(11) DEFAULT NULL, `totalizer` int(11) NOT NULL DEFAULT '0', `shift_start_time` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `terminal_transaction_id` (`terminal_transaction_id`,`fuel_terminal_id`,`start_fuel_time`) USING BTREE, KEY `start_fuel_time_idx` (`start_fuel_time`), KEY `fuel_terminal_idx` (`fuel_terminal_id`), KEY `xboard_idx` (`xboard_id`), KEY `gas_station_id` (`gas_station_id`) USING BTREE, KEY `purchase_type` (`purchase_type`) USING BTREE, KEY `shift_start_time` (`shift_start_time`) USING BTREE, KEY `fuel_type` (`fuel_type`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1665335 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT </code></pre> <p>Thanks for your time,</p>
39,714,657
3
0
null
2016-09-26 10:23:38.333 UTC
40
2021-11-11 17:07:57.45 UTC
2017-05-23 12:25:39.113 UTC
null
-1
null
2,312,801
null
1
56
mysql|database|performance|indexing|partitioning
75,077
<ul> <li><p>Can MySQL reasonably perform queries on billions of rows? -- MySQL can 'handle' billions of rows. &quot;Reasonably&quot; depends on the queries; let's see them.</p> </li> <li><p>Is InnoDB (MySQL 5.5.8) the right choice for multi-billion rows? -- 5.7 has some improvements, but 5.5 is pretty good, in spite of being <strike>nearly 6</strike> 8 years old, and <strike>on the verge of</strike> no longer being supported.</p> </li> <li><p>Best data store for billions of rows -- If you mean 'Engine', then InnoDB.</p> </li> <li><p>How big can a MySQL database get before the performance starts to degrade -- Again, that depends on the queries. I can show you a 1K row table that will meltdown; I have worked with billion-row tables that hum along.</p> </li> <li><p>Why MySQL could be slow with large tables? -- range scans lead to I/O, which is the slow part.</p> </li> <li><p>Can Mysql handle tables which will hold about 300 million records? -- again, yes. The limit is somewhere around a trillion rows.</p> </li> <li><p>(for InnoDB tables which is my case) increasing the innodb_buffer_pool_size (e.g., up to 80% of RAM). Also, I found some other MySQL performance tunning settings here in Percona blog -- yes</p> </li> <li><p>having proper indexes on the table (using EXPLAIN on queries) -- well, let's see them. There are a lot of mistakes that can be made in this <em>critical</em> area.</p> </li> <li><p>partitioning the table -- &quot;Partitioning is not a panacea!&quot; I harp on that in <a href="https://mariadb.com/kb/en/mariadb/partition-maintenance/" rel="noreferrer"><em>my blog</em></a></p> </li> <li><p>MySQL Sharding -- Currently this is DIY</p> </li> <li><p>MySQL clustering -- Currently the best answer is some Galera-based option (PXC, MariaDB 10, DIY w/Oracle). Oracle's &quot;Group Replication&quot; is a viable contender.</p> </li> <li><p>Partitioning does not support <code>FOREIGN KEY</code> or &quot;global&quot; <code>UNIQUE</code>.</p> </li> <li><p>UUIDs, at the scale you are talking about, will not just slow down the system, but actually kill it. <a href="https://mariadb.com/kb/en/guiduuid-performance/" rel="noreferrer"><em>Type 1 UUIDs</em></a> may be a workaround.</p> </li> <li><p>Insert and index-build speed -- There are too many variations to give a single answer. Let's see your tentative <code>CREATE TABLE</code> and how you intend to feed the data in.</p> </li> <li><p>Lots of joins -- &quot;Normalize, but don't over-normalize.&quot; In particular, do not normalize datetimes or floats or other &quot;continuous&quot; values.</p> </li> <li><p>Do build <a href="https://mariadb.com/kb/en/mariadb/data-warehousing-summary-tables/" rel="noreferrer"><em>summary tables</em></a></p> </li> <li><p>2,3 million transactions per day -- If that is 2.3M <em>inserts</em> (30/sec), then there is not much of a performance problem. If more complex, then RAID, SSD, batching, etc, may be necessary.</p> </li> <li><p>deal with such volume of data -- If most activity is with the &quot;recent&quot; rows, then the buffer_pool will nicely 'cache' the activity, thereby avoiding I/O. If the activity is &quot;random&quot;, then MySQL (or <em>anyone</em> else) will have I/O issues.</p> </li> <li><p>Shrinking the datatypes helps in a table like yours. I doubt if you need 4 bytes to specify <code>fuel_type</code>. There are multiple 1-byte approaches.</p> </li> </ul>
33,504,798
How to find the master URL for an existing spark cluster
<p>Currently I am running my program as</p> <pre><code>val conf = new SparkConf() .setAppName("Test Data Analysis") .setMaster("local[*]") .set("spark.executor.memory", "32g") .set("spark.driver.memory", "32g") .set("spark.driver.maxResultSize", "4g") </code></pre> <p>Even though I am running on a cluster of 5 machines (each with 376 GB Physical RAM). my program errors out with <code>java.lang.OutOfMemoryError: Java heap space</code></p> <p>My data sizes are big... but not so big that they exceed 32 GB Executor memory * 5 nodes.</p> <p>I suspect it may be because I am using "local" as my master. I have seen documentation say use <code>spark://machinename:7070</code></p> <p>However I want to know for my cluster... how do I determine this URL and port</p> <p>EDIT: I can see that the documentation talks about running something called "spark-master.sh" in order to make a node as master.</p> <p>in my case the spark cluster was setup/maintained by someone else and so I don't want to change topology by starting my own master.</p> <p>How can I query and find out which node is the existing master. </p> <p>I already tried picking up a random node in the cluster and then try 'spark://node:7077' but this does not work and gives error</p> <pre><code>[15/11/03 20:06:21 WARN AppClient$ClientActor: Could not connect to akka.tcp://sparkMaster@node:7077: akka.remote.EndpointAssociationException: Association failed with [akka.tcp://sparkMaster@node:7077] </code></pre>
36,227,237
4
0
null
2015-11-03 16:52:55.857 UTC
6
2019-02-11 04:13:21.23 UTC
2015-11-03 20:10:15.01 UTC
null
337,134
null
337,134
null
1
31
apache-spark
58,886
<p>I found that doing <code>--master yarn-cluster</code> works best. this makes sure that spark uses all the nodes of the hadoop cluster.</p>
33,827,179
Python decimal.InvalidOperation error
<p>i'm always getting this error when running something like this:</p> <pre><code>from decimal import * getcontext().prec =30 b=("2/3") Decimal(b) </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "Test.py", line 6, in &lt;module&gt; Decimal(b) decimal.InvalidOperation: [&lt;class 'decimal.ConversionSyntax'&gt;] </code></pre> <p>Also, why do i get this result from the console?</p> <pre><code>&gt;&gt;&gt; Decimal(2/3) Decimal('0.66666666666666662965923251249478198587894439697265625') </code></pre> <p>Thanks</p>
33,827,268
2
0
null
2015-11-20 12:50:37.08 UTC
0
2019-07-16 13:40:03.603 UTC
2015-11-20 12:57:30.143 UTC
null
953,482
null
5,238,305
null
1
16
python|python-3.x|math
55,954
<p><code>Decimal</code>'s initializer can't accept strings with a slash in them. Informally, the string has to look like a single number. <a href="https://docs.python.org/3/library/decimal.html?#decimal.Decimal" rel="noreferrer">This table</a> shows the proper format for string arguments. If you want to calculate 2/3, do</p> <pre><code>&gt;&gt;&gt; Decimal(2)/Decimal(3) Decimal('0.6666666666666666666666666667') </code></pre> <p><code>Decimal(2/3)</code> gives <code>Decimal('0.66666666666666662965923251249478198587894439697265625')</code> because 2/3 evaluates to a floating point number, and floats have inherently limited precision. That's the closest the computer can get to representing <code>2/3</code> using a float.</p>
47,449,741
Plotting multiple lines in python
<p>I am new in Python and I want to plot multiple lines in one graph like in the figure below. </p> <p><a href="https://i.stack.imgur.com/PzfCi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PzfCi.png" alt="enter image description here"></a></p> <p>I have tried write simple plotting code like this: <a href="https://i.stack.imgur.com/YtpNX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YtpNX.png" alt="enter image description here"></a></p> <p>I know these parameters</p> <pre><code> # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') </code></pre> <p>But I have a lot of lines such in the first figure, what kind of parameters which I can use to plotting like the first figure. </p> <p>Thank you</p>
47,450,185
2
0
null
2017-11-23 07:24:46.323 UTC
2
2017-11-23 10:02:00.37 UTC
null
null
null
null
3,699,370
null
1
2
python|matplotlib|plot|plotly|linechart
39,751
<p>There are many options for line styles and marker in MPL. Have a look <a href="https://matplotlib.org/api/markers_api.html" rel="noreferrer">here</a>, <a href="https://matplotlib.org/1.3.1/examples/pylab_examples/line_styles.html" rel="noreferrer">here</a> and <a href="https://matplotlib.org/examples/lines_bars_and_markers/marker_reference.html" rel="noreferrer">here</a>.</p> <p>For your specific example (I quickly made up some functions and roughly plotted the first few examples):</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x=np.arange(6) fig=plt.figure() fig.show() ax=fig.add_subplot(111) ax.plot(x,x,c='b',marker="^",ls='--',label='GNE',fillstyle='none') ax.plot(x,x+1,c='g',marker=(8,2,0),ls='--',label='MMR') ax.plot(x,(x+1)**2,c='k',ls='-',label='Rand') ax.plot(x,(x-1)**2,c='r',marker="v",ls='-',label='GMC') ax.plot(x,x**2-1,c='m',marker="o",ls='--',label='BSwap',fillstyle='none') ax.plot(x,x-1,c='k',marker="+",ls=':',label='MSD') plt.legend(loc=2) plt.draw() </code></pre> <p>This should give you something like this.</p> <p><a href="https://i.stack.imgur.com/JEb3q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JEb3q.png" alt="enter image description here"></a></p>
21,771,133
Finding non-numeric rows in dataframe in pandas?
<p>I have a large dataframe in pandas that apart from the column used as index is supposed to have only numeric values:</p> <pre><code>df = pd.DataFrame({'a': [1, 2, 3, 'bad', 5], 'b': [0.1, 0.2, 0.3, 0.4, 0.5], 'item': ['a', 'b', 'c', 'd', 'e']}) df = df.set_index('item') </code></pre> <p>How can I find the row of the dataframe <code>df</code> that has a non-numeric value in it? </p> <p>In this example it's the fourth row in the dataframe, which has the string <code>'bad'</code> in the <code>a</code> column. How can this row be found programmatically?</p>
21,772,078
7
0
null
2014-02-14 04:54:02.58 UTC
25
2022-02-17 05:27:06.697 UTC
2017-09-11 17:49:54.727 UTC
null
2,137,255
user248237
null
null
1
81
python|pandas|dataframe
147,715
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.isreal.html" rel="noreferrer"><code>np.isreal</code></a> to check the type of each element (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html" rel="noreferrer">applymap</a> applies a function to each element in the DataFrame):</p> <pre><code>In [11]: df.applymap(np.isreal) Out[11]: a b item a True True b True True c True True d False True e True True </code></pre> <p>If all in the row are True then they are all numeric:</p> <pre><code>In [12]: df.applymap(np.isreal).all(1) Out[12]: item a True b True c True d False e True dtype: bool </code></pre> <p>So to get the subDataFrame of rouges, (Note: the negation, ~, of the above finds the ones which have at least one rogue non-numeric):</p> <pre><code>In [13]: df[~df.applymap(np.isreal).all(1)] Out[13]: a b item d bad 0.4 </code></pre> <p>You could also find the location of the <em>first</em> offender you could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html" rel="noreferrer">argmin</a>:</p> <pre><code>In [14]: np.argmin(df.applymap(np.isreal).all(1)) Out[14]: 'd' </code></pre> <p>As <a href="https://stackoverflow.com/users/2487184/ct-zhu">@CTZhu</a> points out, it may be slightly faster to <a href="http://docs.python.org/2/library/functions.html#isinstance" rel="noreferrer">check whether it's an instance of</a> either int or float (there is some additional overhead with np.isreal):</p> <pre><code>df.applymap(lambda x: isinstance(x, (int, float))) </code></pre>
27,420,023
java.rmi.ConnectException: Connection refused to host: 127.0.0.1
<p>I've tried to used RMI, here is server side. at first it worked without any exception, but now after three times whenever i try to run the below code, i will get some errors</p> <p>The code is:</p> <pre><code>import java.rmi.server.UnicastRemoteObject; /** * Created by elyas on 12/11/14 AD. */ public class LogicImplement extends UnicastRemoteObject implements Logic { public LogicImplement() throws Exception { java.rmi.registry.LocateRegistry.createRegistry(6060); java.rmi.Naming.rebind("Object1",this); } @Override public int sum(int a, int b) throws Exception { int result = a + b; System.out.println("ana sum executed"); return result; } public static void main(String[] args) { try { LogicImplement logicImplement = new LogicImplement(); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <p>The error is like this: i've tried to change the Object1 to for example Object2, but again i will get error, also i change the port number...</p> <p>what is solution?</p> <pre><code>java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is: java.net.ConnectException: Connection refused at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:341) at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source) at java.rmi.Naming.rebind(Naming.java:177) at LogicImplement.&lt;init&gt;(LogicImplement.java:12) at LogicImplement.main(LogicImplement.java:27) 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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.&lt;init&gt;(Socket.java:425) at java.net.Socket.&lt;init&gt;(Socket.java:208) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) ... 12 more </code></pre>
27,440,761
4
0
null
2014-12-11 10:02:22.223 UTC
1
2017-12-21 01:01:07.32 UTC
null
null
null
null
3,881,354
null
1
4
java|port|rmi|server
39,622
<p>The Answer was very simple, By default, the registry runs on port 1099. To start the registry on a different port, specify the port number on the command line. Do not forget to unset your CLASSPATH environment variable. for more information check this link: <a href="http://docs.oracle.com/javase/tutorial/rmi/running.html" rel="nofollow">Running the Example Programs</a></p> <p>** So for fixing this code i must change the port number form 6060 to 1099</p> <p>notice that: if 1099 is used by other services you have to test 1100, and if 1100 is used too, you have yo use 1101 and so on. :-)</p>
42,733,986
How to wait and fade an element out?
<p>I have an alert box to confirm that the user has successfully subscribed:</p> <pre><code>&lt;div className="alert alert-success"&gt; &lt;strong&gt;Success!&lt;/strong&gt; Thank you for subscribing! &lt;/div&gt; </code></pre> <p>When a user sends an email, I'm changing the "subscribed" state to true.</p> <p>What I want is to:</p> <ul> <li>Show the alert box when the subscribed state is true</li> <li>Wait for 2 seconds</li> <li>Make it fade out</li> </ul> <p>How can I do this?</p>
42,734,261
3
0
null
2017-03-11 10:19:51.023 UTC
2
2022-09-15 15:55:23.69 UTC
2022-09-15 15:55:23.69 UTC
null
1,264,804
null
2,713,632
null
1
17
reactjs
46,492
<p>May 2021 update: as tolga and Alexey Nikonov correctly noted in their answers, it’s possible to give away control over how long the alert is being shown (in the original question, 2 seconds) to the <code>transition-delay</code> property and a smart component state management based on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/transitionend_event" rel="noreferrer"><code>transitionend</code> DOM event</a>. Also, <a href="https://reactjs.org/docs/hooks-intro.html" rel="noreferrer">hooks</a> are these days recommended to handle component’s internal state, not <a href="https://reactjs.org/docs/react-component.html#setstate" rel="noreferrer"><code>setState</code></a>. So I updated my answer a bit:</p> <pre><code>function App(props) { const [isShowingAlert, setShowingAlert] = React.useState(false); return ( &lt;div&gt; &lt;div className={`alert alert-success ${isShowingAlert ? 'alert-shown' : 'alert-hidden'}`} onTransitionEnd={() =&gt; setShowingAlert(false)} &gt; &lt;strong&gt;Success!&lt;/strong&gt; Thank you for subscribing! &lt;/div&gt; &lt;button onClick={() =&gt; setShowingAlert(true)}&gt; Show alert &lt;/button&gt; (and other children) &lt;/div&gt; ); } </code></pre> <p>The delay is then specified in the <code>alert-hidden</code> class in CSS:</p> <pre><code>.alert-hidden { opacity: 0; transition: all 250ms linear 2s; // &lt;- the last value defines transition-delay } </code></pre> <p>The actual change of <code>isShowingAlert</code> is, in fact, near-instant: from false to true, then immediately from true to false. But because the transition to opacity: 0 is delayed by 2 seconds, the user sees the message for this duration.</p> <p>Feel free to play around with <a href="https://codepen.io/rishatmuhametshin/pen/BaWzLdX" rel="noreferrer">Codepen with this example</a>.</p> <hr /> <p>Since React renders data into DOM, you need to keep a variable that first has one value, and then another, so that the message is first shown and then hidden. You could remove the DOM element directly with jQuery's <code>fadeOut</code>, but <a href="https://stackoverflow.com/questions/41435734/should-i-manipulate-dom-directly-or-using-react-state-props">manipulating DOM can cause problems</a>.</p> <p>So, the idea is, you have a certain property that can have one of two values. The closest implementation is a boolean. Since a message box is always in DOM, it's a child of some element. In React, an element is result of rendering a component, and so when you render a component, it can have as many children as you want. So you could add a message box to it.</p> <p>Next, this component has to have a certain property that you can easily change and be completely sure that, as soon as you change it, the component gets re-rendered with new data. It's component state!</p> <pre><code>class App extends React.Component { constructor() { super(); this.state = { showingAlert: false }; } handleClickShowAlert() { this.setState({ showingAlert: true }); setTimeout(() =&gt; { this.setState({ showingAlert: false }); }, 2000); } render() { return ( &lt;div&gt; &lt;div className={`alert alert-success ${this.state.showingAlert ? 'alert-shown' : 'alert-hidden'}`}&gt; &lt;strong&gt;Success!&lt;/strong&gt; Thank you for subscribing! &lt;/div&gt; &lt;button onClick={this.handleClickShowAlert.bind(this)}&gt; Show alert &lt;/button&gt; (and other children) &lt;/div&gt; ); } } </code></pre> <p>Here, you can see that, for message box, either <code>alert-shown</code> or <code>alert-hidden</code> classname is set, depending on the value (truthiness) of <code>showingAlert</code> property of component state. You can then use <a href="https://developer.mozilla.org/en/docs/Web/CSS/transition" rel="noreferrer"><code>transition</code> CSS property</a> to make hiding/showing appearance smooth.</p> <p>So, instead of waiting for the user to click button to show the message box, you need to update component state on a certain event, obviously.</p> <p>That should be good to start with. Next, try to play around with CSS transitions, <code>display</code> and <code>height</code> CSS properties of the message box, to see how it behaves and if the smooth transition happening in these cases.</p> <p>Good luck!</p> <p>PS. See <a href="https://codepen.io/rishatmuhametshin/pen/BWRzGB" rel="noreferrer">a Codepen for that</a>.</p>
21,030,086
Using PowerShell, set the AD home directory for a user, given the display name
<p>I would like to set the home directory based on a csv file containing a list of usernames.</p> <p>I imagine there is a combination of get-user, set-user, and foreach commands that give the correct updates. Here is the code I am using but I'm unable to make the logical jump to piping this output to a Set-ADUser command which sets the home directory.</p> <pre><code>function ConvertUser($user) { $search = New-Object DirectoryServices.DirectorySearcher([ADSI]“”) $search.filter = “(&amp;(objectClass=user)(displayName=$user))” $results = $search.Findall() foreach($result in $results){ $userEntry = $result.GetDirectoryEntry() Write-Output($userEntry.sAMAccountName) } } function ConvertUsers { process{ foreach($user In $_){ ConvertUser($user) } } } Get-Content ".Users.txt" | ConvertUsers </code></pre> <p>I'm sure I'm missing something simple but alas I am a Powershell newb. </p> <p>Edit: I would like to have the output from ConverUsers which is the username and then pipe that to the set-aduser command. Any time I try and pipe it to set-aduser I either get syntax errors, empty pipe, or the wrong data output.</p>
21,030,149
1
0
null
2014-01-09 20:07:22.023 UTC
3
2018-07-26 15:29:24.943 UTC
2014-01-09 20:14:17.13 UTC
null
1,837,482
null
1,837,482
null
1
4
powershell|active-directory
41,848
<p>You're looking for the <code>Set-ADUser</code> cmdlet. It has a <code>-HomeDirectory</code> parameter, which obviously allows you to set the user's home directory, and an <code>-Identity</code> parameter that specifies which user you are editing. It also has a <code>-HomeDrive</code> parameter that specifies the drive letter for their home directory.</p> <pre><code># 1. Get the user, based on their "display name" $User = Get-ADUser -LDAPFilter '(&amp;(displayname=Trevor Sullivan))'; # 2. Change the user's home directory and home drive Set-ADUser -Identity $User.SamAccountName -HomeDirectory \\fileserver\users\trevor -HomeDrive U; </code></pre> <p><img src="https://i.stack.imgur.com/1TMnT.png" alt="Active Directory Users &amp; Computers"></p> <p>Given the following CSV file contents:</p> <p><img src="https://i.stack.imgur.com/C91QN.png" alt="CSV Contents"></p> <p>The following script should set the home drives:</p> <pre><code># 1. Import the user data from CSV $UserList = Import-Csv -Path c:\test\Users.csv; # 2. For each user ... foreach ($User in $UserList) { # 2a. Get the user's AD account $Account = Get-ADUser -LDAPFilter ('(&amp;(displayname={0}))' -f $User.DisplayName); # 2b. Dynamically declare their home directory path in a String $HomeDirectory = '\\fileserver\users\{0}' -f $Account.SamAccountName; # 2c. Set their home directory and home drive letter in Active Directory Set-ADUser -Identity $Account.SamAccountName -HomeDirectory $HomeDirectory -HomeDrive u; } </code></pre>
31,748,671
Pass Objects to AutoMapper Mapping
<p>I am working with AutoMapper and some of the values for the entity being mapped to are variables in my current method. I have tried to Google it but to no avail. Can I pass a set of KeyValue Pairs or an object or something to my mapping to have it use those values?</p> <h3>Sample of Post Mapping Modification</h3> <pre><code>//comment variable is a Comment class instance var imageComment = AutoMapper.Mapper.Map&lt;Data.ImageComment&gt;(comment); //I want to pass in imageId so I dont have to manually add it after the mapping imageComment.ImageId = imageId; </code></pre>
31,754,133
5
0
null
2015-07-31 14:29:57.19 UTC
16
2020-07-11 09:42:09.38 UTC
2015-07-31 14:57:51.96 UTC
null
531,479
null
531,479
null
1
51
c#|asp.net-mvc-4|automapper
40,576
<p>AutoMapper handles this key-value pair scenario out of the box.</p> <pre><code>Mapper.CreateMap&lt;Source, Dest&gt;() .ForMember(d =&gt; d.Foo, opt =&gt; opt.ResolveUsing(res =&gt; res.Context.Options.Items["Foo"])); </code></pre> <p>Then at runtime:</p> <pre><code>Mapper.Map&lt;Source, Dest&gt;(src, opt =&gt; opt.Items["Foo"] = "Bar"); </code></pre> <p>A bit verbose to dig into the context items but there you go.</p>
21,529,467
How to Adjust y axis plot range in Matlab?
<p>I need to plot the following functions in matlab</p> <pre><code>y1=sign(x) y2=tanh(x) y3=(x)/(x+1) </code></pre> <p>The x-range is -5,5 with 0.1 spacing The y-plot range should be between -1.5 to 1.5.</p> <p>Each plot should have a labeled x and y axis and a legend in the lower right corner.</p> <p>The only things I cant figure out is how to adjust the y plot range. Ive tried editing the actual figure but all that seems to do is distort the graph. Is there a command within matlab that will let me adjust the y axis plot range? </p> <p>The other thing I havent figured out yet is adding a legend, I can do it after the figure is created but I guess it needs to be done by matlab command. </p>
21,529,536
2
1
null
2014-02-03 14:08:01.56 UTC
1
2019-06-03 14:05:58.13 UTC
2016-10-23 14:21:00.803 UTC
null
54,964
null
3,155,707
null
1
6
matlab|plot
48,304
<p>Yes, use <a href="http://www.mathworks.co.uk/help/matlab/ref/axis.html" rel="noreferrer"><code>axis</code></a> after the <code>plot</code> command:</p> <pre><code>axis([-5 5 -1.5 1.5]) </code></pre>
42,323,247
How to force axis values to scientific notation in ggplot
<p>I have the following code:</p> <pre><code> library(ggplot2) df &lt;- data.frame(y=seq(1, 1e5, length.out=100), x=sample(100)) p &lt;- ggplot(data = df, aes(x=x, y=y)) + geom_line() + geom_point() p </code></pre> <p>Which produce this image:</p> <p><a href="https://i.stack.imgur.com/oHh0R.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/oHh0R.jpg" alt="enter image description here"></a></p> <p>As mentioned in the image above how can I change the y-axis value to scientific notation?</p>
42,323,301
1
2
null
2017-02-19 03:17:09.647 UTC
6
2017-02-19 03:25:44.843 UTC
null
null
null
null
67,405
null
1
23
r|ggplot2
46,271
<p>You can pass a <code>format</code> function with scientific notation turned on to <em>scale_y_continuous labels</em> parameter:</p> <pre><code>p + scale_y_continuous(labels = function(x) format(x, scientific = TRUE)) </code></pre> <p><a href="https://i.stack.imgur.com/s5mPB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/s5mPB.png" alt="enter image description here"></a></p>
33,323,707
How do I reload a module after changing it?
<p>Python Console with Python 3.4.2 </p> <p>I defined a function in a module which runs correctly in Python Console in PyCharm Community Edition 4.5.4:<br> ReloadTest.py:</p> <pre><code>def reloadtest(x): print("Version A: {}".format(x)) </code></pre> <p>Python Console:</p> <pre><code>Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32 &gt;&gt;&gt; from ReloadTest import reloadtest &gt;&gt;&gt; reloadtest(1) Version A: 1 </code></pre> <p>After I modified the function to "Version B", PyCharm can't find the change, and <code>importlib.reload(ReloadTest)</code> gives me error.<br> I must reload the Python Console or restart PyCharm every time I modify a module. What did I do wrong? What is the best way to handle this?</p> <p>ReloadTest.py:</p> <pre><code>def reloadtest(x): print("Version B: {}".format(x)) </code></pre> <p>Python Console:</p> <pre><code>&gt;&gt;&gt; reloadtest(1) Version A: 1 &gt;&gt;&gt; from ReloadTest import reloadtest &gt;&gt;&gt; reloadtest(1) Version A: 1 &gt;&gt;&gt; import importlib &gt;&gt;&gt; importlib.reload(ReloadTest) Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; NameError: name 'ReloadTest' is not defined &gt;&gt;&gt; from ReloadTest import reloadtest &gt;&gt;&gt; reloadtest(1) Version A: 1 &gt;&gt;&gt; import ReloadTest &gt;&gt;&gt; reloadtest(1) Version A: 1 </code></pre>
33,405,315
4
1
null
2015-10-24 21:44:39.747 UTC
11
2021-04-25 13:23:46.443 UTC
2015-10-28 01:06:30.29 UTC
null
2,719,588
null
2,719,588
null
1
33
pycharm
39,551
<p>Get it to work!<br> Instead of <code>from Module import function</code>, I should import the whole module <code>import Module</code>, then call the function by <code>Module.function()</code>. This is because</p> <pre><code>from ReloadTest import reloadtest </code></pre> <p>and</p> <pre><code>importlib.reload(ReloadTest) </code></pre> <p>can't go together.</p> <pre><code>&gt;&gt;&gt; import ReloadTest &gt;&gt;&gt; ReloadTest.reloadtest(1) Version A: 1 </code></pre> <p>After making changes:</p> <pre><code>&gt;&gt;&gt; importlib.reload(ReloadTest) &lt;module 'ReloadTest' from 'C:\\...\\ReloadTest.py'&gt; &gt;&gt;&gt; ReloadTest.reloadtest(2) Version B: 2 </code></pre>
9,417,356
Bufferedimage resize
<p>I am trying to resized a bufferedimage. I am able to store it and show up on a jframe no problems but I can't seem to resize it. Any tips on how I can change this to make it work and show the image as a 200*200 file would be great </p> <pre><code>private void profPic(){ String path = factory.getString("bottle"); BufferedImage img = ImageIO.read(new File(path)); } public static BufferedImage resize(BufferedImage img, int newW, int newH) { int w = img.getWidth(); int h = img.getHeight(); BufferedImage dimg = new BufferedImage(newW, newH, img.getType()); Graphics2D g = dimg.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null); g.dispose(); return dimg; } </code></pre>
9,417,836
7
0
null
2012-02-23 16:47:30.507 UTC
14
2021-04-09 12:58:43.707 UTC
2018-04-04 07:15:06.903 UTC
null
4,283,581
null
1,060,187
null
1
53
java|bufferedimage
114,875
<p><em>Updated answer</em></p> <p>I cannot recall why <a href="https://stackoverflow.com/revisions/9417836/1">my original answer</a> worked but having tested it in a separate environment, I agree, the original accepted answer doesn't work (why I said it did I cannot remember either). This, on the other hand, did work:</p> <pre><code>public static BufferedImage resize(BufferedImage img, int newW, int newH) { Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH); BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); return dimg; } </code></pre>
30,797,106
what's ARM TCM memory
<p>what is TCM memory on ARM processors, is it a dedicated memory which resides next to the processor or just a region of RAM which is configured as TCM??.</p> <p>if it's a dedicated memory, why can we configure it's location and size?.</p>
30,800,318
1
1
null
2015-06-12 07:00:26 UTC
9
2015-06-12 09:59:07.463 UTC
null
null
null
null
4,838,002
null
1
28
memory|arm
26,518
<p>TCM, Tightly-Coupled Memory is one (or multiple) small, dedicated memory region that as the name implies is very close to the CPU. The main benefit of it is, that the CPU can access the TCM every cycle. Contrary to the ordinary memory there is no cache involved which makes all memory accesses predictable.</p> <p>The main use of TCM is to store performance critical data and code. Interrupt handlers, data for real-time tasks and OS control structures are a common example.</p> <blockquote> <p>if it's a dedicated memory, why can we configure it's location and size</p> </blockquote> <p>Making it configurable would just complicate the address decoding for all memory accesses while giving no real benefit over a fixed address range. So it was probably easier and faster to just tie the TCM to a fixed address.</p> <p>Btw, if you are working on a system that has a TCM and you aren't using it yet, try placing your stack there. That usually gives you some percent of performance gain for free since all stack memory accesses are now single cycle and don't pollute the data-cache anymore. </p>
31,143,015
Docker NLTK Download
<p>I am building a docker container using the following Dockerfile:</p> <pre><code>FROM ubuntu:14.04 RUN apt-get update RUN apt-get install -y python python-dev python-pip ADD . /app RUN apt-get install -y python-scipy RUN pip install -r /arrc/requirements.txt EXPOSE 5000 WORKDIR /app CMD python app.py </code></pre> <p>Everything goes well until I run the image and get the following error:</p> <pre><code>********************************************************************** Resource u'tokenizers/punkt/english.pickle' not found. Please use the NLTK Downloader to obtain the resource: &gt;&gt;&gt; nltk.download() Searched in: - '/root/nltk_data' - '/usr/share/nltk_data' - '/usr/local/share/nltk_data' - '/usr/lib/nltk_data' - '/usr/local/lib/nltk_data' - u'' ********************************************************************** </code></pre> <p>I have had this problem before and it is discussed <a href="https://stackoverflow.com/questions/4867197/failed-loading-english-pickle-with-nltk-data-load">here</a> however I am not sure how to approach it using Docker. I have tried:</p> <pre><code>CMD python CMD import nltk CMD nltk.download() </code></pre> <p>as well as:</p> <pre><code>CMD python -m nltk.downloader -d /usr/share/nltk_data popular </code></pre> <p>But am still getting the error.</p>
31,467,809
5
2
null
2015-06-30 15:56:04.477 UTC
6
2022-01-04 06:14:26.373 UTC
2017-07-27 16:10:59.85 UTC
null
610,569
null
4,793,408
null
1
39
python|docker|nltk
22,529
<p>In your Dockerfile, try adding instead:</p> <blockquote> <p><code>RUN python -m nltk.downloader punkt</code></p> </blockquote> <p>This will run the command and install the requested files to <code>//nltk_data/</code></p> <p>The problem is most likely related to using CMD vs. RUN in the Dockerfile. Documentation for CMD:</p> <blockquote> <p>The main purpose of a CMD is to provide defaults for an executing container.</p> </blockquote> <p>which is used during <code>docker run &lt;image&gt;</code>, not during build. So other CMD lines probably were overwritten by the last <code>CMD python app.py</code> line.</p>
47,168,477
How to stream std::variant<...,...>
<p>My <code>std::variant</code> contains streamable types: </p> <pre><code>std::variant&lt;int, std::string&gt; a, b; a = 1; b = "hi"; std::cout &lt;&lt; a &lt;&lt; b &lt;&lt; std::endl; </code></pre> <p>Compiling with g++7 with -std=c++1z returns compilation time errors. </p> <p>An excerpt:</p> <pre><code>test.cpp: In function 'int main(int, char**)': test.cpp:10:13: error: no match for 'operator&lt;&lt;' (operand types are 'std::ostream {aka std::basic_ostream&lt;char&gt;}' and 'std::variant&lt;int, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;') std::cout &lt;&lt; a &lt;&lt; b &lt;&lt; std::endl; ~~~~~~~~~~^~~~ </code></pre> <p>Seemingly a <code>std::variant&lt;int, std::string&gt;</code> is not able to stream. How can I achieve that I can directly stream the variant to an output stream? </p> <p>Expected output:</p> <pre><code>1hi </code></pre>
47,169,101
3
2
null
2017-11-07 22:29:18.3 UTC
8
2019-12-25 19:37:30.677 UTC
2017-11-07 23:39:03.883 UTC
null
6,022,656
null
863,857
null
1
13
c++|stream|c++17|variant
4,348
<p>This streams nested variants too.</p> <pre><code>template&lt;class T&gt; struct streamer { const T&amp; val; }; template&lt;class T&gt; streamer(T) -&gt; streamer&lt;T&gt;; template&lt;class T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, streamer&lt;T&gt; s) { os &lt;&lt; s.val; return os; } template&lt;class... Ts&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, streamer&lt;std::variant&lt;Ts...&gt;&gt; sv) { std::visit([&amp;os](const auto&amp; v) { os &lt;&lt; streamer{v}; }, sv.val); return os; } </code></pre> <p>Use as:</p> <pre><code>std::cout &lt;&lt; streamer{a} &lt;&lt; streamer{b} &lt;&lt; '\n'; </code></pre>
10,499,789
Session stickiness on Amazon Web Services
<p>I'm a bit confused about the use of the session stickiness on Amazon Web Services. When I deploy my java web application using Amazon Elastic Beanstalk, I can choose to enable the session stickiness and then specify a cookie expiration period.</p> <p>My application uses cookies for the session (JSESSIONID) as well as for other small things. Most of the website is accessible only after logging in (I use Spring security to manage it). The website will run on up to 25 small EC2 instances.</p> <p>Should I enable the session stickiness? If I don't enable it, does it mean that I could be suddendly logged out because the load balancer took me to another server (not the server that authenticated me)? If I enable the session stickiness, do I get logged out when the server that authenticated me gets shut down? Basically, why and when should I use session stickiness?</p> <p>Thank you very much.</p>
10,502,092
2
1
null
2012-05-08 13:40:52.173 UTC
12
2014-03-18 09:26:55.33 UTC
null
null
null
null
1,031,658
null
1
17
amazon-ec2|amazon-web-services|amazon-elastic-beanstalk|amazon-elb
9,614
<blockquote> <p>If I don't enable it, does it mean that I could be suddendly logged out because the load balancer took me to another server (not the server that authenticated me)?</p> </blockquote> <p>Yes</p> <blockquote> <p>If I enable the session stickiness, do I get logged out when the server that authenticated me gets shut down?</p> </blockquote> <p>Yes</p> <p>When using Elastic Beanstalk with a typical Java webapp, I think you will definitely want to enable session stickiness. Otherwise each HTTP request from a user's browser could be routed to a different server.</p> <p>To get around the issue of the user's session being destroyed when the server they are "stuck" to gets shut down you would need to look into <a href="http://tomcat.apache.org/tomcat-7.0-doc/cluster-howto.html">Tomcat session replication</a>. This isn't something that Elastic Beanstalk comes with out of the box unfortunately, so in order to setup session replication you would have to create a custom Elastic Beanstalk AMI for your application to use. Also, you would have to use an implementation of Tomcat session replication <a href="https://forums.aws.amazon.com/thread.jspa?threadID=21554">that does not rely on multicast</a>, since multicast isn't available on AWS, or any other cloud environment that I know of. An example of an implementation that doesn't rely on multicast would be one that uses a database (such as Amazon RDS) or memcached server (such as Amazon Elastic Cache) to make the sessions available across multiple Tomcat instances.</p> <p>Also note that the Elastic Beanstalk UI only allows you to enable load balancer-generated HTTP cookies. However after Elastic Beanstalk has created the load balancer, you can go into the EC2 console and modify the load balancer's settings to switch it to application-generated HTTP cookies, and then tell it to use the "JSESSIONID" cookie.</p>
31,993,704
Storing ggplot objects in a list from within loop in R
<p>My problem is similar to <a href="https://stackoverflow.com/questions/1820590/problem-storing-plot-objects-in-a-list-in-r">this one</a>; when I generate plot objects (in this case histograms) in a loop, seems that all of them become overwritten by the most recent plot. </p> <p>To debug, within the loop, I am printing the index and the generated plot, both of which appear correctly. But when I look at the plots stored in the list, they are all identical <strong>except</strong> for the label. </p> <p>(I'm using multiplot to make a composite image, but you get same outcome if you <code>print (myplots[[1]])</code> through <code>print(myplots[[4]])</code> one at a time.) </p> <p>Because I already have an attached dataframe (unlike the poster of the similar problem), I am not sure how to solve the problem.</p> <p>(btw, column classes are factor in the original dataset I am approximating here, but same problem occurs if they are integer)</p> <p>Here is a reproducible example:</p> <pre><code>library(ggplot2) source("http://peterhaschke.com/Code/multiplot.R") #load multiplot function #make sample data col1 &lt;- c(2, 4, 1, 2, 5, 1, 2, 0, 1, 4, 4, 3, 5, 2, 4, 3, 3, 6, 5, 3, 6, 4, 3, 4, 4, 3, 4, 2, 4, 3, 3, 5, 3, 5, 5, 0, 0, 3, 3, 6, 5, 4, 4, 1, 3, 3, 2, 0, 5, 3, 6, 6, 2, 3, 3, 1, 5, 3, 4, 6) col2 &lt;- c(2, 4, 4, 0, 4, 4, 4, 4, 1, 4, 4, 3, 5, 0, 4, 5, 3, 6, 5, 3, 6, 4, 4, 2, 4, 4, 4, 1, 1, 2, 2, 3, 3, 5, 0, 3, 4, 2, 4, 5, 5, 4, 4, 2, 3, 5, 2, 6, 5, 2, 4, 6, 3, 3, 3, 1, 4, 3, 5, 4) col3 &lt;- c(2, 5, 4, 1, 4, 2, 3, 0, 1, 3, 4, 2, 5, 1, 4, 3, 4, 6, 3, 4, 6, 4, 1, 3, 5, 4, 3, 2, 1, 3, 2, 2, 2, 4, 0, 1, 4, 4, 3, 5, 3, 2, 5, 2, 3, 3, 4, 2, 4, 2, 4, 5, 1, 3, 3, 3, 4, 3, 5, 4) col4 &lt;- c(2, 5, 2, 1, 4, 1, 3, 4, 1, 3, 5, 2, 4, 3, 5, 3, 4, 6, 3, 4, 6, 4, 3, 2, 5, 5, 4, 2, 3, 2, 2, 3, 3, 4, 0, 1, 4, 3, 3, 5, 4, 4, 4, 3, 3, 5, 4, 3, 5, 3, 6, 6, 4, 2, 3, 3, 4, 4, 4, 6) data2 &lt;- data.frame(col1,col2,col3,col4) data2[,1:4] &lt;- lapply(data2[,1:4], as.factor) colnames(data2)&lt;- c("A","B","C", "D") #generate plots myplots &lt;- list() # new empty list for (i in 1:4) { p1 &lt;- ggplot(data=data.frame(data2),aes(x=data2[ ,i]))+ geom_histogram(fill="lightgreen") + xlab(colnames(data2)[ i]) print(i) print(p1) myplots[[i]] &lt;- p1 # add each plot into plot list } multiplot(plotlist = myplots, cols = 4) </code></pre> <p>When I look at a summary of a plot object in the plot list, this is what I see</p> <pre><code>&gt; summary(myplots[[1]]) data: A, B, C, D [60x4] mapping: x = data2[, i] faceting: facet_null() ----------------------------------- geom_histogram: fill = lightgreen stat_bin: position_stack: (width = NULL, height = NULL) </code></pre> <p>I think that <code>mapping: x = data2[, i]</code> is the problem, but I am stumped! I can't post images, so you'll need to run my example and look at the graphs if my explanation of the problem is confusing.</p> <p>Thanks!</p>
31,994,539
4
2
null
2015-08-13 16:29:50.1 UTC
24
2021-04-09 14:56:17.913 UTC
2017-05-23 12:34:41.94 UTC
null
-1
null
5,224,058
null
1
50
r|plot|ggplot2
66,824
<p>In addition to the other excellent answer, here’s a solution that uses “normal”-looking evaluation rather than <code>eval</code>. Since <code>for</code> loops have no separate variable scope (i.e. they are performed in the current environment) we need to use <code>local</code> to wrap the <code>for</code> block; in addition, we need to make <code>i</code> a local variable — which we can do by re-assigning it to its own name<sup>1</sup>:</p> <pre><code>myplots &lt;- vector('list', ncol(data2)) for (i in seq_along(data2)) { message(i) myplots[[i]] &lt;- local({ i &lt;- i p1 &lt;- ggplot(data2, aes(x = data2[[i]])) + geom_histogram(fill = "lightgreen") + xlab(colnames(data2)[i]) print(p1) }) } </code></pre> <p>However, an altogether cleaner way is to forego the <code>for</code> loop entirely and use list functions to build the result. This works in several possible ways. The following is the easiest in my opinion:</p> <pre><code>plot_data_column = function (data, column) { ggplot(data, aes_string(x = column)) + geom_histogram(fill = "lightgreen") + xlab(column) } myplots &lt;- lapply(colnames(data2), plot_data_column, data = data2) </code></pre> <p>This has several advantages: it’s simpler, and it won’t clutter the environment (with the loop variable <code>i</code>).</p> <hr> <p><sup>1</sup> This might seem confusing: why does <code>i &lt;- i</code> have any effect at all? — Because by performing the assignment we create a new, <em>local</em> variable with the same name as the variable in the outer scope. We could equally have used a different name, e.g. <code>local_i &lt;- i</code>.</p>
32,128,412
Python: yield and yield assignment
<p>How does this code, involving assignment and the yield operator, work? The results are rather confounding.</p> <pre><code>def test1(x): for i in x: _ = yield i yield _ def test2(x): for i in x: _ = yield i r1 = test1([1,2,3]) r2 = test2([1,2,3]) print list(r1) print list(r2) </code></pre> <p>Output:</p> <pre><code>[1, None, 2, None, 3, None] [1, 2, 3] </code></pre>
32,128,704
3
2
null
2015-08-20 21:07:02.283 UTC
9
2015-08-20 22:14:59.733 UTC
2015-08-20 22:12:37.723 UTC
null
1,832,942
null
4,667,484
null
1
28
python|yield|assignment-operator
11,284
<p>The assignment syntax ("yield expression") allows you to treat the generator as a rudimentary coroutine.</p> <p>First proposed in <a href="https://www.python.org/dev/peps/pep-0342/" rel="noreferrer">PEP 342</a> and documented here: <a href="https://docs.python.org/2/reference/expressions.html#yield-expressions" rel="noreferrer">https://docs.python.org/2/reference/expressions.html#yield-expressions</a></p> <p>The client code that is working with the generator can communicate data back into the generator using its <code>send()</code> method. That data is accessible via the assignment syntax.</p> <p><code>send()</code> will also iterate - so it actually includes a <code>next()</code> call.</p> <p>Using your example, this is what it would be like to use the couroutine functionality:</p> <pre><code>&gt;&gt;&gt; def test1(x): ... for i in x: ... _ = yield i ... yield _ ... &gt;&gt;&gt; l = [1,2,3] &gt;&gt;&gt; gen_instance = test1(l) &gt;&gt;&gt; #First send has to be a None &gt;&gt;&gt; print gen_instance.send(None) 1 &gt;&gt;&gt; print gen_instance.send("A") A &gt;&gt;&gt; print gen_instance.send("B") 2 &gt;&gt;&gt; print gen_instance.send("C") C &gt;&gt;&gt; print gen_instance.send("D") 3 &gt;&gt;&gt; print gen_instance.send("E") E &gt;&gt;&gt; print gen_instance.send("F") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration </code></pre> <p>Note that some of the sends are lost because of the second <code>yield</code> in each loop iteration that doesn't capture the sent data.</p> <p><strong>EDIT:</strong> Forgot to explain the <code>None</code>s yielded in your example.</p> <p>From <a href="https://docs.python.org/2/reference/expressions.html#generator.next" rel="noreferrer">https://docs.python.org/2/reference/expressions.html#generator.next</a>:</p> <blockquote> <p>When a generator function is resumed with a next() method, the current yield expression always evaluates to None.</p> </blockquote> <p><code>next()</code> is used when using the iteration syntax.</p>
36,931,593
Error when trying to run `pod trunk push [cocoapod].podspec`
<p>When trying to push an update to my cocoapod framework to the repo with <code>pod trunk push</code> as mentioned in the title, I get the following error:</p> <blockquote> <p>[!] Authentication token is invalid or unverified. Either verify it with the email that was sent or register a new session.</p> </blockquote> <p>I've updated the cocoapod before, how do I verify my email or session?</p> <p>Edit: Sometimes I also get the error: <code>[!] You need to register a session first.</code></p>
36,931,594
2
1
null
2016-04-29 06:59:57.723 UTC
7
2018-08-10 22:47:47.563 UTC
2018-08-10 22:47:47.563 UTC
null
4,056,516
null
4,056,516
null
1
60
ios|objective-c|swift|frameworks|cocoapods
8,139
<ol> <li><p>Run the following command in terminal:</p> <p><code>pod trunk register [email protected] 'Your Name'</code></p></li> <li><p>Click the link in the email that is sent to you.</p></li> <li><p>Run your <code>pod trunk push</code> command in terminal again</p></li> </ol>
3,936,697
HTML - Position an image in a new line
<p>I have a series of paragraphs. Each one ends with a illustration which clarifies the subject being explained in the paragraph.</p> <p>I want the illustration to be on a new line and not display along with the text and I have found the following solutions, with it's own problems:</p> <p>Put the illustration in a different &lt;p&gt; than the text related to the illustration.</p> <pre><code>&lt;p&gt;Some text here&lt;p/&gt; &lt;p&gt;&lt;img src="myphoto"/&gt;&lt;/p&gt; </code></pre> <p>This seems to solve all the problems, but later I needed to enclose some of this paragraphs inside a <code>&lt;ul&gt;</code> instead of a <code>&lt;p&gt;</code>. The problem being I cannot enclose the <code>&lt;p&gt;</code> tag for the illustration inside a <code>&lt;li&gt;</code> and does not make sense to put the illustration inside a <code>&lt;li&gt;</code>.</p> <pre><code>&lt;ul&gt; &lt;li&gt;Some text&lt;/li&gt; &lt;p&gt;&lt;img src="myphoto"/&gt;&lt;/p&gt;&lt;!--Incorrect--&gt; &lt;li&gt;&lt;img src="myphoto"/&gt;&lt;/li&gt;&lt;!--Does not make sense--&gt; &lt;/ul&gt; </code></pre> <p>Put the ilulstration inside the same <code>&lt;p&gt;</code> as the text. Then use <code>&lt;br/&gt;</code> tag to move the picture to a new line. I'm not really happy with this workaround, the <code>&lt;br/&gt;</code> is doing presentational stuff that should be better in CSS.</p> <pre><code>&lt;p&gt;Some text here&lt;br/&gt;&lt;img src="myphoto"/&gt;&lt;/p&gt; </code></pre> <p>Finally, set the display attribute of the <code>&lt;img&gt;</code> as block in the CSS style sheet. I'm not sure if this is a good way and don't know the unrelated consequences it may have.</p> <p>I don't know if there is a standard way of doing this. I have search for CSS to start my image in a new line but did not find it. Any help will be welcome.</p>
3,936,725
1
0
null
2010-10-14 19:13:15.173 UTC
null
2017-11-27 07:52:01.437 UTC
2012-07-22 05:31:23.59 UTC
null
23,739
null
467,224
null
1
8
html|css|positioning|image
63,780
<p>Ok, so this is my new solution. Basically, we just set the IMG element to be a block-level element. </p> <pre><code>img { display:block; } </code></pre> <p>This solution does not introduce any new markup. (You just place the <code>&lt;img&gt;</code> element right after the text in the paragraph / list item.) </p> <p>I believe this to be the most elegant solution, since setting images to be blocks is rather common anyway.</p>
3,632,024
Why do Ruby's regular expressions use \A and \z instead of ^ and $?
<p>I'm not a Ruby programmer, but as I was reading through the extensive <a href="http://guides.rubyonrails.org/security.html#regular-expressions" rel="noreferrer">Ruby on Rails security guide</a>, I noticed this section:</p> <blockquote> <p>A common pitfall in Ruby’s regular expressions is to match the string’s beginning and end by ^ and $, instead of \A and \z.</p> </blockquote> <p>Does anyone know if this is this just a matter of aesthetics or something else? I ask because I've only used languages that use <code>^</code> and <code>$</code>.</p>
3,632,051
1
0
null
2010-09-02 23:27:56.017 UTC
13
2015-06-04 12:38:49.537 UTC
2015-06-04 12:38:49.537 UTC
null
12,892
null
385,950
null
1
30
ruby-on-rails|ruby|regex
7,562
<p>This isn't specific to Ruby; <code>\A</code> and <code>\Z</code> are not the same thing as <code>^</code> and <code>$</code>. <code>^</code> and <code>$</code> are the start and end of <strong>line</strong> anchors, whereas <code>\A</code> and <code>\Z</code> are the start and end of <strong>string</strong> anchors.</p> <p>Ruby differs from other languages in that it automatically uses "multiline mode" (which enables the aforementioned behaviour of having <code>^</code> and <code>$</code> match per line) for regular expressions, but in most other flavours you need to enable it yourself, which is probably why that article contains the warning.</p> <p>Reference: <a href="http://www.regular-expressions.info/anchors.html" rel="noreferrer">http://www.regular-expressions.info/anchors.html</a></p>
3,861,721
Add ASP.NET Membership tables to my own existing database, or should I instead configure a separate ASP.NET membership database?
<p>I was reading through this post here <a href="http://www.misfitgeek.com/op-ed/adding-asp-net-membership-to-your-own-database" rel="noreferrer">MisfitGeek: Adding ASP.NET Membership to your OWN Database. </a></p> <p>and thought to my self what the common practice is. What do developers using ASP.NET membership and authorization in their applications recommend as a best practice? Creating the membership tables in the same database that stores their applications data or configuring a second database to store ONLY the membership information?</p> <p>My current setup is a different database for membership information ONLY but am thinking that increases the number of databases I have to maintain. If I have 5 applications using ASP.NET membership, then that means 5 more ASP.NET membership databases. </p> <p>So do you normally create the ASP.NET membership tables in your main database or you configure a separate membership table? </p>
3,861,834
1
0
null
2010-10-05 07:45:15.257 UTC
16
2012-07-03 07:37:57.667 UTC
2012-07-03 07:37:57.667 UTC
null
109,702
null
77,121
null
1
31
asp.net|database-design|asp.net-membership
32,328
<p>I personally just added the asp.net membership stuff to my own database. I then wrote a basic wrapper class around System.Web.Security.Membership class so that the code acts like its using its own membership stuff. Its pretty slick and not that hard to do. If you need assistance setting it up, here is what I did. </p> <p>The link you provided on how to set it up is waaaaaaaaaayy more complicated that what I used:</p> <blockquote> <ol> <li>Run C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe.</li> <li>Hit Next.</li> <li>Select “Configure SQL Server for application services…” and hit Next.</li> <li>Select “Windows Authentication” and the “XXXX” Database and hit Next.</li> <li>Your settings are then presented...then hit Next.</li> <li>Finally you should be presented with a done screen, hit Finish.</li> </ol> </blockquote> <p>I have screenshots in the doc if you really need the walkthrough.</p>
40,873,933
error expected primary-expression before ';'token c++
<p>am new in coding and am using c++ to create a program to find sum median maximum and minimum but i get the error expected primary-expression before ';' token in every place that has cout</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int array[10],maximum,minimum,sum=0,median; cout&lt;&lt;"input ten integers,"&lt;&lt;; for(int i=0; i&lt;10; i++){ cin&gt;&gt; array[i]; sum=sum+array[i]; } for(int i=0; i&lt;10; i++){ if(maximum&gt;array[i]) { maximum=array[i]; } else if( minimum&lt;array[i]) { maximum= array[i]; } } median=(array[4]+array[5])/2; cout&lt;&lt;"maximum value is"&lt;&lt;maximum&lt;&lt;; cout&lt;&lt;"minimum value is"&lt;&lt;minimum&lt;&lt;; cout&lt;&lt;"sum is"&lt;&lt;sum&lt;&lt;; cout&lt;&lt;"median is"&lt;median&lt;&lt;; </code></pre>
40,873,962
1
1
null
2016-11-29 19:11:27.707 UTC
null
2016-11-29 19:22:58.667 UTC
null
null
null
null
7,227,193
null
1
2
c++
41,086
<p>Remove the <code>&lt;&lt;</code> before the <code>;</code> on every line that has it or replace <code>&lt;&lt;;</code> with <code>&lt;&lt;'\n';</code> for a new line.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int array[10], maximum = 0, minimum = 0, sum = 0, median = 0; cout &lt;&lt; "input ten integers: "; for (int i = 0; i &lt; 10; i++) { cin &gt;&gt; array[i]; sum = sum + array[i]; } for (int i = 0; i &lt; 10; i++) { if (maximum &gt; array[i]) { maximum = array[i]; } else if (minimum &lt; array[i]) { maximum = array[i]; } } median = (array[4] + array[5]) / 2; cout &lt;&lt; "maximum value is " &lt;&lt; maximum &lt;&lt; '\n'; cout &lt;&lt; "minimum value is " &lt;&lt; minimum &lt;&lt; '\n'; cout &lt;&lt; "sum is " &lt;&lt; sum &lt;&lt; '\n'; cout &lt;&lt; "median is " &lt;&lt; median &lt;&lt; '\n'; return 0; } </code></pre>
41,132,262
How best to Count(*) with a CASE STATEMENT?
<p>The following SQL (on SQL Server) returns an error of: </p> <blockquote> <p>Incorrect syntax near '*'</p> </blockquote> <p>Is there something inherently wrong with using the following SELECT statement?:</p> <pre><code>SELECT COUNT(CASE WHEN &lt;conditions&gt; THEN * ELSE NULL END) as conditionalcountall FROM TABLE </code></pre> <p>I tried this variation which also failed:</p> <pre><code>SELECT CASE WHEN &lt;conditions&gt; THEN COUNT(*) ELSE NULL END as conditionalcountall FROM TABLE </code></pre>
41,132,301
4
1
null
2016-12-13 23:21:28.59 UTC
1
2021-01-21 16:40:00.43 UTC
2016-12-13 23:23:01.157 UTC
null
4,275,342
null
5,476,942
null
1
4
sql|sql-server|case
39,569
<p>I tend to like sum()</p> <pre><code>SELECT SUM(CASE WHEN &lt;conditions&gt; THEN 1 ELSE 0 END) as conditionalcountall FROM TABLE </code></pre>
28,374,000
Spring - Programmatically generate a set of beans
<p>I have a Dropwizard application that needs to generate a dozen or so beans for each of the configs in a configuration list. Things like health checks, quartz schedulers, etc.</p> <p>Something like this:</p> <pre><code>@Component class MyModule { @Inject private MyConfiguration configuration; @Bean @Lazy public QuartzModule quartzModule() { return new QuartzModule(quartzConfiguration()); } @Bean @Lazy public QuartzConfiguration quartzConfiguration() { return this.configuration.getQuartzConfiguration(); } @Bean @Lazy public HealthCheck healthCheck() throws SchedulerException { return this.quartzModule().quartzHealthCheck(); } } </code></pre> <p>I have multiple instances of MyConfiguration that all need beans like this. Right now I have to copy and paste these definitions and rename them for each new configuration.</p> <p>Can I somehow iterate over my configuration classes and generate a set of bean definitions for each one?</p> <p>I would be fine with a subclassing solution or anything that is type safe without making me copy and paste the same code and rename the methods ever time I have to add a new service.</p> <p>EDIT: I should add that I have other components that depend on these beans (they inject <code>Collection&lt;HealthCheck&gt;</code> for example.)</p>
28,565,540
6
1
null
2015-02-06 20:13:56.073 UTC
34
2022-05-16 09:21:01.873 UTC
2015-02-12 21:49:52.01 UTC
null
12,034
null
12,034
null
1
41
java|spring|spring-mvc|dropwizard
51,906
<p>The "best" approach I could come up with was to wrap all of my Quartz configuration and schedulers in 1 uber bean and wire it all up manually, then refactor the code to work with the uber bean interface.</p> <p>The uber bean creates all the objects that I need in its PostConstruct, and implements ApplicationContextAware so it can auto-wire them. It's not ideal, but it was the best I could come up with.</p> <p>Spring simply does not have a good way to dynamically add beans in a typesafe way. </p>
8,970,913
Create a temp file with a specific extension using php
<p>How do I create a temporary file with a specified extension in php. I came across <a href="http://php.net/manual/en/function.tempnam.php"><code>tempnam()</code></a> but using it the extension can't be specified.</p>
8,971,248
8
1
null
2012-01-23 11:29:21.74 UTC
3
2021-10-08 10:17:02.733 UTC
2012-01-23 11:36:51.723 UTC
null
1,063,333
null
632,447
null
1
28
php|temporary-files
27,628
<p>This might simulate <code>mkstemp()</code> (see <a href="http://linux.die.net/man/3/mkstemp" rel="noreferrer">http://linux.die.net/man/3/mkstemp</a>) a bit, achieving what you want to do:</p> <pre><code>function mkstemp( $template ) { $attempts = 238328; // 62 x 62 x 62 $letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $length = strlen($letters) - 1; if( mb_strlen($template) &lt; 6 || !strstr($template, 'XXXXXX') ) return FALSE; for( $count = 0; $count &lt; $attempts; ++$count) { $random = ""; for($p = 0; $p &lt; 6; $p++) { $random .= $letters[mt_rand(0, $length)]; } $randomFile = str_replace("XXXXXX", $random, $template); if( !($fd = @fopen($randomFile, "x+")) ) continue; return $fd; } return FALSE; } </code></pre> <p>So you could do:</p> <pre><code>if( ($f = mkstemp("test-XXXXXX.txt")) ) { fwrite($f, "test\n"); fclose($f); } </code></pre>
26,944,987
Show Next/Previous item of an array
<p>I'm writing the first item of an array to the screen, and would like to create <code>Next/Previous</code> buttons for array, but I can't get it to work. I have tried several methods, but I can't find suitable solution. </p> <p>Can anyone help? </p> <p>This is the last one I have tried:</p> <pre><code>&lt;div&gt; &lt;script type="text/javascript"&gt; sav = new Array( "first item", "second item", "third item", ); document.write(sav[0] + " &lt;br&gt;"); &lt;/script&gt; &lt;/div&gt; &lt;div&gt; &lt;a href="" onClick="javascript: sav[i++]"&gt;Previous&lt;/a&gt; &lt;a href="" onClick="javascript: sav[i--]"&gt;Next!&lt;/a&gt; &lt;/div&gt; </code></pre>
26,945,342
3
3
null
2014-11-15 10:47:03.593 UTC
5
2018-06-20 11:50:12.46 UTC
2014-11-15 13:13:55.583 UTC
null
2,306,173
null
1,444,175
null
1
9
javascript|html|arrays
41,279
<p>Say you have an <em>Array</em> <code>var arr = ['foo', 'bar', 'baz'];</code>.<br> If you want to dynamically choose items from this <em>Array</em>, you'll need a new variable. Let's call this <code>i</code> and give it a default value <code>var i = 0;</code> </p> <p>So far, <code>arr[i]; // "foo" (i === 0)</code></p> <hr> <h2>Next and Previous</h2> <p>Now, lets write a function to choose the next item by modifying <code>i</code>. We may want to consider what we want to happen when <code>i</code> is bigger than (or equal to) <code>arr.length</code> as well.</p> <pre><code>function nextItem() { i = i + 1; // increase i by one i = i % arr.length; // if we've gone too high, start from `0` again return arr[i]; // give us back the item of where we are now } </code></pre> <p>Next, lets do the reverse, this time we might want to consider what should happen for negative <code>i</code></p> <pre><code>function prevItem() { if (i === 0) { // i would become 0 i = arr.length; // so put it at the other end of the array } i = i - 1; // decrease by one return arr[i]; // give us back the item of where we are now } </code></pre> <p>So far,</p> <pre><code>nextItem(); // "bar" (i === 1) prevItem(); // "foo" (i === 0 as we did `0 + 1 - 1`) // also prevItem(); // "baz" (decreased on 0) nextItem(); // "foo" (increased at end of arr) </code></pre> <p>Great, so we've got the basic algorithms down.</p> <hr> <h2>Connecting this to the <em>DOM</em></h2> <p>First thing to note is that <code>document.write</code> is nearly always a bad idea. Instead, why not give our <em>Elements</em> some <strong>unique</strong> <em>id attributes</em> and use <em>DOM</em> methods in <em>JavaScript</em> <strong>after the <em>Elements</em> exist</strong>.</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="output"&gt;&lt;/div&gt; &lt;div&gt; &lt;span id="prev_button"&gt;Previous&lt;/span&gt; &lt;span id="next_button"&gt;Next!&lt;/span&gt; &lt;/div&gt; </code></pre> <p>So now we can access the first <code>&lt;div&gt;</code> in <em>JavaScript</em> as <code>document.getElementById('output')</code>, and the two <code>&lt;span&gt;</code>s similarly.</p> <p>Now, let's set the initial text in the <code>&lt;div&gt;</code>, this is quite easy</p> <pre><code>document.getElementById('output').textContent = arr[0]; // initial value // if i is still at it's default value, we could have used i instead of 0 </code></pre> <p>Next, we need to add <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener" rel="noreferrer"><strong><em>event listeners</em></strong></a> to the <code>&lt;span&gt;</code>s so they perform an action. The handler of each will set the text of the <code>&lt;div&gt;</code> in a similar way to above, but using the relevant <em>function</em> from earlier.</p> <pre><code>document.getElementById('prev_button').addEventListener( 'click', // we want to listen for a click function (e) { // the e here is the event itself document.getElementById('output').textContent = prevItem(); } ); document.getElementById('next_button').addEventListener( 'click', // we want to listen for a click function (e) { // the e here is the event itself document.getElementById('output').textContent = nextItem(); } ); </code></pre> <p>This is great! Now the only thing left to do is make sure it runs "after the <em>Elements</em> exist". There are two ways to do this, either by putting the <code>&lt;script&gt;</code> element after the elements it uses, or by listening for the <em>load event</em> on window, i.e.</p> <pre><code>window.addEventListener('load', function () { // DOM related JavaScript goes here }); </code></pre> <hr> <p><a href="http://jsfiddle.net/hrzshpma/" rel="noreferrer"><strong>DEMO</strong></a> of everything together</p> <hr> <p>If you want to do this multiple times or are mixing it with other <em>JavaScript</em>, you may need to consider variable name conflicts. The easiest way to get around this is by using an <em>IIFE</em> to create a "safe place" for your variables, but this answer is already long enough.</p>
19,402,207
Java variable placed on stack or heap
<p>I don't have much idea on Java.</p> <p>I was going through few links and found blog says "Java Primitives stored on stack", which I feel it depends on instance variable or local variable.</p> <p>After going through several links my conclusion is,</p> <hr> <p>Class variables – primitives – are stored on heap as a part of Object which it contains.</p> <p>Class variables – object(User Defined) – are stored on heap as a part of Object which it contains. This is true for both reference and actual object.</p> <p>Method Variables – Primitives – are stored on stack as a part of that stack frame.</p> <p>Method Variables – object(User Defined) – are stored on heap but a reference to that area on heap is stored on stack as a part of that stack frame. References can also be get stored on heap if Object contains another object in it.</p> <p>Static methods (in fact all methods) as well as static variables are stored in heap.</p> <p>Please correct me if my understanding is wrong. Thanks.</p>
19,402,293
3
2
null
2013-10-16 11:28:26.81 UTC
13
2020-08-20 23:25:34.62 UTC
null
null
null
null
1,012,372
null
1
29
java
17,180
<p>There are some optimizations in the JVM that may even use the Stack for Objects, this reduces the garbage collection effort.</p> <p>Classes are stored on a special part of the heap, but that depends on the JVM you use. (Permgen f.e. in Hotspot &lt;= 24).</p> <p>In general you should not have to think about where the data is stored, but more about the semantics like visibility and how long something lives. Your explanation in the questions looks good so far.</p>
502,763
Prefuse Toolkit: dynamically adding nodes and edges
<p>Does anyone have experience with the prefuse graph toolkit? Is it possible to change an already displayed graph, ie. add/remove nodes and/or edges, and have the display correctly adapt? </p> <p>For instance, prefuse comes with an example that visualizes a network of friends:</p> <blockquote> <p><a href="http://prefuse.org/doc/manual/introduction/example/Example.java" rel="nofollow noreferrer">http://prefuse.org/doc/manual/introduction/example/Example.java</a></p> </blockquote> <p>What I would like to do is something along the lines of this:</p> <pre><code>// -- 7. add new nodes on the fly ------------------------------------- new Timer(2000, new ActionListener() { private Node oldNode = graph.nodes().next(); // init with random node public void actionPerformed(ActionEvent e) { // insert new node // Node newNode = graph.addNode(); // insert new edge // graph.addEdge(oldNode, newNode); // remember node for next call // oldNode = newNode; } }).start(); </code></pre> <p>But it doesn't seem to work. Any hints?</p>
520,048
4
0
null
2009-02-02 10:21:39.547 UTC
10
2017-03-28 20:03:27.31 UTC
2017-03-28 20:03:27.31 UTC
null
1,571,709
Thomas
null
null
1
4
java|layout|graph-theory|prefuse
6,336
<p>As pointed out in my other post, the reason new nodes and edges are not visible in the original example is that the colors etc. for the nodes are not set correctly. One way to fix this is to explicitly call vis.run("color"); whenever a node or edge was added.</p> <p>Alternatively, we can ensure that the color action is always running, by initializing the ActionList to which we add it (called "color" in the original example) slightly differently:</p> <p>instead of</p> <pre><code>ActionList color = new ActionList(); </code></pre> <p>we could write</p> <pre><code>ActionList color = new ActionList(Activity.INFINITY); </code></pre> <p>This keeps the action list running indefinitely, so that new nodes/edges will automatically be initialized for their visual appearance.</p> <p>However, it is unclear to me whether this would actually be the preferred method - for things like a dynamic layout action (e.g. ForceDirectedLayout), such a declaration makes perfect sense, but for colors it seems to me that a constantly running coloring action is mostly overhead.</p> <p>So, perhaps the previously posted solution of just running the "color" action explicitly (but only once) whenever the graph gets extended, might be the better choice...</p>
934,479
how to adjust "is a type but is used like a variable"?
<p>I'm trying to generate some code in a web service. But it's returning 2 errors:</p> <p>1) List is a type but is used like a variable</p> <p>2) No overload for method 'Customer' takes '3 arguments'</p> <pre><code>[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class wstest : System.Web.Services.WebService { [WebMethod] public List&lt;Customer&gt; GetList() { List&lt;Customer&gt; li = List&lt;Customer&gt;(); li.Add(new Customer("yusuf", "karatoprak", "123456")); return li; } } public class Customer { private string name; private string surname; private string number; public string Name { get { return name; } set { name = value; } } public string SurName { get { return surname; } set { surname = value; } } public string Number { get { return number; } set { number = value; } } } </code></pre> <p>How can i adjust above error?</p>
934,488
4
1
null
2009-06-01 11:41:50.2 UTC
2
2015-05-04 17:59:36.557 UTC
2015-05-04 17:59:36.557 UTC
null
2,856,441
null
52,420
null
1
13
c#|.net|asp.net|generics
86,898
<p>The problem is at the line</p> <pre><code>List&lt;Customer&gt; li = List&lt;Customer&gt;(); </code></pre> <p>you need to add "new"</p> <pre><code>List&lt;Customer&gt; li = new List&lt;Customer&gt;(); </code></pre> <p>Additionally for the next line should be:</p> <pre><code>li.Add(new Customer{Name="yusuf", SurName="karatoprak", Number="123456"}); </code></pre> <p><strong>EDIT:</strong> If you are using VS2005, then you have to create a new constructor that takes the 3 parameters.</p> <pre><code>public Customer(string name, string surname, string number) { this.name = name; this.surname = surname; this.number = number; } </code></pre>
346,622
Opinions on type-punning in C++?
<p>I'm curious about conventions for type-punning pointers/arrays in C++. Here's the use case I have at the moment:</p> <blockquote> Compute a simple 32-bit checksum over a binary blob of data by treating it as an array of 32-bit integers (we know its total length is a multiple of 4), and then summing up all values and ignoring overflow. </blockquote> <p>I would expect such an function to look like this:</p> <pre><code>uint32_t compute_checksum(const char *data, size_t size) { const uint32_t *udata = /* ??? */; uint32_t checksum = 0; for (size_t i = 0; i != size / 4; ++i) checksum += udata[i]; return udata; } </code></pre> <p>Now the question I have is, what do you consider the "best" way to convert <code>data</code> to <code>udata</code>?</p> <p>C-style cast?</p> <pre><code>udata = (const uint32_t *)data </code></pre> <p>C++ cast that assumes all pointers are convertible?</p> <pre><code>udata = reinterpret_cast&lt;const uint32_t *&gt;(data) </code></pre> <p>C++ cast that between arbitrary pointer types using intermediate <code>void*</code>?</p> <pre><code>udata = static_cast&lt;const uint32_t *&gt;(static_cast&lt;const void *&gt;(data)) </code></pre> <p>Cast through a union?</p> <pre><code>union { const uint32_t *udata; const char *cdata; }; cdata = data; // now use udata </code></pre> <p>I fully realize that this will not be a 100% portable solution, but I am only expecting to use it on a small set of platforms where I know it works (namely unaligned memory accesses and compiler assumptions on pointer aliasing). What would you recommend?</p>
346,764
4
0
null
2008-12-06 19:13:29.767 UTC
9
2020-06-02 02:03:49.113 UTC
2010-02-10 06:20:21.587 UTC
Roger Pate
null
Tom
40,620
null
1
23
c++|casting|type-punning
10,078
<p>As far as the C++ standard is concerned, <a href="https://stackoverflow.com/questions/346622/opinions-on-type-punning-in-c#346675">litb</a>'s answer is completely correct and the most portable. Casting <code>const char *data</code> to a <code>const uint3_t *</code>, whether it be via a C-style cast, <code>static_cast</code>, or <code>reinterpret_cast</code>, breaks the strict aliasing rules (see <a href="http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html" rel="nofollow noreferrer">Understanding Strict Aliasing</a>). If you compile with full optimization, there's a good chance that the code will not do the right thing.</p> <p>Casting through a union (such as litb's <code>my_reint</code>) is probably the best solution, although it does technically violate the rule that if you write to a union through one member and read it through another, it results in undefined behavior. However, practically all compilers support this, and it results in the the expected result. If you absolutely desire to conform to the standard 100%, go with the bit-shifting method. Otherwise, I'd recommend going with casting through a union, which is likely to give you better performance.</p>
22,061,073
How do i get images file name from a given folder
<p>I have got a task to display all images inside a folder using jquery.</p> <p>For that i used the code </p> <pre><code>var imageFolder = '../../Images/Avatar/'; var imgsrc = imageFolder +''; </code></pre> <p>I need to get the images file name inside that folder avatar. How can I get the file name. There are lot of image files in that avatar folder also has some txt files.I only need jpg,png,gif images only.</p>
22,061,719
2
1
null
2014-02-27 06:49:15.66 UTC
7
2017-07-04 09:02:46.1 UTC
2014-02-27 06:57:55.297 UTC
null
1,677,272
null
1,752,012
null
1
5
javascript|jquery|html
42,303
<p>try this way </p> <p>HTML CODE:</p> <pre><code>&lt;div id='fileNames'&gt; &lt;/div&gt; </code></pre> <p><strong>JQUERY CODE:</strong></p> <pre><code>var fileExt = {}, fileExt[0]=".png", fileExt[1]=".jpg", fileExt[2]=".gif"; $.ajax({ //This will retrieve the contents of the folder if the folder is configured as 'browsable' url: '../../Images/Avatar/', success: function (data) { $("#fileNames").html('&lt;ul&gt;'); //List all png or jpg or gif file names in the page $(data).find("a:contains(" + fileExt[0] + "),a:contains(" + fileExt[1] + "),a:contains(" + fileExt[2] + ")").each(function () { var filename = this.href.replace(window.location.host, "").replace("http:///", ""); $("#fileNames").append( "&lt;li&gt;" + filename + "&lt;/li&gt;"); }); $("#fileNames").append('&lt;/ul&gt;'); } }); </code></pre> <p><em>Basic logic referred from this SO question <a href="https://stackoverflow.com/questions/18480550/how-to-load-all-the-images-from-one-of-my-folder-into-my-web-page-using-jquery">Here</a></em></p> <p>Happy Coding :)</p>
37,561,991
What is dtype('O'), in pandas?
<p>I have a dataframe in pandas and I'm trying to figure out what the types of its values are. I am unsure what the type is of column <code>'Test'</code>. However, when I run <code>myFrame['Test'].dtype</code>, I get;</p> <pre><code>dtype('O') </code></pre> <p>What does this mean?</p>
37,562,101
4
2
null
2016-06-01 07:22:00.597 UTC
36
2020-06-08 23:47:58.597 UTC
2020-06-08 23:47:58.597 UTC
null
202,229
null
1,613,983
null
1
168
python|pandas|numpy|dataframe|types
201,935
<p>It means:</p> <pre><code>'O' (Python) objects </code></pre> <p><a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.dtypes.html" rel="noreferrer">Source</a>.</p> <blockquote> <p>The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters. The item size must correspond to an existing type, or an error will be raised. The supported kinds are to an existing type, or an error will be raised. The supported kinds are:</p> </blockquote> <pre><code>'b' boolean 'i' (signed) integer 'u' unsigned integer 'f' floating-point 'c' complex-floating point 'O' (Python) objects 'S', 'a' (byte-)string 'U' Unicode 'V' raw data (void) </code></pre> <p>Another <a href="https://stackoverflow.com/a/42672574/2901002">answer</a> helps if need check <code>type</code>s.</p>
30,565,571
Redis - How to expire key daily
<p>I know that EXPIREAT in Redis is used to specify when a key will expire. My problem though is that it takes an absolute UNIX timestamp. I'm finding a hard time thinking about what I should set as an argument if I want the key to expire at the end of the day. </p> <p>This is how I set my key:</p> <blockquote> <p>client.set(key, body);</p> </blockquote> <p>So to set the expire at:</p> <blockquote> <p>client.expireat(key, ???);</p> </blockquote> <p>Any ideas? I'm using this with nodejs and sailsjs Thanks!</p>
30,565,736
3
1
null
2015-06-01 04:17:22.737 UTC
8
2017-10-04 16:40:52.033 UTC
null
null
null
null
3,138,528
null
1
31
node.js|unix|redis|timestamp|sails.js
56,934
<p>If you want to expire it 24 hrs later</p> <pre><code>client.expireat(key, parseInt((+new Date)/1000) + 86400); </code></pre> <p>Or if you want it to expire exactly at the end of today, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours"><code>.setHours</code></a> on a <code>new Date()</code> object to get the time at the end of the day, and use that.</p> <pre><code>var todayEnd = new Date().setHours(23, 59, 59, 999); client.expireat(key, parseInt(todayEnd/1000)); </code></pre>
51,654,757
Laravel eloquent with Trashed on relationship
<p>I need to be able to get a Models Relationship including its soft deleted elements, but only for this 1 instance. I do not want to change the model so that every time I use the relationship it returns all the soft deleted records too.</p> <p>How can I achieve this?</p> <p><strong>User Model</strong></p> <pre><code>class User extends Authenticatable { public function contacts(){ return $this-&gt;hasMany('App\Contacts','user_id','id'); } } </code></pre> <p><strong>Controller</strong></p> <pre><code>$user = User::findOrFail($id); //Need to be able to get the trashed contacts too, but only for this instance and in this function $user-&gt;contacts-&gt;withTrashed(); //Something like this return $user; </code></pre> <p>How can I get the trashed rows only this 1 time inside my controller?</p> <p>Thanks</p>
51,654,947
4
1
null
2018-08-02 13:21:17.023 UTC
2
2021-10-27 08:59:01.66 UTC
null
null
null
null
9,295,849
null
1
27
php|laravel|laravel-5|eloquent
49,661
<p>You can use <code>withTrashed</code> method in different ways.</p> <p>To associate the call with your relationship you can do as follows:</p> <pre><code>public function roles() { return $this-&gt;hasMany(Role::class)-&gt;withTrashed(); } </code></pre> <p>To use the same in the fly:</p> <pre><code>$user-&gt;roles()-&gt;withTrashed()-&gt;get(); </code></pre> <p>For your special scenario:</p> <pre><code>$user-&gt;contacts()-&gt;withTrashed()-&gt;get(); </code></pre>
51,626,224
How to configure services based on request in ASP.NET Core
<p>In ASP.NET Core we can register all dependencies during start up, which executed when application starts. Then registered dependencies will be injected in controller constructor.</p> <pre><code>public class ReportController { private IReportFactory _reportFactory; public ReportController(IReportFactory reportFactory) { _reportFactory = reportFactory; } public IActionResult Get() { vart report = _reportFactory.Create(); return Ok(report); } } </code></pre> <p>Now I want to inject different implementations of <code>IReportFactory</code> based on data in current request (User authorization level or some value in the querystring passed with an request).</p> <p>Question: is there any built-in abstraction(middleware) in ASP.NET Core where we can register another implementation of interface?</p> <p>What is the possible approach for this if there no built-in features?</p> <p><strong>Update</strong> <code>IReportFactory</code> interface was used as a simple example. Actually I have bunch of low level interfaces injected in different places. And now I want that different implementation of those low level interfaces will be injected based on request data.</p> <pre><code>public class OrderController { private IOrderService _orderService; public OrderController(IOrderService orderService) { _orderService = orderService; } public IActionResult Create() { var order = _orderService.Create(); return Ok(order); } } public class OrderService { private OrderBuilder _orderBuilder; private IShippingService _shippingService; // This now have many different implementations public OrderService( OrderBuilder _orderBuilder, IShippingService _shippingService) { _orderService = orderService; _shippingService = shippingService; } public Order Create() { var order = _orderBuilder.Build(); var order.ShippingInfo = _shippingService.Ship(); return order; } } </code></pre> <p>Because we know which implementation we need to use on entry point of our application (I think controller action can be considered as entry point of application), we want inject correct implementation already there - no changes required in already existed design.</p>
51,626,373
3
2
null
2018-08-01 05:57:06.273 UTC
9
2021-01-23 22:12:17.277 UTC
2018-08-01 07:56:51.673 UTC
null
455,493
null
10,147,020
null
1
15
c#|asp.net-core|dependency-injection
10,558
<p>No, you can't. The <code>IServiceCollection</code> is populated during application startup and built before <code>Configure</code> method is called. After that (container being built), the registrations can't be changed anymore.</p> <p>You can however implement an abstract factory, be it as factory method or as an interface/class. </p> <pre><code>// Its required to register the IHttpContextAccessor first services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;(); services.AddScoped&lt;IReportService&gt;(provider =&gt; { var httpContext = provider.GetRequired&lt;IHttpContextAccessor&gt;().HttpContext; if(httpContext.User.IsAuthorized) { return new AuthorizedUserReportService(...); // or resolve it provider.GetService&lt;AuthorizedUserReportService&gt;() } return new AnonymousUserReportService(...); // or resolve it provider.GetService&lt;AnonymousUserReportService&gt;() }); </code></pre> <p>Alternatively use an <a href="https://stackoverflow.com/questions/1943576/is-there-a-pattern-for-initializing-objects-created-via-a-di-container/1945023#1945023">abstract factory class</a></p>
46,745,365
Artisan migrate could not find driver
<p>I am trying to install Laravel. I have installed <code>Xampp</code>, but when I try to setup my database using <code>php artisan migrate</code>I get the error:</p> <blockquote> <p><strong>[Illuminate\Database\QueryException] could not find driver (SQL: select * from information_schema.tables where table_schema = homestead and table_name = migrations) [PDOException] could not find driver</strong></p> </blockquote> <p><code>config/database.php</code> file has the relevant connections:</p> <pre><code>'connections' =&gt; [ 'sqlite' =&gt; [ 'driver' =&gt; 'sqlite', 'database' =&gt; env('DB_DATABASE', database_path('database.sqlite')), 'prefix' =&gt; '', ], 'mysql' =&gt; [ 'driver' =&gt; 'mysql', 'host' =&gt; env('DB_HOST', '127.0.0.1'), 'port' =&gt; env('DB_PORT', '3306'), 'database' =&gt; env('DB_DATABASE', 'forge'), 'username' =&gt; env('DB_USERNAME', 'forge'), 'password' =&gt; env('DB_PASSWORD', ''), 'unix_socket' =&gt; env('DB_SOCKET', ''), 'charset' =&gt; 'utf8mb4', 'collation' =&gt; 'utf8mb4_unicode_ci', 'prefix' =&gt; '', 'strict' =&gt; true, 'engine' =&gt; null, ], 'pgsql' =&gt; [ 'driver' =&gt; 'pgsql', 'host' =&gt; env('DB_HOST', '127.0.0.1'), 'port' =&gt; env('DB_PORT', '5432'), 'database' =&gt; env('DB_DATABASE', 'forge'), 'username' =&gt; env('DB_USERNAME', 'forge'), 'password' =&gt; env('DB_PASSWORD', ''), 'charset' =&gt; 'utf8', 'prefix' =&gt; '', 'schema' =&gt; 'public', 'sslmode' =&gt; 'prefer', ], 'sqlsrv' =&gt; [ 'driver' =&gt; 'sqlsrv', 'host' =&gt; env('DB_HOST', 'localhost'), 'port' =&gt; env('DB_PORT', '1433'), 'database' =&gt; env('DB_DATABASE', 'forge'), 'username' =&gt; env('DB_USERNAME', 'forge'), 'password' =&gt; env('DB_PASSWORD', ''), 'charset' =&gt; 'utf8', 'prefix' =&gt; '', ], ], </code></pre> <p>Any ideas?</p>
47,929,207
20
3
null
2017-10-14 13:56:51.813 UTC
25
2022-07-07 10:39:20.933 UTC
2019-07-09 12:38:26.113 UTC
null
7,051,937
null
1,901,521
null
1
69
php|laravel
214,076
<p>In your php.ini configuration file simply uncomment the extension:</p> <pre><code>;extension=php_pdo_mysql.dll </code></pre> <p><em>(You can find your <strong>php.ini</strong> file in the php folder where your stack server is installed.)</em></p> <p>If you're on <strong>Windows</strong> make it: <code>extension=php_pdo_mysql.dll</code></p> <p>If you're on <strong>Linux</strong> make it: <code>extension=pdo_mysql.so</code></p> <p>And do a quick server restart.</p> <p><em>If this isn't working for you, you may need to install <strong>pdo_mysql</strong> extension into your php library.</em></p>
36,564,596
How to limit the Maximum number of parallel tasks in c#
<p>I have a collection of 1000 input message to process. I'm looping the input collection and starting the new task for each message to get processed.</p> <pre><code>//Assume this messages collection contains 1000 items var messages = new List&lt;string&gt;(); foreach (var msg in messages) { Task.Factory.StartNew(() =&gt; { Process(msg); }); } </code></pre> <p>Can we guess how many maximum messages simultaneously get processed at the time (assuming normal Quad core processor), or can we limit the maximum number of messages to be processed at the time? </p> <p>How to ensure this message get processed in the same sequence/order of the Collection?</p>
36,571,420
11
4
null
2016-04-12 05:50:26.31 UTC
17
2021-09-15 12:12:53.18 UTC
2016-04-16 16:40:59.453 UTC
null
1,310,368
null
1,310,368
null
1
64
c#|.net|asynchronous
68,502
<p>SemaphoreSlim is a very good solution in this case and I higly recommend OP to try this, but @Manoj's answer has flaw as mentioned in comments.semaphore should be waited before spawning the task like this.</p> <p><strong>Updated Answer:</strong> As @Vasyl pointed out Semaphore may be disposed before completion of tasks and will raise exception when <code>Release()</code> method is called so before exiting the using block must wait for the completion of all created Tasks.</p> <pre><code>int maxConcurrency=10; var messages = new List&lt;string&gt;(); using(SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(maxConcurrency)) { List&lt;Task&gt; tasks = new List&lt;Task&gt;(); foreach(var msg in messages) { concurrencySemaphore.Wait(); var t = Task.Factory.StartNew(() =&gt; { try { Process(msg); } finally { concurrencySemaphore.Release(); } }); tasks.Add(t); } Task.WaitAll(tasks.ToArray()); } </code></pre> <p><strong>Answer to Comments</strong> for those who want to see how semaphore can be disposed without <code>Task.WaitAll</code> Run below code in console app and this exception will be raised.</p> <blockquote> <p>System.ObjectDisposedException: 'The semaphore has been disposed.'</p> </blockquote> <pre><code>static void Main(string[] args) { int maxConcurrency = 5; List&lt;string&gt; messages = Enumerable.Range(1, 15).Select(e =&gt; e.ToString()).ToList(); using (SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(maxConcurrency)) { List&lt;Task&gt; tasks = new List&lt;Task&gt;(); foreach (var msg in messages) { concurrencySemaphore.Wait(); var t = Task.Factory.StartNew(() =&gt; { try { Process(msg); } finally { concurrencySemaphore.Release(); } }); tasks.Add(t); } // Task.WaitAll(tasks.ToArray()); } Console.WriteLine("Exited using block"); Console.ReadKey(); } private static void Process(string msg) { Thread.Sleep(2000); Console.WriteLine(msg); } </code></pre>
36,367,532
How can I conditionally import an ES6 module?
<p>I need to do something like:</p> <pre><code>if (condition) { import something from 'something'; } // ... if (something) { something.doStuff(); } </code></pre> <p>The above code does not compile; it throws <code>SyntaxError: ... 'import' and 'export' may only appear at the top level</code>.</p> <p>I tried using <code>System.import</code> as shown <a href="http://www.2ality.com/2013/07/es6-modules.html#module-loader-api" rel="noreferrer">here</a>, but I don't know where <code>System</code> comes from. Is it an ES6 proposal that didn't end up being accepted? The link to "programmatic API" from that article dumps me to a <a href="http://wiki.ecmascript.org/doku.php?id=harmony:module_loaders" rel="noreferrer">deprecated docs page</a>.</p>
46,543,835
15
4
null
2016-04-01 23:44:59.197 UTC
40
2022-08-26 20:08:49.933 UTC
2016-04-01 23:45:48.557 UTC
user4227915
null
null
222,356
null
1
297
javascript|module|ecmascript-6
203,731
<p>We do have dynamic imports proposal now with ECMA. This is in stage 3. This is also available as <a href="https://babeljs.io/docs/plugins/syntax-dynamic-import/" rel="noreferrer">babel-preset</a>.</p> <p>Following is way to do conditional rendering as per your case.</p> <pre><code>if (condition) { import('something') .then((something) =&gt; { console.log(something.something); }); } </code></pre> <p>This basically returns a promise. Resolution of promise is expected to have the module. The proposal also have other features like multiple dynamic imports, default imports, js file import etc. You can find more information about <a href="http://2ality.com/2017/01/import-operator.html" rel="noreferrer">dynamic imports here</a>. </p>
14,136,265
Get Child Nodes from an XML File
<p>I have an XML File like below</p> <pre><code>&lt;Attachment&gt; &lt;FileName&gt;Perimeter SRS.docx&lt;/FileName&gt; &lt;FileSize&gt;15572&lt;/FileSize&gt; &lt;ActivityName&gt;ActivityNamePerimeter SRS.docx&lt;/ActivityName&gt; &lt;UserAlias&gt;JameelM&lt;/UserAlias&gt; &lt;DocumentTransferId&gt;7123eb83-d768-4a58-be46-0dfaf1297b97&lt;/DocumentTransferId&gt; &lt;EngagementName&gt;EAuditEngagementNameNew&lt;/EngagementName&gt; &lt;Sender&gt;[email protected]&lt;/Sender&gt; &lt;/Attachment&gt; </code></pre> <p>I read these xml file like below</p> <pre><code>var doc = new XmlDocument(); doc.Load(files); foreach (XmlElement pointCoord in doc.SelectNodes("/Attachment")) { } </code></pre> <p>I need to get each child node value inside the Attachment node. How can i get these xml elements from the xml node list?</p>
14,136,472
3
2
null
2013-01-03 09:41:38.007 UTC
2
2018-03-27 15:54:09.423 UTC
2018-03-27 15:53:28.66 UTC
null
4,165,377
null
1,668,501
null
1
5
c#|.net|xml
46,203
<blockquote> <p>I need to get each child node value inside the Attachment node. </p> </blockquote> <p>Your question is very unclear, but it <em>looks</em> like it's as simple as:</p> <pre><code>foreach (XmlNode node in doc.DocumentElement.ChildNodes) { } </code></pre> <p>After all, in the document you've shown us, the <code>Attachment</code> <em>is</em> the document element. No XPath is required.</p> <p>As an aside, if you're using .NET 3.5 or higher, LINQ to XML is a <em>much</em> nicer XML API than the old DOM (<code>XmlDocument</code> etc) API.</p>
25,273,075
Editing my vimrc file on a mac
<p>I'm using Mac OSX (10.9) and I'm trying to configure my vimrc file by adding "set number". I found my vimrc file in user/share/vim/ but I can't edit it because it's read-only. How can I fix this and read it?</p>
25,273,147
1
2
null
2014-08-12 20:01:03.29 UTC
18
2014-08-12 20:04:56.047 UTC
null
null
null
null
3,521,929
null
1
43
vim
90,573
<p>You should not overwrite the system vimrc for various reasons. One being that with a system upgrade it will be overwritten.</p> <p>Instead you can create a new .vimrc file in your home directory. Open the terminal and enter:</p> <pre><code> vim ~/.vimrc </code></pre> <p>There you can enter your various configurations. When done, you need to save the file and restart vim.</p> <p>To be sure which vimrc is being used, you can ask inside of vim by typing:</p> <pre><code> :echo $MYVIMRC </code></pre>
25,394,536
UIImage on swift can't check for nil
<p>I have the following code on Swift</p> <pre><code>var image = UIImage(contentsOfFile: filePath) if image != nil { return image } </code></pre> <p>It used to work great, but now on Xcode Beta 6, this returns a warning</p> <pre><code> 'UIImage' is not a subtype of 'NSString' </code></pre> <p>I don't know what to do, I tried different things like</p> <pre><code> if let image = UIImage(contentsOfFile: filePath) { return image } </code></pre> <p>But the error changes to:</p> <pre><code>Bound value in a conditional binding must be of Optional type </code></pre> <p>Is this a bug on Xcode6 beta 6 or am I doing something wrong?</p>
25,394,568
6
3
null
2014-08-19 23:23:19.45 UTC
7
2021-07-06 08:04:56.787 UTC
null
null
null
null
3,931,494
null
1
41
ios|xcode|swift|uiimage
57,990
<p><strong>Update</strong></p> <p>Swift now added the concept of failable initializers and UIImage is now one of them. The initializer returns an Optional so if the image cannot be created it will return nil.</p> <hr> <p>Variables by default cannot be <code>nil</code>. That is why you are getting an error when trying to compare <code>image</code> to <code>nil</code>. You need to explicitly define your variable as <a href="http://drewag.me/posts/what-is-an-optional-in-swift" rel="noreferrer">optional</a>:</p> <pre><code>let image: UIImage? = UIImage(contentsOfFile: filePath) if image != nil { return image! } </code></pre>
39,419,596
Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml
<p>After solving a JDK zero value error, now I'm facing this one. I did a little research, but it seems I can't get to the point. Here is the log error: </p> <pre><code>FATAL EXCEPTION: main E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{.MainActivity}: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020013 E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2204) E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2254) E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141) E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137) E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5069) E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511) E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime: Caused by: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020013 E/AndroidRuntime: at android.content.res.Resources.loadDrawable(Resources.java:1953) E/AndroidRuntime: at android.content.res.Resources.getDrawable(Resources.java:660) E/AndroidRuntime: at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:354) E/AndroidRuntime: at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:193) E/AndroidRuntime: at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:181) E/AndroidRuntime: at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:689) E/AndroidRuntime: at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:186) E/AndroidRuntime: at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:77) E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplBase.&lt;init&gt;(AppCompatDelegateImplBase.java:83) E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.&lt;init&gt;(AppCompatDelegateImplV7.java:146) E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV11.&lt;init&gt;(AppCompatDelegateImplV11.java:28) E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV14.&lt;init&gt;(AppCompatDelegateImplV14.java:41) E/AndroidRuntime: at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:193) E/AndroidRuntime: at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:173) E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:511) E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71) E/AndroidRuntime: at .MainActivity.onCreate(MainActivity.java:29) E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5104) E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1092) E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148) E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2254)  E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141)  E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)  E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)  E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)  E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5069)  E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)  E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)  E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)  E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)  E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)  E/AndroidRuntime: Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #17: invalid drawable tag vector E/AndroidRuntime: at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:881) E/AndroidRuntime: at android.graphics.drawable.Drawable.createFromXml(Drawable.java:822) E/AndroidRuntime: at android.content.res.Resources.loadDrawable(Resources.java:1950) E/AndroidRuntime: at android.content.res.Resources.getDrawable(Resources.java:660)  E/AndroidRuntime: at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:354)  E/AndroidRuntime: at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:193)  E/AndroidRuntime: at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:181)  E/AndroidRuntime: at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:689)  E/AndroidRuntime: at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:186)  E/AndroidRuntime: at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:77)  E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplBase.&lt;init&gt;(AppCompatDelegateImplBase.java:83)  E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.&lt;init&gt;(AppCompatDelegateImplV7.java:146)  E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV11.&lt;init&gt;(AppCompatDelegateImplV11.java:28)  E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV14.&lt;init&gt;(AppCompatDelegateImplV14.java:41)  E/AndroidRuntime: at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:193)  E/AndroidRuntime: at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:173)  E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:511)  E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)  E/AndroidRuntime: at .MainActivity.onCreate(MainActivity.java:29)  E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5104)  E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1092)  E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)  E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2254)  E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141)  E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)  E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)  E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)  E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5069)  E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)  E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)  E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)  E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)  E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)  </code></pre> <p>I'm really confused about what it can be, I read and can't get to the error:</p> <p>My app:gradle is this:</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "24.0.2" defaultConfig { applicationId "me.me2.com.myapp" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.android.support:recyclerview-v7:23.4.0' compile 'com.android.support:cardview-v7:23.4.0' compile 'com.google.firebase:firebase-storage:9.4.0' compile 'com.google.firebase:firebase-database:9.4.0' compile 'com.google.firebase:firebase-auth:9.4.0' compile 'com.firebaseui:firebase-ui-database:0.4.4' compile 'com.squareup.picasso:picasso:2.5.2' } apply plugin: 'com.google.gms.google-services' </code></pre> <p>Here is my style folder:</p> <pre><code>&lt;resources&gt; &lt;!-- Base application theme. --&gt; &lt;style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;!-- Customize your theme here. --&gt; &lt;item name="colorPrimary"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/colorPrimaryDark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/colorAccent&lt;/item&gt; &lt;/style&gt; &lt;style name="AppTheme.NoActionBar"&gt; &lt;item name="windowActionBar"&gt;false&lt;/item&gt; &lt;item name="windowNoTitle"&gt;true&lt;/item&gt; &lt;/style&gt; &lt;style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /&gt; &lt;style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /&gt; &lt;style name="Divider"&gt; &lt;item name="android:layout_width"&gt;match_parent&lt;/item&gt; &lt;item name="android:layout_height"&gt;1dp&lt;/item&gt; &lt;item name="android:background"&gt;?android:attr/listDivider&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>And my mainactivity.class if needed:</p> <pre><code>public class MainActivity extends AppCompatActivity { VideoView videoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // VideoView videoView = (VideoView) findViewById(R.id.videoview); videoView.setVideoURI(Uri.parse("android.resource://"+getPackageName() + "/" +R.raw.video)); videoView.requestFocus(); /** * Loop */ videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { videoView.start(); mp.setLooping(true); } }); } public void Login(View view) { Intent intent = new Intent(this, FragmentMain.class); startActivity(intent); // finish(); } public void Registro(View view) { Intent intent = new Intent(this, Registro.class); startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } </code></pre> <p>Thanks.</p>
39,419,701
18
1
null
2016-09-09 20:57:56.04 UTC
16
2021-01-18 08:30:02.847 UTC
2018-12-03 14:34:17.917 UTC
null
6,398,434
user6099735
null
null
1
56
android|android-layout|android-studio|gradle|android-gradle-plugin
82,761
<p>IF you're using Gradle Plugin 2.0, you need to make changes in your <code>gradle</code>:</p> <pre><code>// Gradle Plugin 2.0+ android { defaultConfig { vectorDrawables.useSupportLibrary = true } } </code></pre> <p>If you are using Gradle 1.5 you’ll use instead of previus:</p> <pre><code>// Gradle Plugin 1.5 android { defaultConfig { // Stops the Gradle plugin's automatic rasterization of vectors generatedDensities = [] } // Flag to tell aapt to keep the attribute ids around // This is handled for you by the 2.0+ Gradle Plugin aaptOptions { additionalParameters "--no-version-vectors" } } </code></pre> <p>Check also: <a href="https://stackoverflow.com/questions/35622438/update-android-support-library-to-23-2-0-cause-error-xmlpullparserexception-bin">Update Android Support Library to 23.2.0 cause error: XmlPullParserException Binary XML file line #17&lt;vector&gt; tag requires viewportWidth &gt; 0</a>.</p> <p>Android Support Library Ref.: <a href="http://android-developers.blogspot.in/2016/02/android-support-library-232.html" rel="noreferrer">Support Vector Drawables and Animated Vector Drawables</a>.</p> <p>Also update Android Support dependencies from </p> <pre><code>compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.android.support:recyclerview-v7:23.4.0' compile 'com.android.support:cardview-v7:23.4.0' </code></pre> <p>to</p> <pre><code>compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.android.support:design:24.2.0' compile 'com.android.support:recyclerview-v7:24.2.0' compile 'com.android.support:cardview-v7:24.2.0' </code></pre> <p>as you're already using build-tools in version of <code>24.0.2</code>.</p>
6,446,699
How do you bind a CollectionContainer to a collection in a view model?
<p>I have a view model with a property that exposes a collection of things. I have a ComboBox whose ItemsSource property is bound to this collection. Now the user can select from the list.</p> <p>I want to allow the user to clear the selection, so I want to add an item (that is Null) to ComboBox. It's pretty straightforward.</p> <p>I decided to try and use a CompositeCollection for the ItemsSource so that I could add the items in the existing list to the ComboBox as well as the extra Null item.</p> <p>After fighting with this for a while I decided to return to the documentation on the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.compositecollection.aspx" rel="noreferrer">CompositeCollection Class</a>. I copied their example and the modified it to use a view model instead of Static Resources.</p> <p>I discovered that no items show up in the list when I bind the CollectionContainer to the list exposed by the ViewModel.</p> <p>I'm not sure how to get around this problem and I'm looking for any advice on this topic.</p> <p>Here is my XAML code:</p> <pre><code>&lt;Window Background="CornflowerBlue" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:TryingWPF" x:Class="CompositeCollections" Title="CompositeCollections" SizeToContent="WidthAndHeight"&gt; &lt;Window.Resources&gt; &lt;c:CompositeCollectionVM x:Key="CompositeCollectionVM"/&gt; &lt;XmlDataProvider x:Key="GreekHeroesData" XPath="GreekHeroes/Hero"&gt; &lt;x:XData&gt; &lt;GreekHeroes xmlns=""&gt; &lt;Hero Name="Jason" /&gt; &lt;Hero Name="Hercules" /&gt; &lt;Hero Name="Bellerophon" /&gt; &lt;Hero Name="Theseus" /&gt; &lt;Hero Name="Odysseus" /&gt; &lt;Hero Name="Perseus" /&gt; &lt;/GreekHeroes&gt; &lt;/x:XData&gt; &lt;/XmlDataProvider&gt; &lt;DataTemplate DataType="{x:Type c:GreekGod}"&gt; &lt;TextBlock Text="{Binding Path=Name}" Foreground="Gold"/&gt; &lt;/DataTemplate&gt; &lt;DataTemplate DataType="Hero"&gt; &lt;TextBlock Text="{Binding XPath=@Name}" Foreground="Cyan"/&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;StackPanel DataContext="{StaticResource CompositeCollectionVM}"&gt; &lt;TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center" Foreground="WhiteSmoke"&gt;Trying Composite Collections&lt;/TextBlock&gt; &lt;DockPanel&gt; &lt;ListBox Name="myListBox" Height="300" Background="#99333333"&gt; &lt;ListBox.ItemsSource&gt; &lt;CompositeCollection&gt; &lt;CollectionContainer Collection="{Binding GreekGods}" /&gt; &lt;CollectionContainer Collection="{Binding Source={StaticResource GreekHeroesData}}" /&gt; &lt;ListBoxItem Foreground="Magenta"&gt;Other Listbox Item 1&lt;/ListBoxItem&gt; &lt;ListBoxItem Foreground="Magenta"&gt;Other Listbox Item 2&lt;/ListBoxItem&gt; &lt;/CompositeCollection&gt; &lt;/ListBox.ItemsSource&gt; &lt;/ListBox&gt; &lt;ListBox ItemsSource="{Binding GreekGods}" Background="#99333333" Margin="5,0" HorizontalAlignment="Right"&gt; &lt;/ListBox&gt; &lt;/DockPanel&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>(As you can see when I bind the ItemsSource of the second ListBox to the list property...the items show up)</p> <p>And here is my VB.NET code that makes the XAML code work:</p> <pre class="lang-vb prettyprint-override"><code>Public Class CompositeCollections End Class Public Class GreekGod Public Property GreekName Public Property Name Public Property Description Public Sub New(ByVal greekName As String, ByVal englishName As String, ByVal description As String) Me.GreekName = greekName Me.Name = englishName Me.Description = description End Sub End Class Public Class CompositeCollectionVM Public Property GreekGods As System.Collections.ObjectModel.ObservableCollection(Of GreekGod) Public Sub New() GreekGods = New System.Collections.ObjectModel.ObservableCollection(Of GreekGod) GreekGods.Add(New GreekGod("Ἀφροδίτη (Venus)", "Aphrodite", "Goddess of love and beauty. Although married to Hephaestus she had many lovers, most notably Ares. She was depicted as a beautiful woman usually accompanied by her son Eros. Her symbols include the rose, scallop shell, and myrtle wreath. Her sacred animal is the dove.")) GreekGods.Add(New GreekGod("Ἀπόλλων (Apóllō)", "Apollo", "God of music, healing, plague, prophecies, poetry, and archery; associated with light, truth and the sun. He is Artemis's twin brother and Hermes elder brother, and son of Zeus and Leto. He was depicted as a handsome, beardless youth with long hair and various attributes including a laurel wreath, bow and quiver, raven, and lyre. Apollo's sacred animal are red cattle.")) GreekGods.Add(New GreekGod("Ἄρης (Mars)", "Ares", "God of war, bloodlust, violence, manly courage, and civil order. The son of Zeus and Hera, he was depicted as either a mature, bearded warrior dressed in battle arms, or a nude beardless youth with helm and spear. His attributes are golden armour and a bronze-tipped spear. His sacred animals are the vulture, venomous snakes, alligators, and dogs.")) GreekGods.Add(New GreekGod("Ἄρτεμις (Diana)", "Artemis", "Virgin goddess of the hunt, wilderness, wild animals, childbirth and plague. In later times she became associated with the moon. She is the daughter of Zeus and Leto, and twin sister of Apollo. In art she was usually depicted as a young woman dressed in a short knee-length chiton and equipped with a hunting bow and a quiver of arrows. In addition to the bow, her attributes include hunting spears, animal pelts, deer and other wild animals. Her sacred animals are deer, bears, and wild boars.")) GreekGods.Add(New GreekGod("Ἀθηνᾶ (Minerva)", "Athena", "Goddess of wisdom, warfare, battle strategy, heroic endeavour, handicrafts and reason. According to most traditions she was born from Zeus's head. She was depicted crowned with a crested helm, armed with shield (Aegis), which holds medusa's head to paralyze her enemies who looked at it and a spear. Her symbols include the aegis and the olive tree. She is commonly shown accompanied by her sacred animal, the snowy owl.")) GreekGods.Add(New GreekGod("Δημήτηρ (Ceres)", "Demeter", "Goddess of agriculture, horticulture, grain and harvest. Demeter is a daughter of Cronus and Rhea and sister of Zeus, by whom she bore Persephone. She was depicted as a mature woman, often crowned and holding sheafs of wheat and a torch. Her symbols are the Cornucopia (horn of plenty), wheat-ears, the winged serpent and the lotus staff. Her sacred animals are pigs and snakes.")) GreekGods.Add(New GreekGod("Διόνυσος (Bacchus)", "Dionysos", "God of wine, parties and festivals, madness, civilization, drunkenness and pleasure at forever young. He was depicted in art as either an older bearded god or a pretty effeminate, long-haired youth. His attributes include the thyrsus (a pinecone-tipped staff), drinking cup, grape vine, and a crown of ivy. Animals sacred to him include dolphins, serpents, tigers, panthers, and donkeys. A later addition to the Olympians, in some accounts he replaced Hestia.")) GreekGods.Add(New GreekGod("ᾍδης (Hádēs) or Πλούτων (Ploútón)", "Hades or Pluto", "King of the Underworld and god of the dead and the hidden wealth of the Earth. His consort is Persephone and his attributes are the key of Hades, the Helm of Darkness, and the three-headed dog, Cerberus. The screech owl was sacred to him. Despite being the son of Cronus and Rhea and the elder brother of Zeus, as a chthonic god he is only rarely listed among the Olympians. The name Pluto became more common in the Classical period with the mystery religions and Athenian literature.")) GreekGods.Add(New GreekGod("Ἥφαιστος (Hḗphaistos)", "Hephaestus or Vulcan", "Crippled god of fire, metalworking, stonemasonry, sculpture and volcanism. The son of Hera alone, he is the smith of the gods and the husband of the adulterous Aphrodite. He was usually depicted as a bearded man holding hammer and tongs—the tools of a smith—and riding a donkey. His symbols are the hammer, tongs, and anvil. His sacred animals are the donkey, the guard dog and the crane. When he was born, he was thrown off of Mount Olympus by Hera as he was considered ugly.")) GreekGods.Add(New GreekGod("Ἥρα (Juno)", "Hera", "Queen of marriage, women, childbirth, heirs, kings and empires. She is daughter of Cronus and Rhea. She was usually depicted as a beautiful woman wearing a crown and veil and holding a royal, lotus-tipped staff. Her sacred animals are the cow, the peacock. She is the eternal wife of Zeus.")) GreekGods.Add(New GreekGod("Ἡρμῆς (Mercury)", "Hermes", "God of travel, messengers, trade, thievery, cunning wiles, language, writing, diplomacy, athletics, and animal husbandry. He is the messenger of the gods, a psychopomp who leads the souls of the dead into Hades' realm, and the son of Zeus and Maia. He was depicted either as a handsome and athletic beardless youth, or as an older bearded man. His attributes include the herald's wand or caduceus, winged sandals, and a traveler's cap. His sacred animals are the tortoise, the ram, and the hawk.")) GreekGods.Add(New GreekGod("Ἑστία (Vesta)", "Hestia", "Virgin goddess of the hearth, home and cooking. She is a daughter of Rhea and Cronus and sister of Zeus. She was depicted as a modestly veiled woman, whose symbols are the hearth and kettle. In some accounts, she gave up her seat as one of the Twelve Olympians to tend to the sacred flame on Mount Olympus for Dionysus.")) GreekGods.Add(New GreekGod("Ποσειδῶν (Neptune)", "Poseidon", "God of the sea, rivers, floods, droughts, storms, earthquakes, and the creator of horses; known as the 'Earth Shaker' or 'Storm Bringer'. He is a son of Cronus and Rhea and brother to Zeus and Hades. In classical artwork, he was depicted as a mature man of sturdy build with a dark beard, and holding a trident. The horse and the dolphin are sacred to him.")) GreekGods.Add(New GreekGod("Ζεύς (Jupiter)", "Zeus", "The king of the gods, the ruler of Mount Olympus and the god of the sky, weather, thunder, law, order, and fate. He is the youngest son of Cronus and Rhea, whom he overthrew after Cronus swallowed his brothers and sisters and he is brother-husband to Hera. In artwork, he was depicted as a regal, mature man with a sturdy figure and dark beard. His usual attributes are the royal sceptre and the lightning bolt. His main attribute was his master bolt. His sacred animals are the eagle and the bull.")) End Sub End Class </code></pre> <p>Thanks for your help!</p> <p><strong>EDIT:</strong></p> <p>H.B.'s answer worked perfectly. Here is the updated working XAML:</p> <pre><code>&lt;Window Background="CornflowerBlue" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:TryingWPF" x:Class="CompositeCollections" Title="CompositeCollections" SizeToContent="WidthAndHeight"&gt; &lt;Window.Resources&gt; &lt;c:CompositeCollectionVM x:Key="CompositeCollectionVM"/&gt; &lt;XmlDataProvider x:Key="GreekHeroesData" XPath="GreekHeroes/Hero"&gt; &lt;x:XData&gt; &lt;GreekHeroes xmlns=""&gt; &lt;Hero Name="Jason" /&gt; &lt;Hero Name="Hercules" /&gt; &lt;Hero Name="Bellerophon" /&gt; &lt;Hero Name="Theseus" /&gt; &lt;Hero Name="Odysseus" /&gt; &lt;Hero Name="Perseus" /&gt; &lt;/GreekHeroes&gt; &lt;/x:XData&gt; &lt;/XmlDataProvider&gt; &lt;DataTemplate DataType="{x:Type c:GreekGod}"&gt; &lt;TextBlock Text="{Binding Path=Name}" Foreground="Gold"/&gt; &lt;/DataTemplate&gt; &lt;DataTemplate DataType="Hero"&gt; &lt;TextBlock Text="{Binding XPath=@Name}" Foreground="Cyan"/&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;StackPanel x:Name="myStackPanel" DataContext="{StaticResource CompositeCollectionVM}"&gt; &lt;StackPanel.Resources&gt; &lt;CompositeCollection x:Key="compCollection"&gt; &lt;CollectionContainer Collection="{Binding DataContext.GreekGods, Source={x:Reference myStackPanel}}" /&gt; &lt;CollectionContainer Collection="{Binding Source={StaticResource GreekHeroesData}}" /&gt; &lt;ListBoxItem Foreground="Magenta"&gt;Other Listbox Item 1&lt;/ListBoxItem&gt; &lt;ListBoxItem Foreground="Magenta"&gt;Other Listbox Item 2&lt;/ListBoxItem&gt; &lt;/CompositeCollection&gt; &lt;/StackPanel.Resources&gt; &lt;TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center" Foreground="WhiteSmoke"&gt;Trying Composite Collections&lt;/TextBlock&gt; &lt;DockPanel&gt; &lt;ListBox Name="compositeListBox" ItemsSource="{Binding Source={StaticResource compCollection}}" Height="300" Background="#99333333" &gt; &lt;/ListBox&gt; &lt;ListBox Name="greekGodsListBox" ItemsSource="{Binding GreekGods}" Background="#99333333" Margin="5,0" HorizontalAlignment="Right"&gt; &lt;/ListBox&gt; &lt;/DockPanel&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre>
6,446,923
2
1
null
2011-06-22 21:18:16 UTC
17
2016-08-02 19:52:42.783 UTC
2014-05-12 13:45:25.603 UTC
null
140,420
null
140,420
null
1
57
wpf|vb.net|xaml|data-binding
33,840
<p>The <code>CompositeCollection</code> has no <code>DataContext</code>, the bindings in the <code>CollectionContainers</code> will not work if they bind directly to a property (which implicitly uses the <code>DataContext</code> as source).</p> <p>You need to explicitly specify a source, i would suggest you name the control with your <code>DataContext</code> and use <a href="http://msdn.microsoft.com/en-us/library/ee795380.aspx" rel="noreferrer"><code>x:Reference</code></a> to get it (<code>ElementName</code> will <em>not</em> work) or you use a <code>StaticResource</code>, e.g.</p> <pre><code>&lt;CollectionContainer Collection="{Binding DataContext.GreekGods, Source={x:Reference myStackPanel}}"/&gt; </code></pre> <pre><code>&lt;CollectionContainer Collection="{Binding GreekGods, Source={StaticResource CompositeCollectionVM}}"/&gt; </code></pre> <p>Note that when using <code>x:Reference</code> the compiler easily trips you up with cyclical dependency errors, to avoid those place your <code>CompositeCollection</code> in the resources of the control you reference, then insert it wherever it belongs using the <code>StaticResource</code> markup extension.</p>
7,276,936
Start Debugger in Code
<p>I need to debug an application that is started from a one-click install. (VS 2010, Excel VSTO with Office 7). Based on login credentials supplied to the one-click installer application, the user should see one of two splash pages. This all works fine on my machine, but when deployed, changing from the default to the second splash page results in an error. </p> <p>For the life of me, I can't figure out how to debug the process from within VS2010. I can attach to the login before entering the credentials, but I can't attach to Excel because it isn't launched until I click the OK button. </p> <p>So, is there some way to have Excel, or rather, my code call the debugger as it is instantiated so I can figure out why my image resource isn't available in the deployed application? </p> <p>Thanks. </p> <p>Randy</p>
7,276,957
4
3
null
2011-09-01 21:45:01.52 UTC
6
2022-03-26 08:20:53.32 UTC
null
null
null
null
16,851
null
1
59
c#|visual-studio-2010|debugging
41,331
<pre><code>System.Diagnostics.Debugger.Launch(); </code></pre>
21,479,079
How to JOIN three tables in Codeigniter
<p>I'm using codeigniter framework to develop one music cms. i have 3 tables in mysql database, Currently im working in "Album" Table and "Model, Controller". i want to SELECT "Album" Table 1 and JOIN "Album" -> "cat_id" with "Category" -> "cat_id", and fetch all categories records.</p> <p>Then i want to JOIN "Album" -> "album_id" on "Soundtrack" -> "album_id" then fetch all soundtrack records A to Z.</p> <p>Please somebody help me to show proper codeigniter query, how i can SELECT and JOIN Tables then fetch records from 3 tables, ?</p> <p><strong>Table 1 -> Category</strong></p> <ul> <li><p>cat_id</p></li> <li><p>cat_name</p></li> <li>cat_title</li> <li><p>date</p> <p><strong>Table 2 -> Album</strong></p></li> <li>cat_id</li> <li><p>album_id</p></li> <li><p>album_title</p></li> <li><p>album_details</p> <p><strong>Table 3 -> Soundtrack</strong></p></li> <li><p>album_id</p></li> <li><p>track_title</p></li> <li>track_url</li> <li>date</li> </ul>
21,479,191
6
2
null
2014-01-31 11:33:28.447 UTC
4
2021-05-03 04:44:53.287 UTC
null
null
null
null
1,218,948
null
1
20
php|mysql|codeigniter|join
119,628
<p>Use this code in model</p> <pre><code>public function funcname($id) { $this-&gt;db-&gt;select('*'); $this-&gt;db-&gt;from('Album a'); $this-&gt;db-&gt;join('Category b', 'b.cat_id=a.cat_id', 'left'); $this-&gt;db-&gt;join('Soundtrack c', 'c.album_id=a.album_id', 'left'); $this-&gt;db-&gt;where('c.album_id',$id); $this-&gt;db-&gt;order_by('c.track_title','asc'); $query = $this-&gt;db-&gt;get(); if($query-&gt;num_rows() != 0) { return $query-&gt;result_array(); } else { return false; } } </code></pre>
21,575,310
Converting "normal" std::string to utf-8
<p>Let's see if I can explain this without too many factual errors...</p> <p>I'm writing a string class and I want it to use <code>utf-8</code> (stored in a std::string) as it's internal storage. I want it to be able to take both "normal" <code>std::string</code> and <code>std::wstring</code> as input and output.</p> <p>Working with std::wstring is not a problem, I can use <code>std::codecvt_utf8&lt;wchar_t&gt;</code> to convert both from and to std::wstring.</p> <p>However after extensive googling and searching on SO I have yet to find a way to convert between a "normal/default" C++ std::string (which I assume in Windows is using the local system localization?) and an utf-8 std::string.</p> <p>I guess one option would be to first convert the std::string to an std::wstring using <code>std::codecvt&lt;wchar_t, char&gt;</code> and then convert it to utf-8 as above, but this seems quite inefficient given that at least the first 128 values of a char should translate straight over to utf-8 without conversion regardless of localization if I understand correctly.</p> <p>I found this similar question: <a href="https://stackoverflow.com/questions/20275824/c-how-to-convert-ascii-or-ansi-to-utf8-and-stores-in-stdstring">C++: how to convert ASCII or ANSI to UTF8 and stores in std::string</a> Although I'm a bit skeptic towards that answer as it's hard coded to latin 1 and I want this to work with all types of localization to be on the safe side.</p> <p>No answers involving boost thanks, I don't want the headache of getting my codebase to work with it.</p>
21,575,607
1
3
null
2014-02-05 10:59:36.693 UTC
5
2014-02-05 11:11:50.89 UTC
2017-05-23 12:00:29.203 UTC
null
-1
null
498,519
null
1
20
c++|windows|visual-studio-2010|utf-8|localization
43,395
<p>If your "normal string" is encoded using the system's code page and you want to convert it to UTF-8 then this should work:</p> <pre><code>std::string codepage_str; int size = MultiByteToWideChar(CP_ACP, MB_COMPOSITE, codepage_str.c_str(), codepage_str.length(), nullptr, 0); std::wstring utf16_str(size, '\0'); MultiByteToWideChar(CP_ACP, MB_COMPOSITE, codepage_str.c_str(), codepage_str.length(), &amp;utf16_str[0], size); int utf8_size = WideCharToMultiByte(CP_UTF8, 0, utf16_str.c_str(), utf16_str.length(), nullptr, 0, nullptr, nullptr); std::string utf8_str(utf8_size, '\0'); WideCharToMultiByte(CP_UTF8, 0, utf16_str.c_str(), utf16_str.length(), &amp;utf8_str[0], utf8_size, nullptr, nullptr); </code></pre>
1,507,780
Searching for a sequence of Bytes in a Binary File with Java
<p>I have a sequence of bytes that I have to search for in a set of Binary files using Java.</p> <p>Example: I'm searching for the byte sequence <code>DEADBEEF</code> (in hex) in a Binary file. How would I go about doing this in Java? Is there a built-in method, like <code>String.contains()</code> for Binary files?</p>
1,507,813
4
0
null
2009-10-02 04:55:51.753 UTC
11
2018-12-09 20:46:40.233 UTC
null
null
null
null
1,572
null
1
37
java|search|byte|binaryfiles
26,450
<p>No, there is no built-in method to do that. But, directly copied from <a href="http://www.velocityreviews.com/forums/t129673-search-byte-for-pattern.html" rel="noreferrer">HERE</a> (with two fixes applied to the original code):</p> <pre><code>/** * Knuth-Morris-Pratt Algorithm for Pattern Matching */ class KMPMatch { /** * Finds the first occurrence of the pattern in the text. */ public static int indexOf(byte[] data, byte[] pattern) { if (data.length == 0) return -1; int[] failure = computeFailure(pattern); int j = 0; for (int i = 0; i &lt; data.length; i++) { while (j &gt; 0 &amp;&amp; pattern[j] != data[i]) { j = failure[j - 1]; } if (pattern[j] == data[i]) { j++; } if (j == pattern.length) { return i - pattern.length + 1; } } return -1; } /** * Computes the failure function using a boot-strapping process, * where the pattern is matched against itself. */ private static int[] computeFailure(byte[] pattern) { int[] failure = new int[pattern.length]; int j = 0; for (int i = 1; i &lt; pattern.length; i++) { while (j &gt; 0 &amp;&amp; pattern[j] != pattern[i]) { j = failure[j - 1]; } if (pattern[j] == pattern[i]) { j++; } failure[i] = j; } return failure; } } </code></pre>
1,937,702
Visual Studio: Run C++ project Post-Build Event even if project is up-to-date
<p>In Visual Studio (2008) is it possible to force the Post-Build Event for a C++ project to run even if the project is up-to-date?</p> <p>Specifically, I have a project which builds a COM in-process server DLL. The project has a post-build step which runs "regsvr32.exe $(TargetPath)". This runs fine on a "Rebuild", but runs on a "Build" only if changes have been made to the project's source.</p> <p>If I do a "Build" without making any changes, Visual Studio simply reports that the project is up-to-date and does nothing - the Post-Build Event is not run. Is there any way that I can force the Event to run in this situation? This is necessary since although the DLL itself is up-to-date, the registration information may not be.</p>
1,938,940
4
0
null
2009-12-21 01:05:48.703 UTC
10
2019-05-03 14:02:59.993 UTC
2019-02-25 13:18:47.927 UTC
null
6,451,573
null
200,783
null
1
51
c++|visual-studio|post-build-event|regsvr32
24,034
<p>You can use the <strong>Custom Build Step</strong> property page to set up a batch file to run. This runs if the File specified in the <strong>Outputs</strong> setting is not found, or is out-of-date. Simply specify some non-existent file there, and the custom build step will always run. It will run even if your project is up-to-date, since the Output file is never found. </p>
1,861,489
Converting a date in MySQL from string field
<p>I'm using a system where the dates are stored as strings in the format <code>dd/mm/yyyy</code>. Is it possible to convert this to <code>yyyy-mm-dd</code> in a SELECT query (so that I can use <code>DATE_FORMAT</code> on it)? Does MySQL have a date parsing function?</p> <p>Currently the only method I can think of is to concatenate a bunch of substrings, but hopefully there's a simpler solution.</p> <p>(Unfortunately I can't convert the field to a true date field since it's a meta-table: the same column contains values for different fields that are just strings.)</p>
1,861,551
4
0
null
2009-12-07 17:26:20.013 UTC
11
2021-04-05 05:44:36.513 UTC
null
null
null
null
37,947
null
1
60
mysql|date
180,351
<p>This:</p> <pre><code>STR_TO_DATE(t.datestring, '%d/%m/%Y') </code></pre> <p>...will convert the string into a datetime datatype. To be sure that it comes out in the format you desire, use <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format" rel="noreferrer">DATE_FORMAT</a>:</p> <pre><code>DATE_FORMAT(STR_TO_DATE(t.datestring, '%d/%m/%Y'), '%Y-%m-%d') </code></pre> <p>If you can't change the datatype on the original column, I suggest <a href="http://dev.mysql.com/doc/refman/5.0/en/create-view.html" rel="noreferrer">creating a view</a> that uses the <code>STR_TO_DATE</code> call to convert the string to a DateTime data type.</p>
49,550,011
Font Awesome Icons in Offline
<p>Is there any way to use this in offline?</p> <pre><code> &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"&gt; </code></pre> <p>I copy the link and save as font-awesome.min.css but still it is not working in offline like this link href="css/font-awesome.min.css" rel="stylesheet" type="text/css" </p> <p><a href="https://i.stack.imgur.com/TdzSE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TdzSE.png" alt="enter image description here"></a></p>
49,550,097
7
4
null
2018-03-29 07:10:17.243 UTC
3
2022-08-23 21:16:08.03 UTC
2018-03-29 09:14:00.637 UTC
null
6,597,375
null
8,341,429
null
1
10
css|html|font-awesome|cdn
49,663
<p>Press the "Download free" button and make sure that you have the webfonts too. There is a <code>web-fonts-with-css</code> folder in the downloaded zip. Copy the fonts in your project and modify the paths for the fonts in your CSS to point to the location of the webfonts. </p> <p>If you open the CSS linked in your questions you'll see that they have some imports with</p> <p><code>url('../fonts/fontawesome-webfont.woff2?v=4.7.0')</code> </p> <p>modify these with the location of the fonts downloaded.</p>
28,676,437
Slack - Show fullname of user instead of username
<p>Is there a way that in slack, we can show fullname of a user in the channel user list, instead of just the username? Since we have multiple teams and not all the people are familiar with usernames that users pick from different teams, its really difficult to identify who is who unless one goes to their profile or checks their fullname manually.</p> <p>So, is there a way to display the full usernames for users in the list instead of just the usernames?</p>
29,567,294
2
3
null
2015-02-23 14:51:13.757 UTC
4
2016-08-15 09:10:13.777 UTC
2015-02-23 15:25:38.097 UTC
null
1,391,685
null
1,391,685
null
1
40
slack-api
42,093
<p><strong>For the application side</strong></p> <p>Yes there is. In the window for slack, at the bottom left by your username, there is an up arrow. Click on that and you will see a preferences option.</p> <p><img src="https://i.stack.imgur.com/lHuKM.png" alt="Slack Preferences"></p> <p>Once you are in Preferences, Click on Message Display. Within this option, you will find "Display real names instead of usernames". Make sure this is checked and click on done.</p> <p><img src="https://i.stack.imgur.com/8PKRD.png" alt="Message Display"></p> <p><strong>For the API Side</strong></p> <p>Since this is tagged Slack-api and I'm not sure if this is what you are talking about, within the response of the API from the users.list method, it will return the First/Last name, so you would just have to use it in whatever you are doing. <a href="https://api.slack.com/methods/users.list" rel="noreferrer">Reference the Docs for the Slack API</a> </p> <pre><code>{ "ok": true, "members": [ { "id": "U023BECGF", "name": "bobby", "deleted": false, "color": "9f69e7", "profile": { "first_name": "Bobby", "last_name": "Tables", "real_name": "Bobby Tables", "email": "[email protected]", "skype": "my-skype-name", "phone": "+1 (123) 456 7890", "image_24": "https:\/\/...", "image_32": "https:\/\/...", "image_48": "https:\/\/...", "image_72": "https:\/\/...", "image_192": "https:\/\/..." }, "is_admin": true, "is_owner": true, "has_2fa": false, "has_files": true }, ... ] </code></pre> <p>}</p>
7,434,371
image.onload function with return
<p>I have a JS function where a value is computed and this value should be returned but I get everytime <code>undefined</code> but if I <code>console.log()</code> the result within this function it works. Could you help?</p> <pre><code>function detect(URL) { var image = new Image(); image.src = URL; image.onload = function() { var result = [{ x: 45, y: 56 }]; // An example result return result; // Doesn't work } } alert(detect('image.png')); </code></pre>
7,434,559
5
3
null
2011-09-15 16:36:22.33 UTC
8
2020-08-06 16:12:44.813 UTC
2020-08-06 16:12:44.813 UTC
null
4,370,109
null
242,751
null
1
22
javascript|image|dom-events
51,325
<p>I get it myself:</p> <p>I didn't know that I can assign a variable to that (for me looking already assigned) onload.</p> <pre><code>function detect(URL) { var image = new Image(); image.src = URL; var x = image.onload = function() { var result = [{ x: 45, y: 56 }]; // An example result return result; }(); return x; } alert(detect('x')); </code></pre>
7,682,322
IBOutlet and viewDidUnload under ARC
<p>There is a similar question to this on SO <a href="https://stackoverflow.com/questions/7678469/should-iboutlets-be-strong-or-weak-under-arc">here</a>, however I just want to clarify something that wasn't fully explained there.</p> <p>I understand that all delegates and outlets - in fact any reference to a "parent" object, to be a good citizen and think about the object graph for a minute - should be zeroing weak references. Due to the nature of zeroing weak pointers automatically dropping to nil on the referenced object's retain count reaching zero, does this mean that setting IBOutlets to nil in <code>viewDidUnload</code> is now unnecessary?</p> <p>So, if I declare my outlet like so:</p> <pre><code>@property (nonatomic, weak) IBOutlet UILabel *myLabel; </code></pre> <p>Does the following code have any effect?</p> <pre><code>- (void)viewDidUnload { self.myLabel = nil; [super viewDidUnload]; } </code></pre>
7,682,785
5
2
null
2011-10-07 01:50:41.703 UTC
16
2013-09-05 07:51:18.84 UTC
2017-05-23 11:55:39.927 UTC
null
-1
null
429,427
null
1
36
ios|weak-references|iboutlet|automatic-ref-counting
7,103
<p>Just doing a bit of research...</p> <p>As I understand it, weak is similar to assign, in that they're both weak references.</p> <p>However, assign does not create a zeroing reference. i.e. if the object in question is destroyed, and you access that property, you WILL get a <code>BAD_ACCESS_EXCEPTION</code>.</p> <p>Weak properties are automatically zeroed (= nil) when the object it is referencing is destroyed.</p> <p>In both cases, it is not necessary to set property to nil, as it does not contribute to the retain count of the object in question. It is necessary when using retain properties.</p> <p>Apparently, ARC also introduces a new "strong" property, which is the same as "retain"?</p> <p>Research done <a href="http://www.mikeash.com/pyblog/friday-qa-2011-09-30-automatic-reference-counting.html" rel="nofollow noreferrer">here</a> </p>
7,539,282
Order of calling constructors/destructors in inheritance
<p>A little question about creating objects. Say I have these two classes:</p> <pre><code>struct A{ A(){cout &lt;&lt; "A() C-tor" &lt;&lt; endl;} ~A(){cout &lt;&lt; "~A() D-tor" &lt;&lt; endl;} }; struct B : public A{ B(){cout &lt;&lt; "B() C-tor" &lt;&lt; endl;} ~B(){cout &lt;&lt; "~B() D-tor" &lt;&lt; endl;} A a; }; </code></pre> <p>and in main I create an instance of <code>B</code>: </p> <pre><code>int main(){ B b; } </code></pre> <p><em>Note that <code>B</code> derives from <code>A</code> and also has a field of type <code>A</code>.</em></p> <p>I am trying to figure out the rules. I know that when constructing an object first calls its parent constructor, and vice versa when destructing.</p> <p>What about fields (<code>A a;</code> in this case)? When <code>B</code> is created, when will it call <code>A</code>'s constructor? I haven't defined an initialization list, is there some kind of a default list? And if there's no default list? And the same question about destructing.</p>
7,539,330
6
4
null
2011-09-24 13:20:34.47 UTC
31
2018-02-16 02:12:03.977 UTC
2013-12-07 16:08:48.857 UTC
null
635,608
null
882,868
null
1
43
c++|constructor|order-of-execution|call-hierarchy
80,210
<ul> <li>Construction always starts with the base <code>class</code>. If there are multiple base <code>class</code>es then, construction starts with the left most base. (<strong>side note</strong>: If there is a <code>virtual</code> inheritance then it's given higher preference).</li> <li>Then the member fields are constructed. They are initialized in the order they are declared</li> <li>Finally, the <code>class</code> itself is constructed</li> <li>The order of the destructor is exactly the reverse</li> </ul> <p>Irrespective of the initializer list, the call order will be like this:</p> <ol> <li>Base <code>class A</code>'s constructor</li> <li><code>class B</code>'s field named <code>a</code> (of type <code>class A</code>) will be constructed</li> <li>Derived <code>class B</code>'s constructor</li> </ol>
7,109,667
Change default location of vimrc
<p>In Vim, is it possible to change the default location of the user vimrc file, i.e., from $HOME/.vimrc to some other location ?</p>
7,109,871
8
0
null
2011-08-18 15:05:23.187 UTC
18
2019-05-28 12:08:29.003 UTC
null
null
null
null
715,769
null
1
52
vim
43,371
<p>You must start vim with the command <code>vim -u ./path/to/your/vimrcfile</code></p> <p><code>vim -u NONE</code> is a good way to start Vim without any plugin or customisation.</p> <p>See <code>:help starting.txt</code> for more information.</p>
14,076,207
Simulating a key press event in Python 2.7
<p>What I want to do is to press any keyboard key from the Python script level on Windows. I have tried SendKeys but it works only on python 2.6. Other methods that I have tried including</p> <pre><code>import win32com.client win32com.client.Dispatch("WScript.Shell").SendKeys('String to be typed') </code></pre> <p>allow only to type strings from the script level but dont allow to press ENTER and other 'special' keys. </p> <p>Therefore my question is: How can I simulate any keyboard key press event from python script level including 'special' ones like ENTER, CTRL, ESC etc. </p> <p>It would be also very helpful if it is possible to hold a key pressed down for any specified time and press a combination of keys like Alt+F4. </p>
22,894,683
1
1
null
2012-12-28 21:45:20.513 UTC
9
2017-02-16 23:56:04.457 UTC
null
null
null
null
1,354,439
null
1
8
python|api|events|keyboard|simulation
25,602
<p>I wrote this code more than 1 year ago so it is not perfect but it works:</p> <pre><code>from win32api import keybd_event import time import random Combs = { 'A': [ 'SHIFT', 'a'], 'B': [ 'SHIFT', 'b'], 'C': [ 'SHIFT', 'c'], 'D': [ 'SHIFT', 'd'], 'E': [ 'SHIFT', 'e'], 'F': [ 'SHIFT', 'f'], 'G': [ 'SHIFT', 'g'], 'H': [ 'SHIFT', 'h'], 'I': [ 'SHIFT', 'i'], 'J': [ 'SHIFT', 'j'], 'K': [ 'SHIFT', 'k'], 'L': [ 'SHIFT', 'l'], 'M': [ 'SHIFT', 'm'], 'N': [ 'SHIFT', 'n'], 'O': [ 'SHIFT', 'o'], 'P': [ 'SHIFT', 'p'], 'R': [ 'SHIFT', 'r'], 'S': [ 'SHIFT', 's'], 'T': [ 'SHIFT', 't'], 'U': [ 'SHIFT', 'u'], 'W': [ 'SHIFT', 'w'], 'X': [ 'SHIFT', 'x'], 'Y': [ 'SHIFT', 'y'], 'Z': [ 'SHIFT', 'z'], 'V': [ 'SHIFT', 'v'], 'Q': [ 'SHIFT', 'q'], '?': [ 'SHIFT', '/'], '&gt;': [ 'SHIFT', '.'], '&lt;': [ 'SHIFT', ','], '"': [ 'SHIFT', "'"], ':': [ 'SHIFT', ';'], '|': [ 'SHIFT', '\\'], '}': [ 'SHIFT', ']'], '{': [ 'SHIFT', '['], '+': [ 'SHIFT', '='], '_': [ 'SHIFT', '-'], '!': [ 'SHIFT', '1'], '@': [ 'SHIFT', '2'], '#': [ 'SHIFT', '3'], '$': [ 'SHIFT', '4'], '%': [ 'SHIFT', '5'], '^': [ 'SHIFT', '6'], '&amp;': [ 'SHIFT', '7'], '*': [ 'SHIFT', '8'], '(': [ 'SHIFT', '9'], ')': [ 'SHIFT', '0'] } Base = { '0': 48, '1': 49, '2': 50, '3': 51, '4': 52, '5': 53, '6': 54, '7': 55, '8': 56, '9': 57, 'a': 65, 'b': 66, 'c': 67, 'd': 68, 'e': 69, 'f': 70, 'g': 71, 'h': 72, 'i': 73, 'j': 74, 'k': 75, 'l': 76, 'm': 77, 'n': 78, 'o': 79, 'p': 80, 'q': 81, 'r': 82, 's': 83, 't': 84, 'u': 85, 'v': 86, 'w': 87, 'x': 88, 'y': 89, 'z': 90, '.': 190, '-': 189, ',': 188, '=': 187, '/': 191, ';': 186, '[': 219, ']': 221, '\\': 220, "'": 222, 'ALT': 18, 'TAB': 9, 'CAPSLOCK': 20, 'ENTER': 13, 'BS': 8, 'CTRL': 17, 'ESC': 27, ' ': 32, 'END': 35, 'DOWN': 40, 'LEFT': 37, 'UP': 38, 'RIGHT': 39, 'SELECT': 41, 'PRINTSCR': 44, 'INS': 45, 'DEL': 46, 'LWIN': 91, 'RWIN': 92, 'LSHIFT': 160, 'SHIFT': 161, 'LCTRL': 162, 'RCTRL': 163, 'VOLUP': 175, 'DOLDOWN': 174, 'NUMLOCK': 144, 'SCROLL': 145 } def KeyUp(Key): keybd_event(Key, 0, 2, 0) def KeyDown(Key): keybd_event(Key, 0, 1, 0) def Press(Key, speed=1): rest_time = 0.05/speed if Key in Base: Key = Base[Key] KeyDown(Key) time.sleep(rest_time) KeyUp(Key) return True if Key in Combs: KeyDown(Base[Combs[Key][0]]) time.sleep(rest_time) KeyDown(Base[Combs[Key][1]]) time.sleep(rest_time) KeyUp(Base[Combs[Key][1]]) time.sleep(rest_time) KeyUp(Base[Combs[Key][0]]) return True return False def Write(Str, speed = 1): for s in Str: Press(s, speed) time.sleep((0.1 + random.random()/10.0) / float(speed)) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; Write('Hello, World!', speed=3) Hello, World! &gt;&gt;&gt; Press('ENTER') </code></pre> <p>If you want to implement some more keys then you can find their codes <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx" rel="nofollow noreferrer">here</a>. And just add these keys to the Base dictionary.</p>
14,102,655
users own pch (clip) in r
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2181902/how-to-use-an-image-as-a-point-in-ggplot">How to use an image as a point in ggplot?</a> </p> </blockquote> <p>Is it possible to have user defined pch (clip art or icon or other type of file) used as point in R base or ggplot or other graphical device.</p> <p>For example:</p> <p><img src="https://i.stack.imgur.com/Of8aN.jpg" alt="enter image description here"></p> <pre><code>set.seed(123) mydt &lt;- data.frame (x = rnorm(5, 5,2), y = rnorm (5,10,3), z = rnorm (5, 1,0.5)) </code></pre> <p><img src="https://i.stack.imgur.com/MNrOE.jpg" alt="enter image description here"></p> <p>Here size is proportional to z. </p>
14,103,504
2
1
null
2012-12-31 14:18:57.273 UTC
9
2012-12-31 18:38:51.68 UTC
2017-05-23 11:58:26.223 UTC
null
-1
null
927,589
null
1
11
r|plot|ggplot2|pch
1,533
<p>Using <code>grid.raster</code></p> <pre><code>library(png) flower &lt;- readPNG("flower.png") pushViewport(plotViewport(margins=c(5,5,5,5))) grid.rect(gp = gpar(fill=NA)) pushViewport(plotViewport(margins=c(5,5,5,5), xscale=extendrange(mydt$x), yscale=extendrange(mydt$y))) grid.raster(image=flower,x=mydt$x,y=mydt$y,width=mydt$z, interpolate=FALSE,default.units = 'native') grid.polyline(mydt$x,mydt$y,default.units='native') upViewport(2) </code></pre> <p><img src="https://i.stack.imgur.com/thBjU.png" alt="enter image description here"></p>
14,120,502
How to download and write a file from Github using Requests
<p>Lets say there's a file that lives at the github repo:</p> <p><a href="https://github.com/someguy/brilliant/blob/master/somefile.txt" rel="noreferrer">https://github.com/someguy/brilliant/blob/master/somefile.txt</a></p> <p>I'm trying to use requests to request this file, write the content of it to disk in the current working directory where it can be used later. Right now, I'm using the following code:</p> <pre><code>import requests from os import getcwd url = "https://github.com/someguy/brilliant/blob/master/somefile.txt" directory = getcwd() filename = directory + 'somefile.txt' r = requests.get(url) f = open(filename,'w') f.write(r.content) </code></pre> <p>Undoubtedly ugly, and more importantly, not working. Instead of the expected text, I get:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;!-- Hello future GitHubber! I bet you're here to remove those nasty inline styles, DRY up these templates and make 'em nice and re-usable, right? Please, don't. https://github.com/styleguide/templates/2.0 --&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-type" content="text/html; charset=utf-8"&gt; &lt;title&gt;Page not found &amp;middot; GitHub&lt;/title&gt; &lt;style type="text/css" media="screen"&gt; body { background: #f1f1f1; font-family: "HelveticaNeue", Helvetica, Arial, sans-serif; text-rendering: optimizeLegibility; margin: 0; } .container { margin: 50px auto 40px auto; width: 600px; text-align: center; } a { color: #4183c4; text-decoration: none; } a:visited { color: #4183c4 } a:hover { text-decoration: none; } h1 { letter-spacing: -1px; line-height: 60px; font-size: 60px; font-weight: 100; margin: 0px; text-shadow: 0 1px 0 #fff; } p { color: rgba(0, 0, 0, 0.5); margin: 20px 0 40px; } ul { list-style: none; margin: 25px 0; padding: 0; } li { display: table-cell; font-weight: bold; width: 1%; } #error-suggestions { font-size: 14px; } #next-steps { margin: 25px 0 50px 0;} #next-steps li { display: block; width: 100%; text-align: center; padding: 5px 0; font-weight: normal; color: rgba(0, 0, 0, 0.5); } #next-steps a { font-weight: bold; } .divider { border-top: 1px solid #d5d5d5; border-bottom: 1px solid #fafafa;} #parallax_wrapper { position: relative; z-index: 0; } #parallax_field { overflow: hidden; position: absolute; left: 0; top: 0; height: 370px; width: 100%; } </code></pre> <p>etc etc.<br> <br> Content from Github, but not the content of the file. What am I doing wrong?</p>
14,120,601
4
1
null
2013-01-02 10:34:19.33 UTC
11
2022-01-08 13:14:40.51 UTC
null
null
null
null
868,908
null
1
34
python|github|python-requests
57,957
<p>The content of the file in question is <em>included</em> in the returned data. You are getting the full GitHub view of that file, not just the contents.</p> <p>If you want to download <em>just</em> the file, you need to use the <code>Raw</code> link at the top of the page, which will be (for your example):</p> <pre><code>https://raw.github.com/someguy/brilliant/master/somefile.txt </code></pre> <p>Note the change in domain name, and the <code>blob/</code> part of the path is gone.</p> <p>To demonstrate this with the <code>requests</code> GitHub repository itself:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.get('https://github.com/kennethreitz/requests/blob/master/README.rst') &gt;&gt;&gt; 'Requests:' in r.text True &gt;&gt;&gt; r.headers['Content-Type'] 'text/html; charset=utf-8' &gt;&gt;&gt; r = requests.get('https://raw.github.com/kennethreitz/requests/master/README.rst') &gt;&gt;&gt; 'Requests:' in r.text True &gt;&gt;&gt; r.headers['Content-Type'] 'text/plain; charset=utf-8' &gt;&gt;&gt; print r.text Requests: HTTP for Humans ========================= .. image:: https://travis-ci.org/kennethreitz/requests.png?branch=master [... etc. ...] </code></pre>
13,858,062
Reset autoincrement in Microsoft SQL Server 2008 R2
<p>I created a primary key to be autoincrement.</p> <ul> <li>I added two rows: <code>ID=1, ID=2</code></li> <li>I deleted these two rows.</li> <li>I added a new row, but the new row's ID was: <code>ID=3</code></li> </ul> <p>How can I reset or restart the autoincrement to 1?</p>
13,858,108
2
0
null
2012-12-13 10:40:42.533 UTC
8
2014-11-25 07:40:27.58 UTC
2012-12-13 14:35:46.337 UTC
null
576,752
null
644,686
null
1
35
sql-server-2008-r2|auto-increment|identity-column
78,591
<p>If you use the <a href="http://msdn.microsoft.com/en-us/library/ms176057.aspx"><code>DBCC CHECKIDENT</code></a> command:</p> <pre><code> DBCC CHECKIDENT ("YourTableNameHere", RESEED, 1); </code></pre> <p>But <strong>use with CAUTION!</strong> - this will just reset the <code>IDENTITY</code> to 1 - so your next inserts will get values 1, then 2, and then 3 --> and you'll have a clash with your pre-existing value of 3 here!</p> <p><code>IDENTITY</code> just dishes out numbers in consecutive order - it does <strong>NOT</strong> in any way make sure there are no conflicts! If you already have values - do <strong>not</strong> reseed back to a lower value!</p>
13,870,206
Apache not starting in MAMP (but MySQL working) in OSX
<p>I've had MAMP working for a few months and recently installed PostgreSQL. It recommended installing Apache as well, which I did to make sure PostgreSQL worked. I then uninstalled PostgreSQL and the apache build and tried to restart MAMP. It fired up the MySQL database (green light) but Apache didn't start. I uninstalled and reinstalled MAMP only to face the same problem.</p> <p>Apache doesn't seem to be logging any errors in the MAMP folder, so without any errors to report I'm struggling with where to begin fixing it. I'm hoping its to do with the fact that I installed another version (and deleted it) that has caused the problem but I'm too inexperienced to know what I've done.</p> <p>Where might I find any errors if not in the MAMP folder? Not in:</p> <ul> <li>/Applications/MAMP/Library/logs</li> <li>/Applications/MAMP/bin/logs</li> </ul>
24,287,496
16
0
null
2012-12-13 23:13:55.677 UTC
17
2018-05-08 10:55:32.347 UTC
null
null
null
null
630,203
null
1
62
macos|apache|mamp
94,647
<p>Stoping the Apache solved this issue for me, using the command-line: </p> <pre><code>sudo apachectl stop </code></pre>
14,057,932
javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context
<p>I'm trying to pass a object via REST web service. Following are my classes explains the functionality that I need using some example codes. </p> <p><strong>Rest Web Service Class method</strong></p> <pre><code>@POST @Path("/find") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_JSON}) public Response getDepartments(){ Response response = new Response(); try { response.setCode(MessageCode.SUCCESS); response.setMessage("Department Names"); Department dept = new Department("12", "Financial"); response.setPayload(dept); } catch (Exception e) { response.setCode(MessageCode.ERROR); response.setMessage(e.getMessage()); e.printStackTrace(); } return response; } </code></pre> <p><strong>Response Class</strong></p> <pre><code>import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Response implements Serializable{ private static final long serialVersionUID = 1L; public enum MessageCode { SUCCESS, ERROR, UNKNOWN } private MessageCode code; private String message; private Object payload; public MessageCode getCode() { return code; } public void setCode(MessageCode code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getPayload() { return payload; } public void setPayload(Object payload) { this.payload = payload; } } </code></pre> <p><strong>Department Class</strong></p> <pre><code>@XmlRootElement public class Department implements java.io.Serializable { private String deptNo; private String deptName; public Department() { } public Department(String deptNo, String deptName) { this.deptNo = deptNo; this.deptName = deptName; } public String getDeptNo() { return this.deptNo; } public void setDeptNo(String deptNo) { this.deptNo = deptNo; } public String getDeptName() { return this.deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } } </code></pre> <p>When I make a call to getDepartments method in the rest web service class it returns following exceptions. But If I change the type <strong>Object</strong> of the <strong>payload</strong> to <strong>Department</strong> in the Response class it returns the json response correctly. But since I need to use this Response class for different types of Classes I can't restring the payload to one class type. Can anyone please help me in this matter?</p> <p><strong>Stack Trace</strong> </p> <pre><code>Dec 27, 2012 9:34:18 PM com.sun.jersey.spi.container.ContainerResponse logException SEVERE: Mapped exception to response: 500 (Internal Server Error) javax.ws.rs.WebApplicationException: javax.xml.bind.MarshalException - with linked exception: [javax.xml.bind.JAXBException: class Department nor any of its super class is known to this context.] at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:159) at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306) at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437) at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349) at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339) at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416) at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:401) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:945) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) Caused by: javax.xml.bind.MarshalException - with linked exception: [javax.xml.bind.JAXBException: class Department nor any of its super class is known to this context.] at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:323) at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:177) at com.sun.jersey.json.impl.BaseJSONMarshaller.marshallToJSON(BaseJSONMarshaller.java:103) at com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider.writeTo(JSONRootElementProvider.java:136) at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:157) ... 23 more Caused by: javax.xml.bind.JAXBException: class Department nor any of its super class is known to this context. at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:250) at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:265) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:657) at com.sun.xml.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:156) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:344) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsSoleContent(XMLSerializer.java:597) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:328) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:498) at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:320) ... 27 more Caused by: javax.xml.bind.JAXBException: class Department nor any of its super class is known to this context. at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:611) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:652) ... 33 more </code></pre>
14,073,899
11
2
null
2012-12-27 16:33:44.617 UTC
8
2022-03-14 11:39:49.363 UTC
2013-08-26 15:45:16.287 UTC
null
814,702
null
793,635
null
1
64
java|rest|jaxb|jax-rs
191,983
<p>JAX-RS implementations automatically support marshalling/unmarshalling of classes based on discoverable JAXB annotations, but because your payload is declared as <code>Object</code>, I think the created <code>JAXBContext</code> misses the <code>Department</code> class and when it's time to marshall it it doesn't know how.</p> <p>A quick and dirty fix would be to add a <a href="http://docs.oracle.com/javaee/6/api/javax/xml/bind/annotation/XmlSeeAlso.html" rel="noreferrer"><code>XmlSeeAlso</code></a> annotation to your response class:</p> <pre><code>@XmlRootElement @XmlSeeAlso({Department.class}) public class Response implements Serializable { .... </code></pre> <p>or something a little more complicated would be "to enrich" the JAXB context for the <code>Response</code> class by using a <code>ContextResolver</code>:</p> <pre><code>import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; @Provider @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public class ResponseResolver implements ContextResolver&lt;JAXBContext&gt; { private JAXBContext ctx; public ResponseResolver() { try { this.ctx = JAXBContext.newInstance( Response.class, Department.class ); } catch (JAXBException ex) { throw new RuntimeException(ex); } } public JAXBContext getContext(Class&lt;?&gt; type) { return (type.equals(Response.class) ? ctx : null); } } </code></pre>
13,944,222
Change SVN repository URL
<p>My current SVN structure:</p> <pre><code>Path: . URL: svn://someaddress.com.tr/project Repository Root: svn://someaddress.com.tr Repository UUID: ------------------------------------- Revision: 10297 Node Kind: directory Schedule: normal Last Changed Author: ---- Last Changed Rev: 9812 Last Changed Date: 2010-12-20 17:38:48 +0100 (Mon, 20 Dec 2010) </code></pre> <p>But our project (hence the SVN service) will work over <code>sub.someaddress.com.tr</code> instead of <code>someaddress.com.tr</code> (someaddress.com.tr will be redirected to somewhere else soon).</p> <p>Since it is the development server, I could not be sure about what to do. Will I need to use <code>svn switch</code> or <code>svn switch --relocate</code>? Also, will I need to switch svn root <strong>someaddress.com.tr</strong> or the project branch <strong>someaddress.com.tr/project</strong>?</p>
13,944,343
7
1
null
2012-12-19 01:22:32.783 UTC
20
2022-07-05 08:05:39.74 UTC
2016-12-05 16:06:00.927 UTC
null
63,550
null
257,972
null
1
134
svn|svn-repository
191,897
<p>Given that the Apache Subversion server will be moved to this new DNS alias: <code>sub.someaddress.com.tr</code>:</p> <ul> <li><p>With Subversion 1.7 or higher, use <a href="http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.relocate.html" rel="noreferrer"><code>svn relocate</code></a>. Relocate is used when the SVN server's location changes. <code>switch</code> is only used if you want to change your local working copy to another branch or another path. If using TortoiseSVN, you may follow instructions from the <a href="http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-dug-relocate.html" rel="noreferrer">TortoiseSVN Manual</a>. If using the SVN command line interface, refer to <a href="http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.relocate.html" rel="noreferrer">this section of SVN's documentation</a>. The command should look like this:</p> <p><code>svn relocate svn://sub.someaddress.com.tr/project</code></p> </li> <li><p>Keep using <code>/project</code> given that the actual contents of your repository probably won't change.</p> </li> </ul> <p>Note: <code>svn relocate</code> is not available before version 1.7 (thanks to ColinM for the info). In older versions you would use:</p> <pre><code> svn switch --relocate OLD NEW </code></pre>
28,870,932
How to remove white border from blur background image
<p>How to remove the white blur border from the background image.</p> <pre><code>&lt;div class="background-image"&gt;&lt;/div&gt; </code></pre> <p>CSS, i tried adding margin:-10px but it doesn't work</p> <pre><code>.background-image { background: no-repeat center center fixed; background-image: url('http://www.hdpaperz.com/wallpaper/original/windows-8-wallpapers-2560x1600-2311_1.jpg') ; background-size: cover; display: block; height: 100%; left: -5px; top:-5px; bottom:-5px; position: fixed; right: -5px; z-index: 1; margin:0px auto; -webkit-filter: blur(5px); -moz-filter: blur(5px); -o-filter: blur(5px); -ms-filter: blur(5px); filter: blur(5px); -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; } </code></pre> <p><a href="http://jsfiddle.net/maio/8wq132nd/1/" rel="noreferrer">http://jsfiddle.net/maio/8wq132nd/1/</a></p>
28,884,241
10
2
null
2015-03-05 05:50:01.337 UTC
10
2022-08-08 07:56:27.147 UTC
2015-03-05 06:35:32.903 UTC
null
2,754,197
null
2,754,197
null
1
25
html|css|blur
55,990
<p>I have added overflow, padding and even margin, but still the problem not solved. So i tried to give the image tag between div. Problem solved.</p> <pre><code>&lt;div class="background-image"&gt; &lt;img src="http://www.hdpaperz.com/wallpaper/original/windows-8-wallpapers-2560x1600-2311_1.jpg" width="100%" height="100%"/&gt; &lt;/div&gt; </code></pre> <p>css</p> <pre><code> .background-image { background: no-repeat center center fixed; background-size: cover; display: block; left: -5px; top:-5px; bottom:-5px; position: fixed; right: -5px; z-index: 1; -webkit-filter: blur(5px); -moz-filter: blur(5px); -o-filter: blur(5px); -ms-filter: blur(5px); filter: blur(5px); -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; margin:-5px; } </code></pre> <p>js fiddle</p> <p><a href="http://jsfiddle.net/2pgdttLh/" rel="noreferrer">http://jsfiddle.net/2pgdttLh/</a></p>
9,227,407
How to insert data into a PL/SQL table type rather than PL/SQL table?
<p>I have a table TDATAMAP which has around 10 million records, I want to fetch all the records into a PL/SQL table type variable, match it with some criteria and finally insert all the required records in a staging table. Please tell me if its possible to do it using PL/SQL table typle variable and BULK INSERT/COLLECT . I am also concerned about the performance of the code.</p>
9,227,515
2
1
null
2012-02-10 11:59:55.007 UTC
null
2012-02-10 19:28:38.153 UTC
null
null
null
null
273,006
null
1
3
oracle|plsql
38,521
<p>You can, but you probably should not, load 10 million records into memory at once - as long as there is sufficient memory to hold that much. Normally BULK COLLECT is used with the LIMIT clause to process a finite number of rows at a time e.g. 1000.</p> <p>From the <a href="http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems020.htm" rel="noreferrer">documentation</a>:</p> <blockquote> <p>The BULK COLLECT clause lets you fetch entire columns from the result set, or the entire result set at once. The following example, retrieves columns from a cursor into a collection:</p> </blockquote> <pre><code>DECLARE TYPE NameList IS TABLE OF emp.ename%TYPE; names NameList; CURSOR c1 IS SELECT ename FROM emp WHERE job = 'CLERK'; BEGIN OPEN c1; FETCH c1 BULK COLLECT INTO names; ... CLOSE c1; END; </code></pre> <blockquote> <p>The following example uses the LIMIT clause. With each iteration of the loop, the FETCH statement fetches 100 rows (or less) into index-by table acct_ids. The previous values are overwritten.</p> </blockquote> <pre><code>DECLARE TYPE NumList IS TABLE OF NUMBER INDEX BY BINARY_INTEGER; CURSOR c1 IS SELECT acct_id FROM accounts; acct_ids NumList; rows NATURAL := 100; -- set limit BEGIN OPEN c1; LOOP /* The following statement fetches 100 rows (or less). */ FETCH c1 BULK COLLECT INTO acct_ids LIMIT rows; EXIT WHEN c1%NOTFOUND; ... END LOOP; CLOSE c1; END; </code></pre>
32,905,917
How to return JSON data from spring Controller using @ResponseBody
<p><strong>Spring version 4.2.0, Hibernate 4.1.4</strong> Here is my <code>Controller</code> function:</p> <pre><code>@RequestMapping(value = "/mobile/getcomp", method = RequestMethod.GET) @ResponseBody public List&lt;Company&gt; listforCompanies() { List&lt;Company&gt; listOfCompanies= new ArrayList&lt;Company&gt;(); listOfCompanies = companyManager.getAllCompanies(); return listOfCompanies; } </code></pre> <p>Jackson JSON mapper dependency in <code>Pom.xml</code>:</p> <pre class="lang-xml prettyprint-override"><code> &lt;!-- Jackson JSON Mapper --&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt; &lt;version&gt;${jackson.version}&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Getting the list in my <code>ArrayList</code>, but when returning the following error is shown:</p> <pre class="lang-none prettyprint-override"><code>SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [/IrApp] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList] with root cause java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList at org.springframework.util.Assert.isTrue(Assert.java:68) at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:124) </code></pre> <p><a href="http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/">Link</a> to the example I'm following.</p>
32,906,060
8
4
null
2015-10-02 11:11:35.757 UTC
15
2020-04-30 18:08:00.697 UTC
2016-11-15 01:02:18.88 UTC
null
442,945
null
1,766,277
null
1
60
java|json|spring|spring-mvc|spring-4
121,266
<p>Add the below dependency to your pom.xml:</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;version&gt;2.5.0&lt;/version&gt; &lt;/dependency&gt; </code></pre>
45,853,956
putty - server unexpectedly closed network connection on windows
<p>I'm getting this error when using Putty:</p> <blockquote> <p>server unexpectedly closed network connection</p> </blockquote> <p>I try to connect my EC2 ubuntu 14.04 LTS Instance using putty, and also i generate pem key to ppk key then i upload ppk key in putty and try to connect my Instance.</p>
45,854,334
1
5
null
2017-08-24 05:56:55.937 UTC
null
2020-12-17 12:45:46.44 UTC
null
null
null
null
6,021,205
null
1
2
putty
48,878
<p>To create and save a new keep-alive connection, follow these steps:</p> <ul> <li>Open the PuTTY application, and go to the Options panel (labeled "Category") on the left of the window.</li> <li>Select (click) the "Connection" item.</li> <li>In the ​​"Sending of null packets to keep the session active" area on the right, change the default value of "Seconds between keepalives" from 0 (turn off) to 1800 (30 minutes).</li> <li>Select the "Enable TCP keepalives (SO_KEEPALIVE option)" check box. Note: This option may not be available in older versions of the PuTTY client.</li> <li>On the topmost left side of the Options panel, select (click) "Session".</li> <li>In the "Host Name (or IP Address)" field, enter the destination host name or IP address (e.g., "destination.ipaddress.here.com" or "192.168.1.1").</li> <li>In the "Saved Sessions" text-entry box, provide a name for the session (e.g., "savedsession").</li> <li>Select "Save".</li> </ul> <p>To use the modified session settings, select it from the "Saved sessions" list, then click the buttons marked "Load" and "Open".</p> <p>If your connected sessions still time out, enter a lower number of seconds into the "Seconds between keepalives" value.</p> <p>On searching more I also got a point that:</p> <p>"Uncheck 'Attempt GSSAPI authentication (SSH-2 only)' in Putty: Category - Connection - SSH - Auth - GSSAPI</p> <p>In my case it seems to be GSSAPI is incompatible to a Ubuntu host that uses Beyond trust (formerly: likewise open)."</p>
3,310,736
input[type="submit"] - change background when clicked
<p>I have a simple <code>&lt;input type="submit" value="Search"&gt;</code> submit button. In the CSS i have styled it with <code>input[type="submit"]</code> and <code>input[type="submit"]:hover</code> so it changes its background by default and when hovered. Is there a way to change its background when clicked?</p>
3,310,780
2
1
null
2010-07-22 15:48:02.91 UTC
null
2012-09-29 22:55:47.81 UTC
null
null
null
null
399,299
null
1
4
html|css|input|submit
43,051
<p>You should be able to use <code>input[type=submit]:active</code>, similar to how you'd style links.</p> <p>Do note that this will not function properly in IE6 (not sure about 7 and 8)</p>
444,966
How to handle IPv6 Addresses in PHP?
<p>After searching around somewhat thoroughly, I noticed a slight lack of functions in PHP for handling <a href="http://en.wikipedia.org/wiki/IPv6" rel="nofollow noreferrer">IPv6</a>. For my own personal satisfaction I created a few functions to help the transition.</p> <p>The <code>IPv6ToLong()</code> function is a temporary solution to that brought up here: <a href="https://stackoverflow.com/questions/420680/">How to store IPv6-compatible address in a relational database</a>. It will split the IP in to two integers and return them in an array.</p> <pre><code>/** * Convert an IPv4 address to IPv6 * * @param string IP Address in dot notation (192.168.1.100) * @return string IPv6 formatted address or false if invalid input */ function IPv4To6($Ip) { static $Mask = '::ffff:'; // This tells IPv6 it has an IPv4 address $IPv6 = (strpos($Ip, '::') === 0); $IPv4 = (strpos($Ip, '.') &gt; 0); if (!$IPv4 &amp;&amp; !$IPv6) return false; if ($IPv6 &amp;&amp; $IPv4) $Ip = substr($Ip, strrpos($Ip, ':')+1); // Strip IPv4 Compatibility notation elseif (!$IPv4) return $Ip; // Seems to be IPv6 already? $Ip = array_pad(explode('.', $Ip), 4, 0); if (count($Ip) &gt; 4) return false; for ($i = 0; $i &lt; 4; $i++) if ($Ip[$i] &gt; 255) return false; $Part7 = base_convert(($Ip[0] * 256) + $Ip[1], 10, 16); $Part8 = base_convert(($Ip[2] * 256) + $Ip[3], 10, 16); return $Mask.$Part7.':'.$Part8; } /** * Replace '::' with appropriate number of ':0' */ function ExpandIPv6Notation($Ip) { if (strpos($Ip, '::') !== false) $Ip = str_replace('::', str_repeat(':0', 8 - substr_count($Ip, ':')).':', $Ip); if (strpos($Ip, ':') === 0) $Ip = '0'.$Ip; return $Ip; } /** * Convert IPv6 address to an integer * * Optionally split in to two parts. * * @see https://stackoverflow.com/questions/420680/ */ function IPv6ToLong($Ip, $DatabaseParts= 2) { $Ip = ExpandIPv6Notation($Ip); $Parts = explode(':', $Ip); $Ip = array('', ''); for ($i = 0; $i &lt; 4; $i++) $Ip[0] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT); for ($i = 4; $i &lt; 8; $i++) $Ip[1] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT); if ($DatabaseParts == 2) return array(base_convert($Ip[0], 2, 10), base_convert($Ip[1], 2, 10)); else return base_convert($Ip[0], 2, 10) + base_convert($Ip[1], 2, 10); } </code></pre> <p>For these functions I typically implement them by calling this function first:</p> <pre><code>/** * Attempt to find the client's IP Address * * @param bool Should the IP be converted using ip2long? * @return string|long The IP Address */ function GetRealRemoteIp($ForDatabase= false, $DatabaseParts= 2) { $Ip = '0.0.0.0'; // [snip: deleted some dangerous code not relevant to question. @webb] if (isset($_SERVER['REMOTE_ADDR']) &amp;&amp; $_SERVER['REMOTE_ADDR'] != '') $Ip = $_SERVER['REMOTE_ADDR']; if (($CommaPos = strpos($Ip, ',')) &gt; 0) $Ip = substr($Ip, 0, ($CommaPos - 1)); $Ip = IPv4To6($Ip); return ($ForDatabase ? IPv6ToLong($Ip, $DatabaseParts) : $Ip); } </code></pre> <p>Someone please tell me if I'm reinventing the wheel here or I've done something wrong.</p> <p>This implementation converts IPv4 to IPv6. Any IPv6 address it doesn't touch.</p>
455,689
5
2
null
2009-01-14 22:35:45.217 UTC
20
2021-11-08 23:52:04.683 UTC
2021-11-08 23:52:04.683 UTC
Milen A. Radev
1,563,960
sirlancelot
51,021
null
1
32
php|ip|ipv6
51,513
<p>How about <a href="http://php.net/inet_ntop" rel="noreferrer"><code>inet_ntop()</code></a>? Then instead of chopping things into integers, you just use a <code>varbinary(16)</code> to store it.</p>
186,800
Is it possible to specify proxy credentials in your web.config?
<p>I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration:</p> <pre><code>&lt;defaultProxy useDefaultCredentials="false"&gt; &lt;proxy usesystemdefault="true" proxyaddress="&lt;proxy address&gt;" bypassonlocal="true" /&gt; &lt;/defaultProxy&gt; </code></pre> <p>I know you can do this via code, but the software the website is running is a closed-source CMS so I can't do this.</p> <p>Is there any way to do this? MSDN isn't helping me much..</p>
194,414
5
0
null
2008-10-09 11:19:18.187 UTC
38
2022-06-10 06:25:40.437 UTC
2008-10-09 11:31:28.617 UTC
null
5,793
null
5,793
null
1
63
c#|web-services|proxy
108,732
<p>Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.</p> <p>Create an assembly called <em>SomeAssembly.dll</em> with this class :</p> <pre><code>namespace SomeNameSpace { public class MyProxy : IWebProxy { public ICredentials Credentials { get { return new NetworkCredential("user", "password"); } //or get { return new NetworkCredential("user", "password","domain"); } set { } } public Uri GetProxy(Uri destination) { return new Uri("http://my.proxy:8080"); } public bool IsBypassed(Uri host) { return false; } } } </code></pre> <p>Add this to your config file :</p> <pre><code>&lt;defaultProxy enabled="true" useDefaultCredentials="false"&gt; &lt;module type = "SomeNameSpace.MyProxy, SomeAssembly" /&gt; &lt;/defaultProxy&gt; </code></pre> <p>This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.</p> <p>This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx" rel="noreferrer">ConfigurationSection</a>, or add some information in the <a href="http://msdn.microsoft.com/en-us/library/ms228154.aspx" rel="noreferrer">AppSettings</a>, which is far more easier.</p>
147,969
Is it idiomatic Ruby to add an assert( ) method to Ruby's Kernel class?
<p>I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it?</p> <p>BTW, <em>I know of the existence of the various Unit frameworks in Ruby</em> - this is an exercise to learn the Ruby idioms, rather than to "get something done".</p>
1,261,375
5
1
null
2008-09-29 08:39:16.18 UTC
10
2022-09-04 19:48:56.027 UTC
2012-06-11 14:01:52.88 UTC
Andrew Harmel-Law
785,541
Andrew Harmel-Law
2,455
null
1
86
ruby|assert|xunit
41,737
<p>No it's not a best practice. The best analogy to assert() in Ruby is just raising</p> <pre><code> raise "This is wrong" unless expr </code></pre> <p>and you can implement your own exceptions if you want to provide for more specific exception handling</p>
991,904
Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad?
<p>I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.</p>
991,917
5
0
null
2009-06-14 01:12:55.97 UTC
51
2017-06-28 17:02:01.367 UTC
null
null
null
null
62,029
null
1
187
java|python|multithreading|jvm|gil
19,467
<p>Python (the language) doesn't need a GIL (which is why it can perfectly be implemented on JVM [Jython] and .NET [IronPython], and those implementations multithread freely). CPython (the popular implementation) has always used a GIL for ease of coding (esp. the coding of the garbage collection mechanisms) and of integration of non-thread-safe C-coded libraries (there used to be a ton of those around;-).</p> <p>The <a href="http://code.google.com/p/unladen-swallow/" rel="noreferrer">Unladen Swallow</a> project, among other ambitious goals, does <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan" rel="noreferrer">plan</a> a GIL-free virtual machine for Python -- to quote that site, "In addition, we intend to remove the GIL and fix the state of multithreading in Python. We believe this is possible through the implementation of a more sophisticated GC system, something like IBM's Recycler (Bacon et al, 2001)."</p>
559,611
Password storage in source control
<p>We store all our application and db passwords in plain text in source control. We do this as our build/deploy process generates required configuration files and also does actual deploys that require these passwords (ie: running sql against a database requires you logon to the db using valid credentials). Has anyone had a similar need where you were able to implement this type of functionality while not storing the passwords in plain text?</p>
559,743
6
1
null
2009-02-18 02:21:52.553 UTC
11
2009-02-18 03:37:39.737 UTC
null
null
null
Marcus Leon
47,281
null
1
19
password-protection|password-storage
8,831
<p>If your plan is to store all the code and configuration information to run a production system directly from version control, and without human intervention, you're screwed. Why? This is all just a violation of the old security axiom "never write your password down". Let's do a proof by negation.</p> <p>First cut, you have plain text passwords in the configuration files. That's no good, they can be read by anyone who can see the files.</p> <p>Second cut, we'll encrypt the passwords! But now the code needs to know how to decrypt the passwords, so you need to put the decryption key somewhere in the code. The problem has just been pushed down a level.</p> <p>How about using public/private keys? Same problem as the passwords, the key has to be in the code.</p> <p>The use of a local configuration file not stored in version control still puts the password, and the means to read them if they're encrypted, on disk and available to an attacker. You can harden things a little by ensuring that configuration file's permissions are very limited, but should the box be rooted you're screwed.</p> <p>Which brings us to why putting passwords on disk is a bad idea. It violates the concept of a security firewall. One compromised machine containing login information means other machines will be compromised. One poorly maintained machine can tear down your whole organization.</p> <p>At some point a human is going to have to inject the critical secret to start the chain of trust going. What you could do is encrypt all the secrets in the code and then when the system starts up have a human manually enter the key to decrypt all the passwords. This is like the master password system Firefox uses. It is open to abuse since once that one password is compromised, many systems may be compromised, but it is convenient and probably more secure since users only have to remember one password and are less likely to write it down.</p> <p>The final touch is to ensure that should the login information be compromised (and you should always assume that it will be) that A) the attacker can't do much with it and B) you can quickly shut down the compromised accounts. The former means to only give the accounts as much access as they need. For example, if your program only ever needs to read from a database have it log in on an account restricted to SELECT. In general, remove all access and then add it only as necessary. Be stingy about the rights to delete lest you get a visit from <a href="http://xkcd.com/327/" rel="noreferrer">little Bobby Tables</a>.</p> <p>The latter means you give each user/organization/project their own login, even if they can have the exact same rights and privileges and access the same data. It's a bit more of a hassle, but it means that if one system is compromised you can quickly shut down that account without shutting down your whole business.</p>
196,876
Is there a better way to get a named series of constants (enumeration) in Python?
<p>Just looking at ways of getting named constants in python.</p> <pre><code>class constant_list: (A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3) </code></pre> <p>Then of course you can refer to it like so: </p> <pre><code>constant_list.A_CONSTANT </code></pre> <p>I suppose you could use a dictionary, using strings: </p> <pre><code>constant_dic = { "A_CONSTANT" : 1, "B_CONSTANT" : 2, "C_CONSTANT" : 3,} </code></pre> <p>and refer to it like this:</p> <pre><code>constant_dic["A_CONSTANT"] </code></pre> <hr> <p>My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?</p> <p>Thanks in advance.</p>
196,881
6
1
null
2008-10-13 06:43:47.23 UTC
10
2009-11-20 01:47:25.83 UTC
null
null
null
Bernard
61
null
1
21
python
4,729
<p>For 2.3 or after:</p> <pre><code>class Enumerate(object): def __init__(self, names): for number, name in enumerate(names.split()): setattr(self, name, number) </code></pre> <p>To use:</p> <pre><code> codes = Enumerate('FOO BAR BAZ') </code></pre> <p><code>codes.BAZ</code> will be 2 and so on. </p> <p>If you only have 2.2, precede this with:</p> <pre><code> from __future__ import generators def enumerate(iterable): number = 0 for name in iterable: yield number, name number += 1 </code></pre> <p>(<em>This was taken from <a href="http://www.velocityreviews.com/forums/t322211-enum-in-python.html" rel="noreferrer">here</a></em>)</p>
142,948
How can I use functional programming in the real world?
<p>Functional languages are good because they avoid bugs by eliminating state, but also because they can be easily parallelized automatically for you, without you having to worry about the thread count. </p> <p>As a Win32 developer though, can I use Haskell for some dlls of my application? And if I do, is there a real advantage that would be taken automatically for me? If so what gives me this advantage, the compiler? </p> <p>Does F# parallelize functions you write across multiple cores and cpu's automatically for you? Would you ever see the thread count in task manager increase?</p> <p>Basically my question is, how can I start using Haskell in a practical way, and will I really see some benefits if I do?</p>
143,009
6
3
null
2008-09-27 04:02:25.163 UTC
51
2012-05-02 19:38:43.017 UTC
2012-05-02 19:38:43.017 UTC
JasonBunting
53,777
Brian R. Bondy
3,153
null
1
103
haskell|f#|functional-programming
19,511
<p>It seems like the book Real World Haskell is just what you're looking for. You can read it free online:</p> <p><a href="http://book.realworldhaskell.org/" rel="noreferrer">http://book.realworldhaskell.org/</a></p>
42,489,918
Async/Await inside Array#map()
<p>I'm getting compile time error with this code: </p> <pre><code>const someFunction = async (myArray) =&gt; { return myArray.map(myValue =&gt; { return { id: "my_id", myValue: await service.getByValue(myValue); } }); }; </code></pre> <p>Error message is: </p> <blockquote> <p>await is a reserved word</p> </blockquote> <p>Why can't I use it like this? </p> <p>I also tried another way, but it gives me same error:</p> <pre><code> const someFunction = async (myArray) =&gt; { return myArray.map(myValue =&gt; { const myNewValue = await service.getByValue(myValue); return { id: "my_id", myValue: myNewValue } }); }; </code></pre>
42,497,383
6
4
null
2017-02-27 15:46:42.467 UTC
17
2021-12-25 21:16:40.583 UTC
2017-03-01 14:33:14.077 UTC
null
218,196
null
921,193
null
1
78
javascript|async-await|ecmascript-2017
68,845
<p>You can't do this as you imagine, because you can't use <code>await</code> if it is not directly inside an <code>async</code> function.</p> <p>The sensible thing to do here would be to make the function passed to <code>map</code> asynchronous. This means that <code>map</code> would return an array of promises. We can then use <code>Promise.all</code> to get the result when all the promises return. As <code>Promise.all</code> itself returns a promise, the outer function does not need to be <code>async</code>.</p> <pre><code>const someFunction = (myArray) =&gt; { const promises = myArray.map(async (myValue) =&gt; { return { id: "my_id", myValue: await service.getByValue(myValue) } }); return Promise.all(promises); } </code></pre>
30,821,188
Python NLTK pos_tag not returning the correct part-of-speech tag
<p>Having this:</p> <pre><code>text = word_tokenize("The quick brown fox jumps over the lazy dog") </code></pre> <p>And running:</p> <pre><code>nltk.pos_tag(text) </code></pre> <p>I get:</p> <pre><code>[('The', 'DT'), ('quick', 'NN'), ('brown', 'NN'), ('fox', 'NN'), ('jumps', 'NNS'), ('over', 'IN'), ('the', 'DT'), ('lazy', 'NN'), ('dog', 'NN')] </code></pre> <p>This is incorrect. The tags for <code>quick brown lazy</code> in the sentence should be:</p> <pre><code>('quick', 'JJ'), ('brown', 'JJ') , ('lazy', 'JJ') </code></pre> <p>Testing this through their <a href="http://nlp.stanford.edu:8080/corenlp/process">online tool</a> gives the same result; <code>quick</code>, <code>brown</code> and <code>fox</code> should be adjectives not nouns.</p>
30,823,202
3
4
null
2015-06-13 16:52:28.27 UTC
25
2021-05-05 16:21:03.117 UTC
2015-06-16 00:12:25.887 UTC
null
1,118,542
null
4,996,173
null
1
36
python|machine-learning|nlp|nltk|pos-tagger
19,331
<p><strong>In short</strong>:</p> <blockquote> <p>NLTK is not perfect. In fact, no model is perfect.</p> </blockquote> <p><strong>Note:</strong></p> <p>As of NLTK version 3.1, default <code>pos_tag</code> function is no longer the <a href="https://stackoverflow.com/questions/31386224/what-created-maxent-treebank-pos-tagger-english-pickle">old MaxEnt English pickle</a>. </p> <p>It is now the <strong>perceptron tagger</strong> from <a href="https://github.com/nltk/nltk/blob/develop/nltk/tag/perceptron.py" rel="noreferrer">@Honnibal's implementation</a>, see <a href="https://github.com/nltk/nltk/blob/develop/nltk/tag/__init__.py#L87" rel="noreferrer"><code>nltk.tag.pos_tag</code></a></p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; print inspect.getsource(pos_tag) def pos_tag(tokens, tagset=None): tagger = PerceptronTagger() return _pos_tag(tokens, tagset, tagger) </code></pre> <p>Still it's better but not perfect:</p> <pre><code>&gt;&gt;&gt; from nltk import pos_tag &gt;&gt;&gt; pos_tag("The quick brown fox jumps over the lazy dog".split()) [('The', 'DT'), ('quick', 'JJ'), ('brown', 'NN'), ('fox', 'NN'), ('jumps', 'VBZ'), ('over', 'IN'), ('the', 'DT'), ('lazy', 'JJ'), ('dog', 'NN')] </code></pre> <p>At some point, if someone wants <code>TL;DR</code> solutions, see <a href="https://github.com/alvations/nltk_cli" rel="noreferrer">https://github.com/alvations/nltk_cli</a></p> <hr> <p><strong>In long</strong>:</p> <p><strong>Try using other tagger (see <a href="https://github.com/nltk/nltk/tree/develop/nltk/tag" rel="noreferrer">https://github.com/nltk/nltk/tree/develop/nltk/tag</a>) , e.g.</strong>:</p> <ul> <li>HunPos</li> <li>Stanford POS</li> <li>Senna</li> </ul> <p><strong>Using default MaxEnt POS tagger from NLTK, i.e. <code>nltk.pos_tag</code></strong>:</p> <pre><code>&gt;&gt;&gt; from nltk import word_tokenize, pos_tag &gt;&gt;&gt; text = "The quick brown fox jumps over the lazy dog" &gt;&gt;&gt; pos_tag(word_tokenize(text)) [('The', 'DT'), ('quick', 'NN'), ('brown', 'NN'), ('fox', 'NN'), ('jumps', 'NNS'), ('over', 'IN'), ('the', 'DT'), ('lazy', 'NN'), ('dog', 'NN')] </code></pre> <p><strong>Using Stanford POS tagger</strong>:</p> <pre><code>$ cd ~ $ wget http://nlp.stanford.edu/software/stanford-postagger-2015-04-20.zip $ unzip stanford-postagger-2015-04-20.zip $ mv stanford-postagger-2015-04-20 stanford-postagger $ python &gt;&gt;&gt; from os.path import expanduser &gt;&gt;&gt; home = expanduser("~") &gt;&gt;&gt; from nltk.tag.stanford import POSTagger &gt;&gt;&gt; _path_to_model = home + '/stanford-postagger/models/english-bidirectional-distsim.tagger' &gt;&gt;&gt; _path_to_jar = home + '/stanford-postagger/stanford-postagger.jar' &gt;&gt;&gt; st = POSTagger(path_to_model=_path_to_model, path_to_jar=_path_to_jar) &gt;&gt;&gt; text = "The quick brown fox jumps over the lazy dog" &gt;&gt;&gt; st.tag(text.split()) [(u'The', u'DT'), (u'quick', u'JJ'), (u'brown', u'JJ'), (u'fox', u'NN'), (u'jumps', u'VBZ'), (u'over', u'IN'), (u'the', u'DT'), (u'lazy', u'JJ'), (u'dog', u'NN')] </code></pre> <p><strong>Using HunPOS</strong> (NOTE: the default encoding is ISO-8859-1 not UTF8):</p> <pre><code>$ cd ~ $ wget https://hunpos.googlecode.com/files/hunpos-1.0-linux.tgz $ tar zxvf hunpos-1.0-linux.tgz $ wget https://hunpos.googlecode.com/files/en_wsj.model.gz $ gzip -d en_wsj.model.gz $ mv en_wsj.model hunpos-1.0-linux/ $ python &gt;&gt;&gt; from os.path import expanduser &gt;&gt;&gt; home = expanduser("~") &gt;&gt;&gt; from nltk.tag.hunpos import HunposTagger &gt;&gt;&gt; _path_to_bin = home + '/hunpos-1.0-linux/hunpos-tag' &gt;&gt;&gt; _path_to_model = home + '/hunpos-1.0-linux/en_wsj.model' &gt;&gt;&gt; ht = HunposTagger(path_to_model=_path_to_model, path_to_bin=_path_to_bin) &gt;&gt;&gt; text = "The quick brown fox jumps over the lazy dog" &gt;&gt;&gt; ht.tag(text.split()) [('The', 'DT'), ('quick', 'JJ'), ('brown', 'JJ'), ('fox', 'NN'), ('jumps', 'NNS'), ('over', 'IN'), ('the', 'DT'), ('lazy', 'JJ'), ('dog', 'NN')] </code></pre> <p><strong>Using Senna</strong> (Make sure you've the latest version of NLTK, there were some changes made to the API):</p> <pre><code>$ cd ~ $ wget http://ronan.collobert.com/senna/senna-v3.0.tgz $ tar zxvf senna-v3.0.tgz $ python &gt;&gt;&gt; from os.path import expanduser &gt;&gt;&gt; home = expanduser("~") &gt;&gt;&gt; from nltk.tag.senna import SennaTagger &gt;&gt;&gt; st = SennaTagger(home+'/senna') &gt;&gt;&gt; text = "The quick brown fox jumps over the lazy dog" &gt;&gt;&gt; st.tag(text.split()) [('The', u'DT'), ('quick', u'JJ'), ('brown', u'JJ'), ('fox', u'NN'), ('jumps', u'VBZ'), ('over', u'IN'), ('the', u'DT'), ('lazy', u'JJ'), ('dog', u'NN')] </code></pre> <hr> <p><strong>Or try building a better POS tagger</strong>:</p> <ul> <li>Ngram Tagger: <a href="http://streamhacker.com/2008/11/03/part-of-speech-tagging-with-nltk-part-1/" rel="noreferrer">http://streamhacker.com/2008/11/03/part-of-speech-tagging-with-nltk-part-1/</a></li> <li>Affix/Regex Tagger: <a href="http://streamhacker.com/2008/11/10/part-of-speech-tagging-with-nltk-part-2/" rel="noreferrer">http://streamhacker.com/2008/11/10/part-of-speech-tagging-with-nltk-part-2/</a> </li> <li>Build Your Own Brill (Read the code it's a pretty fun tagger, <a href="http://www.nltk.org/_modules/nltk/tag/brill.html" rel="noreferrer">http://www.nltk.org/_modules/nltk/tag/brill.html</a>), see <a href="http://streamhacker.com/2008/12/03/part-of-speech-tagging-with-nltk-part-3/" rel="noreferrer">http://streamhacker.com/2008/12/03/part-of-speech-tagging-with-nltk-part-3/</a></li> <li>Perceptron Tagger: <a href="https://honnibal.wordpress.com/2013/09/11/a-good-part-of-speechpos-tagger-in-about-200-lines-of-python/" rel="noreferrer">https://honnibal.wordpress.com/2013/09/11/a-good-part-of-speechpos-tagger-in-about-200-lines-of-python/</a></li> <li>LDA Tagger: <a href="http://scm.io/blog/hack/2015/02/lda-intentions/" rel="noreferrer">http://scm.io/blog/hack/2015/02/lda-intentions/</a></li> </ul> <hr> <p><strong>Complains about <code>pos_tag</code> accuracy on stackoverflow include</strong>:</p> <ul> <li><a href="https://stackoverflow.com/questions/13529945/pos-tagging-nltk-thinks-noun-is-adjective">POS tagging - NLTK thinks noun is adjective</a></li> <li><a href="https://stackoverflow.com/questions/21786257/python-nltk-pos-tagger-not-behaving-as-expected">python NLTK POS tagger not behaving as expected</a></li> <li><a href="https://stackoverflow.com/questions/8146748/how-to-obtain-better-results-using-nltk-pos-tag">How to obtain better results using NLTK pos tag</a></li> <li><a href="https://stackoverflow.com/questions/8365557/pos-tag-in-nltk-does-not-tag-sentences-correctly">pos_tag in NLTK does not tag sentences correctly</a></li> </ul> <p><strong>Issues about NLTK HunPos include</strong>:</p> <ul> <li><a href="https://stackoverflow.com/questions/5088448/how-to-i-tag-textfiles-with-hunpos-in-nltk">How do I tag textfiles with hunpos in nltk?</a> </li> <li><a href="https://stackoverflow.com/questions/5091389/does-anyone-know-how-to-configure-the-hunpos-wrapper-class-on-nltk">Does anyone know how to configure the hunpos wrapper class on nltk?</a></li> </ul> <p><strong>Issues with NLTK and Stanford POS tagger include</strong>:</p> <ul> <li><a href="https://stackoverflow.com/questions/7344916/trouble-importing-stanford-pos-tagger-into-nltk">trouble importing stanford pos tagger into nltk</a></li> <li><a href="https://stackoverflow.com/questions/27116495/java-command-fails-in-nltk-stanford-pos-tagger">Java Command Fails in NLTK Stanford POS Tagger</a></li> <li><a href="https://stackoverflow.com/questions/22930328/error-using-stanford-pos-tagger-in-nltk-python">Error using Stanford POS Tagger in NLTK Python</a></li> <li><a href="https://stackoverflow.com/questions/23322674/how-to-improve-speed-with-stanford-nlp-tagger-and-nltk">How to improve speed with Stanford NLP Tagger and NLTK</a></li> <li><a href="https://stackoverflow.com/questions/27171298/nltk-stanford-pos-tagger-error-java-command-failed">Nltk stanford pos tagger error : Java command failed</a></li> <li><a href="https://stackoverflow.com/questions/8555312/instantiating-and-using-stanfordtagger-within-nltk">Instantiating and using StanfordTagger within NLTK</a></li> <li><a href="https://stackoverflow.com/questions/26647253/running-stanford-pos-tagger-in-nltk-leads-to-not-a-valid-win32-application-on">Running Stanford POS tagger in NLTK leads to &quot;not a valid Win32 application&quot; on Windows</a></li> </ul>
39,311,872
Is performance reduced when executing loops whose uop count is not a multiple of processor width?
<p>I'm wondering how loops of various sizes perform on recent x86 processors, as a function of number of uops.</p> <p>Here's a quote from Peter Cordes who raised the issue of non-multiple-of-4 counts in <a href="https://stackoverflow.com/a/31027695/149138">another question</a>:</p> <blockquote> <p>I also found that the uop bandwidth out of the loop buffer isn't a constant 4 per cycle, if the loop isn't a multiple of 4 uops. (i.e. it's abc, abc, ...; not abca, bcab, ...). Agner Fog's microarch doc unfortunately wasn't clear on this limitation of the loop buffer.</p> </blockquote> <p>The issue is about whether loops need to be a multiple of N uops to execute at maximum uop throughput, where N is the width of the processor. (i.e., 4 for recent Intel processors). There are a lot of complicating factors when talking about "width" and count uops, but I mostly want to ignore those. In particular, assume no micro or macro-fusion.</p> <p>Peter gives the following example of a loop with 7 uops in its body:</p> <blockquote> <p>A 7-uop loop will issue groups of 4|3|4|3|... I haven't tested larger loops (that don't fit in the loop buffer) to see if it's possible for the first instruction from the next iteration to issue in the same group as the taken-branch to it, but I assume not.</p> </blockquote> <p>More generally, the claim is that each iteration of a loop with <code>x</code> uops in its body will take at least <code>ceil(x / 4)</code> iterations, rather than simply <code>x / 4</code>. </p> <p>Is this true for some or all recent x86-compatible processors?</p>
39,940,932
3
22
null
2016-09-03 22:28:22.093 UTC
17
2020-05-16 09:28:01.187 UTC
2017-08-30 04:23:47.24 UTC
null
149,138
null
149,138
null
1
32
performance|assembly|x86|cpu-architecture|micro-optimization
4,461
<p>I did some investigation with Linux <code>perf</code> to help answer this on my Skylake <a href="http://ark.intel.com/products/88967/Intel-Core-i7-6700HQ-Processor-6M-Cache-up-to-3_50-GHz" rel="noreferrer">i7-6700HQ</a> box, and Haswell results have been kindly provided by another user. The analysis below applies to Skylake, but it is followed by a comparison versus Haswell.</p> <p>Other architectures may vary<sup>0</sup>, and to help sort it all out I welcome additional results. The <a href="https://github.com/travisdowns/x86-loop-test" rel="noreferrer">source is available</a>).</p> <p>This question mostly deals with the front end, since on recent architectures it is the front end which imposes the hard limit of four fused-domain uops per cycle.</p> <h1>Summary of Rules for Loop Performance</h1> <p>First, I'll summarize the results in terms of a few "performance rules" to keep in mind when dealing with small loops. There are plenty of other performance rules as well - these are complementary to them (i.e., you probably don't break another rule to just to satisfy these ones). These rules apply most directly to Haswell and later architectures - see the <a href="https://stackoverflow.com/a/53148682/149138">other answer</a> for an overview of the differences on earlier architectures.</p> <p>First, count the number of <em>macro-fused</em> uops in your loop. You can use Agner's <a href="http://www.agner.org/optimize/#manual_instr_tab" rel="noreferrer">instruction tables</a> to look this up directly for every instruction, except that an ALU uop and immediately follow branch will usually fuse together into a single uop. Then based on this count:</p> <ul> <li>If the count is a multiple of 4, you're good: these loops execute optimally.</li> <li>If the count is even and less than 32, you're good, except if it's 10 in which case you should unroll to another even number if you can.</li> <li>For odd numbers you should try to unroll to an even number less than 32 or a multiple of 4, if you can. </li> <li>For loops larger than 32 uops but less than 64, you might want to unroll if it isn't already a multiple of 4: with more than 64 uops you'll get efficient performance at any value on Sklyake and almost all values on Haswell (with a few deviations, possibly alignment related). The inefficiencies for these loops are still relatively small: the values to avoid most are <code>4N + 1</code> counts, followed by <code>4N + 2</code> counts.</li> </ul> <h1>Summary of Findings</h1> <p>For code served out of the uop cache, there are no apparent multiple-of-4 effects. Loops of any number of uops can be executed at a throughput of 4 fused-domain uops per cycle.</p> <p>For code processed by the legacy decoders, the opposite is true: loop execution time is limited to integral number of cycles, and hence loops that are not a multiple of 4 uops cannot achieve 4 uops/cycle, as they waste some issue/execution slots. </p> <p>For code issued from the loop stream detector (LSD), the situation is a mix of the two and is explained in more detail below. In general, loops less than 32 uops and with an even number of uops execute optimally, while odd-sized loops do not, and larger loops require a multiple-of-4 uop count to execute optimally.</p> <h1>What Intel Says</h1> <p>Intel actually has a note on this in their optimization manual, details in the other answer.</p> <h1>Details</h1> <p>As anyone well-versed recent x86-64 architectures knows, at any point the fetch and decode portion of the front end may be working in one several different modes, depending on the code size and other factors. As it turns out, these different modes all have different behaviors with respect to loop sizing. I'll cover them separately follow.</p> <h2>Legacy Decoder</h2> <p>The <em>legacy decoder</em><sup>1</sup> is the full machine-code-to-uops decoder that is used<sup>2</sup> when the code doesn't fit in the uop caching mechanisms (LSD or DSB). The primary reason this would occur is if the code working set is larger than the uop cache (approximately ~1500 uops in the ideal case, less in practice). For this test though, we'll take advantage of the fact that the legacy decoder will also be used if an aligned 32-byte chunk contains more than 18 instructions<sup>3</sup>. </p> <p>To test the legacy decoder behavior, we use a loop that looks like this:</p> <pre><code>short_nop: mov rax, 100_000_000 ALIGN 32 .top: dec rax nop ... jnz .top ret </code></pre> <p>Basically, a trivial loop that counts down until <code>rax</code> is zero. All instructions are a single uop<sup>4</sup> and the number of <code>nop</code> instructions is varied (at the location shown as <code>...</code>) to test different sizes of loops (so a 4-uop loop will have 2 <code>nop</code>s, plus the two loop control instructions). There is no macro-fusion as we always separate the <code>dec</code> and <code>jnz</code> with at least one <code>nop</code>, and also no micro-fusion. Finally, there is no memory access at (outside of the implied icache access).</p> <p>Note that this loop is very <em>dense</em> - about 1 byte per instruction (since the <code>nop</code> instructions are 1 byte each) - so we'll trigger the > 18 instructions in a 32B chunk condition as soon as hit 19 instructions in the loop. Based on examining the <code>perf</code> performance counters <code>lsd.uops</code> and <code>idq.mite_uops</code> that's exactly what we see: essentially 100% of the instructions come out of the LSD<sup>5</sup> up until and including the 18 uop loop, but at 19 uops and up, 100% come from the legacy decoder.</p> <p>In any case, here are the cycles/iteration for all loop sizes from 3 to 99 uops<sup>6</sup>:</p> <p><a href="https://i.stack.imgur.com/ymXt5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ymXt5.png" alt="Cyles/iteration for loops with given size"></a> </p> <p>The blue points are the loops that fit in the LSD, and show somewhat complex behavior. We'll look at these later. </p> <p>The red points (starting at 19 uops/iteration), are handled by the legacy decoder, and show a very predictable pattern:</p> <ul> <li>All loops with <code>N</code> uops take exactly <code>ceiling(N/4)</code> iterations</li> </ul> <p>So, for the legacy decoder at least, Peter's observation holds exactly on Skylake: loops with a <em>multiple of 4 uops</em> may execute at an IPC of 4, but any other number of uops will waste 1, 2 or 3 execution slots (for loops with <code>4N+3</code>, <code>4N+2</code>, <code>4N+1</code> instructions, respectively).</p> <p>It is not clear to me why this happens. Although it may seem obvious if you consider that decoding happens in contiguous 16B chunks, and so at a decoding rate of 4 uops/cycle loops not a multiple of 4 would always have some trailing (wasted) slots in the cycle the <code>jnz</code> instruction is encountered. However, the actual fetch &amp; decode unit is composed of predecode and decode phases, with a queue in-between. The predecode phase actually has a throughput of <em>6</em> instructions, but only decodes to the end of the 16-byte boundary on each cycle. This seems to imply that the bubble that occurs at the end of the loop could be absorbed by the predecoder -> decode queue since the predecoder has an average throughput higher than 4.</p> <p>So I can't fully explain this based on my understanding of how the predecoder works. It may be that there is some additional limitation in decoding or pre-decoding that prevents non-integral cycle counts. For example, perhaps the legacy decoders cannot decode instructions on both sides of a jump even if the instructions after the jump are available in the predecoded queue. Perhaps it is related to the need to <a href="http://www.agner.org/optimize/blog/read.php?i=142#272" rel="noreferrer">handle</a> macro-fusion.</p> <p>The test above shows the behavior where the top of the loop is aligned on a 32-byte boundary. Below is the same graph, but with an added series that shows the effect when the top of loop is moved 2 bytes up (i.e, now misaligned at a 32N + 30 boundary):</p> <p><a href="https://i.stack.imgur.com/bgFzN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bgFzN.png" alt="Legacy decoder cycles/iteration when misaligned"></a></p> <p>Most loop sizes now suffer a 1 or 2 cycle penalty. The 1 penalty case makes sense when you consider decoding 16B boundaries and 4-instructions per cycle decoding, and the 2 cycle penalty cases occurs for loops where for some reason the DSB is used for 1 instruction in the loop (probably the <code>dec</code> instruction which appears in its own 32-byte chunk), and some DSB&lt;->MITE switching penalties are incurred.</p> <p>In some cases, the misalignment doesn't hurt when it ends up better aligning the end of the loop. I tested the misalignment and it persists in the same way up to 200 uop loops. If you take the description of the predecoders at face value, it would seem that, as above, they should be able to hide a fetch bubble for misalignment, but it doesn't happen (perhaps the queue is not big enough).</p> <h2>DSB (Uop Cache)</h2> <p>The uop cache (Intel likes to call it the DSB) is able to cache most loops of moderate amount of instructions. In a typical program, you'd hope that most of your instructions are served out of this cache<sup>7</sup>. </p> <p>We can repeat the test above, but now serving uops out of the uop cache. This is a simple matter of increasing the size of our nops to 2 bytes, so we no longer hit the 18-instruction limit. We use the 2-byte nop <code>xchg ax, ax</code> in our loop:</p> <pre><code>long_nop_test: mov rax, iters ALIGN 32 .top: dec eax xchg ax, ax ; this is a 2-byte nop ... xchg ax, ax jnz .top ret </code></pre> <p>Here, there results are very straightforward. For all tested loop sizes delivered out of the DSB, the number of cycles required was <code>N/4</code> - i.e., the loops executed at the maximum theoretical throughput, even if they didn't have a multiple of 4 uops. So in general, on Skylake, moderately sized loops served out of the DSB shouldn't need to worry about ensuring the uop count meets some particular multiple.</p> <p>Here's a graph out to 1,000 uop loops. If you squint, you can see the sub-optimal behavior before 64-uops (when the loop is in the LSD). After that, it's a straight shot, 4 IPC the whole way to 1,000 uops (with a blip around 900 that was probably due to load on my box):</p> <p><a href="https://i.stack.imgur.com/UHEaN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UHEaN.png" alt="Cycle counts for loops served out of the DSB"></a></p> <p>Next we look at performance for loops that are small enough to fit in the uop cache.</p> <h2>LSD (Loop steam detector)</h2> <p><strong>Important note:</strong> Intel has apparently <em>disabled</em> the LSD on Skylake (SKL150 erratum) and Kaby Lake (KBL095, KBW095 erratum) chips via a microcode update and on Skylake-X out of the box, due to <a href="http://gallium.inria.fr/blog/intel-skylake-bug/" rel="noreferrer">a bug</a> related to the interaction between hyperthreading and the LSD. For those chips, the graph below will likely not have the interesting region up to 64 uops; rather, it will just look the same as the region after 64 uops.</p> <p>The loop stream detector can cache small loops of up to 64 uops (on Skylake). In Intel's recent documentation it is positioned more as a power-saving mechanism than a performance feature - although there are certainly no performance downsides mentioned to using the LSD.</p> <p>Running this for the loop sizes that should fit in the LSD, we get the following cycles/iteration behavior:</p> <p><a href="https://i.stack.imgur.com/uEILw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uEILw.png" alt="Cycles per Iteration for LSD-resident loops"></a></p> <p>The red line here is the % of uops which are delivered from the LSD. It flatlines at 100% for all loop sizes from 5 to 56 uops.</p> <p>For the 3 and 4 uop loops, we have the unusual behavior that 16% and 25% of the uops, respectively, are delivered from the legacy decoder. Huh? Luckily, it doesn't seem to affect the loop throughput as both cases achieve the maximum throughput of 1 loop/cycle - despite the fact that one could expect some MITE&lt;->LSD transition penalties.</p> <p>Between loop sizes of 57 and 62 uops, the number of uops delivered from LSD exhibits some weird behavior - approximately 70% of the uops are delivered from the LSD, and the rest from the DSB. Skylake nominally has a 64-uop LSD, so this is some kind of transition right before the LSD size is exceeded - perhaps there is some kind of internal alignment within the IDQ (on which the LSD is implemented) that causes only partial hits to the LSD in this phase. This phase is short and, performance-wise, seems mostly to be a linear combination of the full-in-LSD performance which precedes it, and the fully-in-DSB performance which follows it.</p> <p>Let's look at the main body of results between 5 and 56 uops. We see three distinct regions:</p> <p><strong>Loops from 3 to 10 uops:</strong> Here, the behavior is complex. It is the only region where we see cycle counts that can't be explained by static behavior over a single loop iteration<sup>8</sup>. The range is short enough that it's hard to say if there is a pattern. Loops of 4, 6 and 8 uops all execute optimally, in <code>N/4</code> cycles (that's the same pattern as the next region).</p> <p>A loop of 10 uops, on the other hand, executes in 2.66 cycles per iteration, making it the only even loop size that doesn't execute optimally until you get to loop sizes of 34 uops or above (other than the outlier at 26). That corresponds to something like a repeated uop/cycle execution rate of <code>4, 4, 4, 3</code>. For a loop of 5 uops, you get 1.33 cycles per iteration, very close but not the same as the ideal of 1.25. That corresponds to an execution rate of <code>4, 4, 4, 4, 3</code>.</p> <p>These results are hard to explain. The results are repeatable from run to run, and robust to changes such as swapping out the nop for an instruction that actually does something like <code>mov ecx, 123</code>. It might be something to do with the limit of 1 taken branch every 2 cycles, which applies to all loops except those that are "very small". It might be that the uops occasionally line up such that this limitation kicks in, leading to an extra cycle. Once you get to 12 uops or above, this never occurs since you are always taking at least three cycles per iteration.</p> <p><strong>Loops from 11 to 32-uops:</strong> We see a stair-step pattern, but with a period of two. Basically all loops with an <em>even</em> number of uops perform optimally - i.e., taking exactly <code>N/4</code> cycles. Loops with odd number of uops waste one "issue slot", and take the same number of cycles as a loop with one more uops (i.e., a 17 uop loop takes the same 4.5 cycles as an 18 uop loop). So here we have behavior better than <code>ceiling(N/4)</code> for many uop counts, and we have the first evidence that Skylake at least can execute loops in a non-integral number of cycles.</p> <p>The only outliers are N=25 and N=26, which both take about 1.5% longer than expected. It's small but reproducible, and robust to moving the function around in the file. That's too small to be explained by a per-iteration effect, unless it has a giant period, so it's probably something else. </p> <p>The overall behavior here is exactly consistent (outside of the 25/26 anomaly) with the hardware <strong>unrolling the loop</strong> by a factor of 2.</p> <p><strong>Loops from 33 to ~64 uops:</strong> We see a stair-step pattern again, but with a period of 4, and worse average performance than the up-to 32 uop case. The behavior is exactly <code>ceiling(N/4)</code> - that is, the same as the legacy decoder case. So for loops of 32 to 64 uops, the LSD provides no apparent benefit over the legacy decoders, <em>in terms of front end throughput for this particular limitation</em>. Of course, there are many other ways the LSD is better - it avoids many of the potential decoding bottlenecks that occur for more complex or longer instructions, and it saves power, etc.</p> <p>All of this is quite surprising, because it means that loops delivered from the uop cache generally perform <em>better</em> in the front end than loops delivered from the LSD, despite the LSD usually being positioned as a strictly better source of uops than the DSB (e.g., as part of advice to try to keep loops small enough to fit in the LSD).</p> <p>Here's another way to look at the same data - in terms of the efficiency loss for a given uop count, versus the theoretical maximum throughput of 4 uops per cycle. A 10% efficiency hit means you only have 90% of the throughput that you'd calculate from the simple <code>N/4</code> formula.</p> <p>The overall behavior here is consistent with the hardware not doing any unrolling, which makes sense since a loop of more than 32 uops cannot be unrolled at all in a buffer of 64 uops. </p> <p><a href="https://i.stack.imgur.com/0GbQb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0GbQb.png" alt="Efficiency Loss by Loop Size"></a></p> <p>The three regions discussed above are colored differently, and at least competing effects are visible:</p> <ol> <li><p>Everything else being equal, the larger the number of uops involved, the lower the efficiency hit. The hit is a fixed cost only once per iteration, so larger loops pay a smaller <em>relative</em> cost.</p></li> <li><p>There is a large jump in inefficiency when you cross to into the 33+ uop region: both the size of the throughput loss increases, and the number of affected uop counts doubles.</p></li> <li><p>The first region is somewhat chaotic, and 7 uops is the worst overall uop count. </p></li> </ol> <h2>Alignment</h2> <p>The DSB and LSD analysis above is for loop entries aligned to a 32-byte boundary, but the unaligned case doesn't seem to suffer in either case: there isn't a material difference from the aligned case (other than perhaps some small variation for less than 10 uops that I didn't investigate further).</p> <p>Here's the unaligned results for <code>32N-2</code> and <code>32N+2</code> (i.e., the loop top 2 bytes before and after the 32B boundary):</p> <p><a href="https://i.stack.imgur.com/U80KV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/U80KV.png" alt="Misaligned Cycles per Iteration"></a></p> <p>The ideal <code>N/4</code> line is also shown for reference.</p> <h1>Haswell</h1> <p>Next next take a look at the prior microarchitecture: Haswell. The numbers here have been graciously provided by user <a href="https://stackoverflow.com/users/2809095/iwillnotexist-idonotexist">Iwillnotexist Idonotexist</a>.</p> <h2>LSD + Legacy Decode Pipeline</h2> <p>First, the results from the "dense code" test which tests the LSD (for small uop counts) and the legacy pipeline (for larger uop counts, since the loop "busts out" of the DSB due to instruction density.</p> <p>Immediately we see a difference already in terms of <em>when</em> each architecture delivers uops from the LSD for a dense loop. Below we compare Skylake and Haswell for short loops of <em>dense</em> code (1 byte per instruction).</p> <p><a href="https://i.stack.imgur.com/NwINS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NwINS.png" alt="Haswell vs Skylake LSD Delivery %"></a></p> <p>As described above, the Skylake loop stops being delivered from the LSD at exactly 19 uops, as expected from the 18-uop per 32-byte region of code limit. Haswell, on the other hand, seems to stop delivering reliably from the LSD for the 16-uop and 17-uop loops as well. I don't have any explanation for this. There is also a difference in the 3-uop case: oddly both processors only deliver <em>some</em> of the their uops out of the LSD in the 3 and 4 uop cases, but the exact amount is the same for 4 uops, and different from 3.</p> <p>We mostly care about the actual performance though, right? So let's look at the cycles/iteration for the 32-byte aligned <em>dense</em> code case:</p> <p><a href="https://i.stack.imgur.com/Mir6K.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Mir6K.png" alt="Haswell vs Skylake LSD + Legacy Pipeline"></a> </p> <p>This is the same data as show above for Skylake (the misaligned series has been removed), with Haswell plotted alongside. Immediately you notice that the pattern is <em>similar</em> for Haswell, but not the same. As above, there are two regions here:</p> <h3>Legacy Decode</h3> <p>The loops larger than ~16-18 uops (the uncertainty is described above) are delivered from the legacy decoders. The pattern for Haswell is somewhat different from Skylake.</p> <p>For the range from 19-30 uops they are identical, but after that Haswell breaks the pattern. Skylake took <code>ceil(N/4)</code> cycles for loops delivered from the legacy decoders. Haswell, on the other hand, seems to take something like <code>ceil((N+1)/4) + ceil((N+2)/12) - ceil((N+1)/12)</code>. OK, that's messy (shorter form, anyone?) - but basically it means that while Skylake executes loops with 4*N cycles optimally (i.e,. at 4-uops/cycle), such loops are (locally) usually the <em>least</em> optimal count (at least locally) - it takes one more cycle to execute such loops than Skylake. So you are actually best off with loops of 4N-1 uops on Haswell, <em>except</em> that the 25% of such loops that are <em>also</em> of the form 16-1N (31, 47, 63, etc) take one additional cycle. It's starting to sound like a leap year calculation - but the pattern is probably best understood visually above.</p> <p>I don't think this pattern is <em>intrinsic</em> to uop dispatch on Haswell, so we shouldn't read to much into it. It seems to be explained by </p> <pre><code>0000000000455a80 &lt;short_nop_aligned35.top&gt;: 16B cycle 1 1 455a80: ff c8 dec eax 1 1 455a82: 90 nop 1 1 455a83: 90 nop 1 1 455a84: 90 nop 1 2 455a85: 90 nop 1 2 455a86: 90 nop 1 2 455a87: 90 nop 1 2 455a88: 90 nop 1 3 455a89: 90 nop 1 3 455a8a: 90 nop 1 3 455a8b: 90 nop 1 3 455a8c: 90 nop 1 4 455a8d: 90 nop 1 4 455a8e: 90 nop 1 4 455a8f: 90 nop 2 5 455a90: 90 nop 2 5 455a91: 90 nop 2 5 455a92: 90 nop 2 5 455a93: 90 nop 2 6 455a94: 90 nop 2 6 455a95: 90 nop 2 6 455a96: 90 nop 2 6 455a97: 90 nop 2 7 455a98: 90 nop 2 7 455a99: 90 nop 2 7 455a9a: 90 nop 2 7 455a9b: 90 nop 2 8 455a9c: 90 nop 2 8 455a9d: 90 nop 2 8 455a9e: 90 nop 2 8 455a9f: 90 nop 3 9 455aa0: 90 nop 3 9 455aa1: 90 nop 3 9 455aa2: 90 nop 3 9 455aa3: 75 db jne 455a80 &lt;short_nop_aligned35.top&gt; </code></pre> <p>Here I've noted the 16B decode chunk (1-3) each instruction appears in, and the cycle in which it will be decoded. The rule is basically that up to the next 4 instructions are decoded, as long as they fall in the current 16B chunk. Otherwise they have to wait until the next cycle. For N=35, we see that there is a loss of 1 decode slot in cycle 4 (only 3 instruction are left in the 16B chunk), but that otherwise the loop lines up very well with the 16B boundaries and even the last cycle (9) can decode 4 instructions. </p> <p>Here's a truncated look at N=36, which is identical except for the end of the loop:</p> <pre><code>0000000000455b20 &lt;short_nop_aligned36.top&gt;: 16B cycle 1 1 455a80: ff c8 dec eax 1 1 455b20: ff c8 dec eax 1 1 455b22: 90 nop ... [29 lines omitted] ... 2 8 455b3f: 90 nop 3 9 455b40: 90 nop 3 9 455b41: 90 nop 3 9 455b42: 90 nop 3 9 455b43: 90 nop 3 10 455b44: 75 da jne 455b20 &lt;short_nop_aligned36.top&gt; </code></pre> <p>There are now 5 instructions to decode in the 3rd and final 16B chunk, so one additional cycle is needed. Basically 35 instructions, <em>for this particular pattern of instructions</em> happens to line up better with the 16B bit boundaries and saves one cycle when decoding. This doesn't mean that N=35 is better than N=36 in general! Different instructions will have different numbers of bytes and will line up differently. A similar alignment issue explains also the additional cycle that is required every 16 bytes: </p> <pre><code>16B cycle ... 2 7 45581b: 90 nop 2 8 45581c: 90 nop 2 8 45581d: 90 nop 2 8 45581e: 90 nop 3 8 45581f: 75 df jne 455800 &lt;short_nop_aligned31.top&gt; </code></pre> <p>Here the final <code>jne</code> has slipped into the next 16B chunk (if an instruction spans a 16B boundary it is effectively in the latter chunk), causing an extra cycle loss. This occurs only every 16 bytes.</p> <p>So the Haswell legacy decoder results are explained perfectly by a legacy decoder that behaves as described, for example, in Agner Fog's <a href="http://www.agner.org/optimize/#manual_microarch" rel="noreferrer">microarchitecture doc</a>. In fact, it also seems to explain Skylake results if you assume Skylake can decode 5 instructions per cycle (delivering up to 5 uops)<sup>9</sup>. Assuming it can, the asymptotic legacy decode throughput <em>on this code</em> for Skylake is still 4-uops, since a block of 16 nops decodes 5-5-5-1, versus 4-4-4-4 on Haswell, so you only get benefits at the edges: in the N=36 case above, for example, Skylake can decode all remaining 5 instructions, versus 4-1 for Haswell, saving a cycle.</p> <p>The upshot is that it seems to be that the legacy decoder behavior can be understood in a fairly straightforward manner, and the main optimization advice is to continue to massage code so that it falls "smartly" into the 16B aligned chunks (perhaps that's NP-hard like bin packing?).</p> <h2>DSB (and LSD again)</h2> <p>Next let's take a look at the scenario where the code is served out of the LSD or DSB - by using the "long nop" test which avoids breaking the 18-uop per 32B chunk limit, and so stays in the DSB.</p> <p>Haswell vs Skylake:</p> <p><a href="https://i.stack.imgur.com/Rtnuw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Rtnuw.png" alt="Haswell vs Skylake LSD and DSB"></a></p> <p>Note the LSD behavior - here Haswell stops serving out of the LSD at exactly 57 uops, which is completely consistent with the published size of the LSD of 57 uops. There is no weird "transition period" like we see on Skylake. Haswell also has the weird behavior for 3 and 4 uops where only ~0% and ~40% of the uops, respectively, come from the LSD.</p> <p>Performance-wise, Haswell is normally in-line with Skylake with a few deviations, e.g., around 65, 77 and 97 uops where it rounds up to the next cycle, whereas Skylake is always able to sustain 4 uops/cycle even when that's results in a non-integer number of cycles. The slight deviation from expected at 25 and 26 uops has disappeared. Perhaps the 6-uop delivery rate of Skylake helps it avoid uop-cache alignment issues that Haswell suffers with its 4-uop delivery rate. </p> <h1>Other Architectures</h1> <p>Results for the following additional architectures were kindly provided by user Andreas Abel, but we'll have to use another answer for further analysis as we are at the character limit here.</p> <h1>Help Needed</h1> <p>Although results for many platforms have been kindly offered by the community, I'm still interested in results on chips older than Nehalem, and newer than Coffee Lake (in particular, Cannon Lake, which is a new uarch). The code to generate these results <a href="https://github.com/travisdowns/x86-loop-test" rel="noreferrer">is public</a>. Also, the results above <a href="https://github.com/travisdowns/x86-loop-test/blob/master/loop_test.ods" rel="noreferrer">are available</a> in <code>.ods</code> format in GitHub as well. </p> <hr> <p><sup>0</sup> In particular, the legacy decoder maximum throughput apparently increased from 4 to 5 uops in Skylake, and the maximum throughput for the uop cache increased from 4 to 6. Both of those could impact the results described here. </p> <p><sup>1</sup> Intel actually like to call the legacy decoder the MITE (Micro-instruction Translation Engine), perhaps because it's a faux-pas to actually tag any part of your architecture with the <em>legacy</em> connotation.</p> <p><sup>2</sup> Technically there is another, even slower, source of uops - the MS (microcode sequencing engine), which is used to implement any instruction with more than 4 uops, but we ignore this here since none of our loops contain microcoded instructions.</p> <p><sup>3</sup> This works because any aligned 32-byte chunk can use at most 3-ways in its uop cache slot, and each slot holds up to 6 uops. So if you use more than <code>3 * 6 = 18</code> uops in a 32B chunk, the code can't be stored in the uop cache at all. It's probably rare to encounter this condition in practice, since the code needs to be very dense (less than 2 bytes per instruction) to trigger this.</p> <p><sup>4</sup> The <code>nop</code> instructions decode to one uop, but don't are eliminated prior to execution (i.e., they don't use an execution port) - but still take up space in the front end and so count against the various limits that we are interested in. </p> <p><sup>5</sup> The LSD is the <em>loop stream detector</em>, which caches small loops of up to 64 (Skylake) uops directly in the IDQ. On earlier architectures it can hold 28 uops (both logical cores active) or 56 uops (one logical core active).</p> <p><sup>6</sup> We can't easily fit a 2 uop loop in this pattern, since that would mean zero <code>nop</code> instructions, meaning the <code>dec</code> and <code>jnz</code> instructions would macro-fuse, with a corresponding change in the uop count. Just take my word that all loops with 4 or less uops execute at best at 1 cycle/iteration.</p> <p><sup>7</sup> For fun, I just ran <code>perf stat</code> against a short run of Firefox where I opened a tab and clicked around on a few Stack Overflow questions. For instructions delivered, I got 46% from DSB, 50% from legacy decoder and 4% for LSD. This shows that at least for big, branchy code like a browser the DSB still can't capture the large majority of the code (lucky the legacy decoders aren't too bad). </p> <p><sup>8</sup> By this, I mean that all the other cycle counts can be explained by simply by taking an "effective" integral loop cost in uops (which might be higher than the actual size is uops) and dividing by 4. For these very short loops, this doesn't work - you can't get to 1.333 cycles per iteration by dividing any integer by 4. Said another way, in all other regions the costs have the form N/4 for some integer N.</p> <p><sup>9</sup> In fact we know that Skylake <em>can</em> deliver 5 uops per cycle from the legacy decoder, but we don't know if those 5 uops can come from 5 different instructions, or only 4 or less. That is, we expect that Skylake can decode in the pattern <code>2-1-1-1</code>, but I'm not sure if it can decode in the pattern <code>1-1-1-1-1</code>. The above results give some evidence that it can indeed decode <code>1-1-1-1-1</code>.</p>
35,715,400
Laravel 5.2 could not open laravel.log
<p>I know there are a lot of questions on this topic but my issues is really weird that's why I decided to post. I have this error in <code>/var/logs/apache/error.log</code></p> <pre><code> [Tue Mar 01 07:26:51.435312 2016] [:error] [pid 8837] [client 127.0.0.1:37843] PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'The stream or file "/var/www/personale/librarie-cor/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied' in /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:87\nStack trace: \n#0 /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\\Handler\\StreamHandler-&gt;write(Array) \n#1 /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Logger.php(289): Monolog\\Handler\\AbstractProcessingHandler-&gt;handle(Array) \n#2 /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Logger.php(565): Monolog\\Logger-&gt;addRecord(400, Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException), Array) \n#3 /var/www/personale/librarie-cor/vendor/laravel/framework/src/Illuminate/Log/Writer.php(202): Monolog\\Logger-&gt;error(Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException), Array) \n#4 /var/www/personale/librarie-cor in /var/www/personale/librarie-cor/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 87 </code></pre> <p>The thing is I already did <code>chmod -R 777 storage/</code>, here is a screenshot:</p> <p><a href="https://i.stack.imgur.com/tV1gS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tV1gS.png" alt="chmoded"></a> </p> <p>How can I get rid of the error?</p>
35,716,067
6
5
null
2016-03-01 05:34:45.837 UTC
10
2018-04-04 11:53:31.387 UTC
null
null
null
null
2,588,339
null
1
14
php|laravel|laravel-5|chmod
21,068
<p>I finally found a solution.. Seems like the problem had to do with PSR-4 and auto importing classes</p> <p>So here's the solution for anyone else having this problem: </p> <pre><code>php artisan clear-compiled composer dump-autoload php artisan optimize php artisan cache:clear </code></pre>
21,119,617
Does mmap or malloc allocate RAM?
<p>I know this is probably a stupid question but i've been looking for awhile and can't find a definitive answer. If I use <code>mmap</code> or <code>malloc</code> (in C, on a linux machine) does either one allocate space in RAM? For example, if I have 2GB of RAM and wanted to use all available RAM could I just use a <code>malloc/memset</code> combo, <code>mmap</code>, or is there another option I don't know of?</p> <p>I want to write a series of simple programs that can run simultaneously and keep all RAM used in the process to force swap to be used, and pages swapped in/out frequently. I tried this already with the program below, but it's not exactly what I want. It does allocate memory (RAM?), and force swap to be used (if enough instances are running), but when I call <code>sleep</code> doesn't that just lock the memory from being used (so nothing is actually being swapped in or out from other processes?), or am I misunderstanding something.</p> <p>For example, if I ran this 3 times would I be using 2GB (all) of RAM from the first two instances, and the third instance would then swap one of the previous two instances out (of RAM) and the current instance into RAM? Or would instance #3 just run using disk or virtual memory?</p> <p>This brings up another point, would I need to allocate enough memory to use all available virtual memory as well for the swap partition to be used?</p> <p>Lastly, would <code>mmap</code> (or any other C function. Hell, even another language if applicable) be better for doing this?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define MB(size) ( (size) * 1024 * 1024) #define GB(size) ( (size) * 1024 * 1024 * 1024) int main(){ char *p; p = (char *)malloc(MB(512)); memset(p, 'T', MB(512)); printf(".5 GB allocated...\n"); char *q; q = (char *)malloc(MB(512)); memset(q, 'T', MB(512)); printf("1 GB allocated...\n"); printf("Sleeping...\n"); sleep(300); } </code></pre> <p>** Edit: I am using CentOS 6.4 (with 3.6.0 kernel) for my OS, if that helps any.</p>
21,119,698
2
5
null
2014-01-14 17:12:02.353 UTC
9
2014-01-14 18:35:29.91 UTC
2014-01-14 17:58:47.533 UTC
null
1,488,719
null
1,488,719
null
1
13
c|linux|memory|malloc|mmap
11,127
<p>This is very OS/machine dependent.</p> <p>In most OSes neither allocates RAM. They both allocate VM space. They make a certain range of your processes virtual memory valid for use. RAM is normally allocated later by the OS on first write. Until then those allocations do not use RAM (aside from the page table that lists them as valid VM space).</p> <p>If you want to allocate physical RAM then you have to make each page (<code>sysconf(_SC_PAGESIZE)</code> gives you the system pagesize) dirty.</p> <p>In Linux you can see your VM mappings with all details in <code>/proc/self/smaps</code>. <code>Rss</code> is your resident set of that mapping (how much is resident in RAM), everything else that is dirty will have been swapped out. All non-dirty memory will be available for use, but won't exist until then.</p> <p>You can make all pages dirty with something like</p> <pre><code>size_t mem_length; char (*my_memory)[sysconf(_SC_PAGESIZE)] = mmap( NULL , mem_length , PROT_READ | PROT_WRITE , MAP_PRIVATE | MAP_ANONYMOUS , -1 , 0 ); int i; for (i = 0; i * sizeof(*my_memory) &lt; mem_length; i++) { my_memory[i][0] = 1; } </code></pre> <p>On some Implementations this can also be achieved by passing the <code>MAP_POPULATE</code> flag to <code>mmap</code>, but (depending on your system) it may just fail <code>mmap</code> with <code>ENOMEM</code> if you try to map more then you have RAM available.</p>
20,953,371
ASP.NET Identity, require 'strong' passwords
<p>Perhaps my googlin' skills are not so great this morning, but I can't seem to find how to set up different password requirements (rather than min/max length) with a new asp.net mvc5 project using individual user accounts.</p> <pre><code>[Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } </code></pre> <p>I don't know what password requirements I want to do just yet, but likely a combination of min length and requiring one lowercase, on capital letter, and a number.</p> <p>Any idea how I can accomplish this (via model attributes preferably)?</p>
20,953,845
4
6
null
2014-01-06 15:33:56.77 UTC
15
2016-12-18 14:52:56.42 UTC
null
null
null
null
1,118,218
null
1
40
c#|asp.net|asp.net-mvc|asp.net-identity
25,062
<p>You could use the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute%28v=vs.110%29.aspx" rel="nofollow noreferrer">RegularExpressionAttribute</a> together with the rules from this answer:</p> <p><a href="https://stackoverflow.com/questions/5142103/regex-for-password-strength#answer-5142164">Regex to validate password strength</a></p>
17,803,456
An alternative for the deprecated __malloc_hook functionality of glibc
<p>I am writing a memory profiler for C and for that am intercepting calls to the <code>malloc</code>, <code>realloc</code> and <code>free</code> functions via malloc_hooks. Unfortunately, these are deprecated because of their poor behavior in multi threaded environments. I could not find a document describing the alternative best practice solution to achieve the same thing, can someone enlighten me?</p> <p>I've read that a simple <code>#define malloc(s) malloc_hook(s)</code> would do the trick, but that does not work with the system setup I have in mind, because it is too intrusive to the original code base to be suitable for use in a profiling / tracing tool. Having to manually change the original application code is a killer for any decent profiler. Optimally, the solution I am looking for should be enabled or disabled just by linking to an optional shared library. For example, my current setup uses a function declared with <code>__attribute__ ((constructor))</code> to install the intercepting <code>malloc</code> hooks.</p> <p>Thanks</p>
17,850,402
3
2
null
2013-07-23 07:02:34.253 UTC
14
2019-02-28 06:45:55.15 UTC
2018-09-28 17:55:19.15 UTC
null
1,971,003
null
885,605
null
1
37
c|gcc|malloc|deprecated|glibc
16,861
<p>After trying some things, I finally managed to figure out how to do this.</p> <p>First of all, in <code>glibc</code>, <code>malloc</code> is defined as a weak symbol, which means that it can be overwritten by the application or a shared library. Hence, <code>LD_PRELOAD</code> is not necessarily needed. Instead, I implemented the following function in a shared library:</p> <pre><code>void* malloc (size_t size) { [ ... ] } </code></pre> <p>Which gets called by the application instead of <code>glibc</code>s <code>malloc</code>.</p> <p>Now, to be equivalent to the <code>__malloc_hook</code>s functionality, a couple of things are still missing.</p> <h2>1.) the caller address</h2> <p>In addition to the original parameters to <code>malloc</code>, <code>glibc</code>s <code>__malloc_hook</code>s also provide the address of the calling function, which is actually the return address of where <code>malloc</code> would return to. To achieve the same thing, we can use the <code>__builtin_return_address</code> function that is available in gcc. I have not looked into other compilers, because I am limited to gcc anyway, but if you happen to know how to do such a thing portably, please drop me a comment :)</p> <p>Our <code>malloc</code> function now looks like this:</p> <pre><code>void* malloc (size_t size) { void *caller = __builtin_return_address(0); [ ... ] } </code></pre> <h2>2.) accessing <code>glibc</code>s malloc from within your hook</h2> <p>As I am limited to glibc in my application, I chose to use <code>__libc_malloc</code> to access the original malloc implementation. Alternatively, <code>dlsym(RTLD_NEXT, "malloc")</code> can be used, but at the possible pitfall that this function uses <code>calloc</code> on its first call, possibly resulting in an infinite loop leading to a segfault.</p> <h2>complete malloc hook</h2> <p>My complete hooking function now looks like this:</p> <pre><code>extern void *__libc_malloc(size_t size); int malloc_hook_active = 0; void* malloc (size_t size) { void *caller = __builtin_return_address(0); if (malloc_hook_active) return my_malloc_hook(size, caller); return __libc_malloc(size); } </code></pre> <p>where <code>my_malloc_hook</code> looks like this:</p> <pre><code>void* my_malloc_hook (size_t size, void *caller) { void *result; // deactivate hooks for logging malloc_hook_active = 0; result = malloc(size); // do logging [ ... ] // reactivate hooks malloc_hook_active = 1; return result; } </code></pre> <p>Of course, the hooks for <code>calloc</code>, <code>realloc</code> and <code>free</code> work similarly.</p> <h2>dynamic and static linking</h2> <p>With these functions, dynamic linking works out of the box. Linking the .so file containing the malloc hook implementation will result of all calls to <code>malloc</code> from the application and also all library calls to be routed through my hook. Static linking is problematic though. I have not yet wrapped my head around it completely, but in static linking malloc is not a weak symbol, resulting in a multiple definition error at link time. </p> <p>If you need static linking for whatever reason, for example translating function addresses in 3rd party libraries to code lines via debug symbols, then you can link these 3rd party libs statically while still linking the malloc hooks dynamically, avoiding the multiple definition problem. I have not yet found a better workaround for this, if you know one,feel free to leave me a comment.</p> <p>Here is a short example:</p> <pre><code>gcc -o test test.c -lmalloc_hook_library -Wl,-Bstatic -l3rdparty -Wl,-Bdynamic </code></pre> <p><code>3rdparty</code> will be linked statically, while <code>malloc_hook_library</code> will be linked dynamically, resulting in the expected behaviour, and addresses of functions in <code>3rdparty</code> to be translatable via debug symbols in <code>test</code>. Pretty neat, huh?</p> <h2>Conlusion</h2> <p>the techniques above describe a non-deprecated, pretty much equivalent approach to <code>__malloc_hook</code>s, but with a couple of mean limitations:</p> <p><code>__builtin_caller_address</code> only works with <code>gcc</code></p> <p><code>__libc_malloc</code> only works with <code>glibc</code></p> <p><code>dlsym(RTLD_NEXT, [...])</code> is a GNU extension in <code>glibc</code></p> <p>the linker flags <code>-Wl,-Bstatic</code> and <code>-Wl,-Bdynamic</code> are specific to the GNU binutils.</p> <p>In other words, this solution is utterly non-portable and alternative solutions would have to be added if the hooks library were to be ported to a non-GNU operating system.</p>
46,989,310
commons-logging defines classes that conflict with classes now provided by Android after Android Studio Update
<p>I have updated Android Studio to version 3 and now seems unable to compile my project previously compiled without errors.</p> <p>The error message is the follow</p> <blockquote> <p>Error:Error: commons-logging defines classes that conflict with classes now provided by Android. Solutions include finding newer versions or alternative libraries that don't have the same problem (for example, for httpclient use HttpUrlConnection or okhttp instead), or repackaging the library using something like jarjar. [DuplicatePlatformClasses]</p> </blockquote> <p>The dependencies are</p> <pre><code>dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:27.0.0' compile 'com.android.support:design:27.0.0' compile 'com.google.api-client:google-api-client-android:1.23.0' exclude module: 'httpclient' compile 'com.google.http-client:google-http-client-gson:1.23.0' exclude module: 'httpclient' compile 'com.google.firebase:firebase-core:11.4.2' } </code></pre> <p>and error seems caused by </p> <pre><code>compile 'com.google.api-client:google-api-client-android:1.23.0' exclude module: 'httpclient' compile 'com.google.http-client:google-http-client-gson:1.23.0' exclude module: 'httpclient' </code></pre> <p>I already use <code>exclude module: 'httpclient'</code> So why It doesn't compile? Is this a bug of Android Studio 3 and\or included <code>com.android.tools.build:gradle:3.0.0</code> plugin or I'm missing something? With the previous version no problem to compile exactly the same project.</p>
46,995,816
12
4
null
2017-10-28 11:41:19.81 UTC
6
2022-03-23 16:06:59.267 UTC
2017-10-28 11:57:00.943 UTC
null
1,145,744
null
1,145,744
null
1
59
android|android-studio|android-gradle-plugin|android-studio-3.0|android-gradle-3.0
24,329
<p>Add to <code>build.gradle</code> located in app module </p> <pre><code>configurations { all { exclude module: 'httpclient' } } </code></pre>
22,947,181
Don't argparse read unicode from commandline?
<p>Running Python 2.7</p> <p>When executing:</p> <pre><code>$ python client.py get_emails -a "åäö" </code></pre> <p>I get:</p> <pre><code>usage: client.py get_emails [-h] [-a AREA] [-t {rfc2822,plain}] client.py get_emails: error: argument -a/--area: invalid unicode value: '\xc3\xa5\xc3\xa4\xc3\xb6' </code></pre> <p>This is my parser:</p> <pre><code>def _argparse(): desc = """ Simple CLI-client for... """ argparser = argparse.ArgumentParser(description=desc) subparsers = argparser.add_subparsers(dest='command') # create the parser for the "get_emails" command parser_get_emails = subparsers.add_parser('get_emails', help=u'Get email list') parser_get_emails.add_argument('-a', '--area', type=unicode, help='Limit to area') parser_get_emails.add_argument('-t', '--out_type', choices=['rfc2822', 'plain'], default='rfc2822', help='Type of output') args = argparser.parse_args() return args </code></pre> <p>Does this mean I can't use any unicode characters with python argparse module?</p>
22,947,334
2
2
null
2014-04-08 20:10:53.547 UTC
8
2014-04-15 13:33:22.283 UTC
null
null
null
null
934,836
null
1
13
python|unicode|argparse
9,365
<p>You can try</p> <pre><code>type=lambda s: unicode(s, 'utf8') </code></pre> <p>instead of</p> <pre><code>type=unicode </code></pre> <p>Without encoding argument unicode() defaults to ascii.</p>
23,431,595
Task.Yield - real usages?
<p>I've been reading about <code>Task.Yield</code> , And as a Javascript developer I can tell that's it's job is <strike><em>exactly</em></strike> the same as <code>setTimeout(function (){...},0);</code> in terms of letting the main single thread deal with other stuff aka :</p> <blockquote> <p>"don't take all the power , release from time time - so others would have some too..."</p> </blockquote> <p>In js it's working particular in long loops. ( <em>don't make the browser freeze...</em>)</p> <p>But I saw this example <a href="http://books.google.co.il/books?id=qgq8T4X3erIC&amp;pg=PA574&amp;lpg=PA574&amp;dq=%22the%20task.yield%20method%20creates%22&amp;source=bl&amp;ots=94eP29Nmls&amp;sig=XxEvfX6PVmXhdOdOJC7dlJUGf0I&amp;hl=en&amp;sa=X&amp;ei=t7ZjU5WTJoaxO-f4gXg&amp;ved=0CCYQ6AEwAA#v=onepage&amp;q=%22the%20task.yield%20method%20creates%22&amp;f=false" rel="noreferrer">here</a> : </p> <pre><code>public static async Task &lt; int &gt; FindSeriesSum(int i1) { int sum = 0; for (int i = 0; i &lt; i1; i++) { sum += i; if (i % 1000 == 0) ( after a bulk , release power to main thread) await Task.Yield(); } return sum; } </code></pre> <p>As a JS programmer I can understand what they did here.</p> <p>BUT as a C# programmer I ask myself : why not open a task for it ?</p> <pre><code> public static async Task &lt; int &gt; FindSeriesSum(int i1) { //do something.... return await MyLongCalculationTask(); //do something } </code></pre> <p><strong>Question</strong></p> <p>With Js I can't open a Task (<em><sup>yes i know i can actually with web workers</sup></em>) . But with c# <strong>I can</strong>.</p> <p><strong>If So</strong> -- why even bother with releasing from time to time while I can release it at all ?</p> <h1>Edit</h1> <p><strong>Adding references :</strong> </p> <p>From <a href="http://books.google.co.il/books?id=qgq8T4X3erIC&amp;pg=PA574&amp;lpg=PA574&amp;dq=%22the%20task.yield%20method%20creates%22&amp;source=bl&amp;ots=94eP29Nmls&amp;sig=XxEvfX6PVmXhdOdOJC7dlJUGf0I&amp;hl=en&amp;sa=X&amp;ei=t7ZjU5WTJoaxO-f4gXg&amp;ved=0CCYQ6AEwAA#v=onepage&amp;q=%22the%20task.yield%20method%20creates%22&amp;f=false" rel="noreferrer">here</a> : <img src="https://i.stack.imgur.com/mDeX7.jpg" alt="enter image description here"></p> <p>From <a href="http://books.google.co.il/books?id=I-dHxFjfbi8C&amp;pg=PA65&amp;lpg=PA65&amp;dq=%22task.yield%28%29%22%20%20books&amp;source=bl&amp;ots=QwX60qDOeN&amp;sig=6YlwxL1aX_OuYzpU8ENoYUM8TR0&amp;hl=en&amp;sa=X&amp;ei=O5lkU5zKBumM7Qbqx4BY&amp;ved=0CDIQ6AEwAQ#v=onepage&amp;q=%22task.yield%28%29%22%20%20books&amp;f=false" rel="noreferrer">here</a> (another ebook): </p> <p><img src="https://i.stack.imgur.com/KS3Xq.jpg" alt="enter image description here"></p>
23,441,833
6
3
null
2014-05-02 15:22:20.563 UTC
14
2022-09-07 21:32:27.167 UTC
2014-05-04 04:02:55.993 UTC
user149341
null
null
859,154
null
1
46
c#|multithreading|async-await|.net-4.5|c#-5.0
27,414
<p>When you see:</p> <pre><code>await Task.Yield(); </code></pre> <p>you can think about it this way:</p> <pre><code>await Task.Factory.StartNew( () =&gt; {}, CancellationToken.None, TaskCreationOptions.None, SynchronizationContext.Current != null? TaskScheduler.FromCurrentSynchronizationContext(): TaskScheduler.Current); </code></pre> <p>All this does is makes sure the continuation will happen asynchronously in the future. By <em>asynchronously</em> I mean that the execution control will return to the caller of the <code>async</code> method, and the continuation callback will <em>not</em> happen on the same stack frame.</p> <p>When exactly and on what thread it will happen completely depends on the caller thread's synchronization context.</p> <p><strong>For a UI thread</strong>, the continuation will happen upon some future iteration of the message loop, run by <code>Application.Run</code> (<a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.application.run(v=vs.110).aspx" rel="noreferrer">WinForms</a>) or <code>Dispatcher.Run</code> (<a href="https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.run(v=vs.110).aspx" rel="noreferrer">WPF</a>). Internally, it comes down to the Win32 <code>PostMessage</code> API, which post a custom message to the UI thread's message queue. The <code>await</code> continuation callback will be called when this message gets pumped and processed. You're completely out of control about when exactly this is going to happen.</p> <p>Besides, Windows has its own priorities for pumping messages: <a href="https://web.archive.org/web/20130627005845/http://support.microsoft.com:80/kb/96006" rel="noreferrer">INFO: Window Message Priorities</a>. The most relevant part:</p> <blockquote> <p>Under this scheme, prioritization can be considered tri-level. All posted messages are higher priority than user input messages because they reside in different queues. And all user input messages are higher priority than WM_PAINT and WM_TIMER messages.</p> </blockquote> <p>So, if you use <code>await Task.Yield()</code> to yield to the message loop in attempt to keep the UI responsive, you are actually at risk of obstructing the UI thread's message loop. Some pending user input messages, as well as <code>WM_PAINT</code> and <code>WM_TIMER</code>, have a lower priority than the posted continuation message. Thus, if you do <code>await Task.Yield()</code> on a tight loop, you still may block the UI.</p> <p>This is how it is different from the JavaScript's <code>setTimer</code> analogy you mentioned in the question. A <code>setTimer</code> callback will be called <em>after</em> all user input message have been processed by the browser's message pump.</p> <p>So, <code>await Task.Yield()</code> is not good for doing background work on the UI thread. In fact, you very rarely need to run a background process on the UI thread, but sometimes you do, e.g. editor syntax highlighting, spell checking etc. In this case, use the framework's idle infrastructure.</p> <p>E.g., with WPF you could do <code>await Dispatcher.Yield(DispatcherPriority.ApplicationIdle)</code>:</p> <pre><code>async Task DoUIThreadWorkAsync(CancellationToken token) { var i = 0; while (true) { token.ThrowIfCancellationRequested(); await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); // do the UI-related work item this.TextBlock.Text = &quot;iteration &quot; + i++; } } </code></pre> <p>For WinForms, you could use <code>Application.Idle</code> event:</p> <pre><code>// await IdleYield(); public static Task IdleYield() { var idleTcs = new TaskCompletionSource&lt;bool&gt;(); // subscribe to Application.Idle EventHandler handler = null; handler = (s, e) =&gt; { Application.Idle -= handler; idleTcs.SetResult(true); }; Application.Idle += handler; return idleTcs.Task; } </code></pre> <p><a href="https://web.archive.org/web/20151029200959/http://blogs.msdn.com/b/windowsappdev/archive/2012/03/20/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime.aspx" rel="noreferrer">It is recommended</a> that you do not exceed 50ms for each iteration of such background operation running on the UI thread.</p> <p><strong>For a non-UI thread</strong> with no synchronization context, <code>await Task.Yield()</code> just switches the continuation to a random pool thread. There is no guarantee it is going to be a <em>different</em> thread from the current thread, it's only guaranteed to be an <em>asynchronous</em> continuation. If <code>ThreadPool</code> is starving, it may schedule the continuation onto the same thread.</p> <p><strong>In ASP.NET</strong>, doing <code>await Task.Yield()</code> doesn't make sense at all, except for the workaround mentioned in <a href="https://stackoverflow.com/a/23436765/1768303">@StephenCleary's answer</a>. Otherwise, it will only hurt the web app performance with a redundant thread switch.</p> <p><strong>So, is <code>await Task.Yield()</code> useful?</strong> IMO, not much. It can be used as a shortcut to run the continuation via <code>SynchronizationContext.Post</code> or <code>ThreadPool.QueueUserWorkItem</code>, if you really need to impose asynchrony upon a part of your method.</p> <p><strong>Regarding the books you quoted</strong>, in my opinion those approaches to using <code>Task.Yield</code> are wrong. I explained why they're wrong for a UI thread, above. For a non-UI pool thread, there's simply no <em>&quot;other tasks in the thread to execute&quot;</em>, unless you running a custom task pump like <a href="https://web.archive.org/web/20151210031057/http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx" rel="noreferrer">Stephen Toub's <code>AsyncPump</code></a>.</p> <p><strong>Updated to answer the comment:</strong></p> <blockquote> <p>... how can it be asynchronouse operation and stay in the same thread ?..</p> </blockquote> <p>As a simple example: WinForms app:</p> <pre><code>async void Form_Load(object s, object e) { await Task.Yield(); MessageBox.Show(&quot;Async message!&quot;); } </code></pre> <p><code>Form_Load</code> will return to the caller (the WinFroms framework code which has fired <code>Load</code> event), and then the message box will be shown asynchronously, upon some future iteration of the message loop run by <code>Application.Run()</code>. The continuation callback is queued with <code>WinFormsSynchronizationContext.Post</code>, which internally posts a private Windows message to the UI thread's message loop. The callback will be executed when this message gets pumped, still on the same thread.</p> <p>In a console app, you can run a similar serializing loop with <code>AsyncPump</code> mentioned above.</p>
1,679,974
Converting an FFT to a spectogram
<p>I have an audio file and I am iterating through the file and taking 512 samples at each step and then passing them through an FFT.</p> <p>I have the data out as a block 514 floats long (Using IPP's ippsFFTFwd_RToCCS_32f_I) with real and imaginary components interleaved.</p> <p>My problem is what do I do with these complex numbers once i have them? At the moment I'm doing for each value</p> <pre><code>const float realValue = buffer[(y * 2) + 0]; const float imagValue = buffer[(y * 2) + 1]; const float value = sqrt( (realValue * realValue) + (imagValue * imagValue) ); </code></pre> <p>This gives something slightly usable but I'd rather some way of getting the values out in the range 0 to 1. The problem with he above is that the peaks end up coming back as around 9 or more. This means things get viciously saturated and then there are other parts of the spectrogram that barely shows up despite the fact that they appear to be quite strong when I run the audio through audition's spectrogram. I fully admit I'm not 100% sure what the data returned by the FFT is (Other than that it represents the frequency values of the 512 sample long block I'm passing in). Especially my understanding is lacking on what exactly the compex number represents. </p> <p>Any advice and help would be much appreciated!</p> <p>Edit: Just to clarify. My big problem is that the FFT values returned are meaningless without some idea of what the scale is. Can someone point me towards working out that scale?</p> <p>Edit2: I get really nice looking results by doing the following:</p> <pre><code>size_t count2 = 0; size_t max2 = kFFTSize + 2; while( count2 &lt; max2 ) { const float realValue = buffer[(count2) + 0]; const float imagValue = buffer[(count2) + 1]; const float value = (log10f( sqrtf( (realValue * realValue) + (imagValue * imagValue) ) * rcpVerticalZoom ) + 1.0f) * 0.5f; buffer[count2 &gt;&gt; 1] = value; count2 += 2; } </code></pre> <p>To my eye this even looks better than most other spectrogram implementations I have looked at.</p> <p>Is there anything MAJORLY wrong with what I'm doing?</p>
1,680,905
5
2
null
2009-11-05 11:33:37.497 UTC
9
2012-05-19 07:36:06.037 UTC
2012-05-07 07:47:46.22 UTC
null
20,984
null
131,140
null
1
12
c++|fft|spectrogram|intel-ipp
11,087
<p>The usual thing to do to get all of an FFT visible is to take the logarithm of the magnitude. </p> <p>So, the position of the output buffer tells you what frequency was detected. The magnitude (L2 norm) of the complex number tells you how strong the detected frequency was, and the phase (arctangent) gives you information that is a lot more important in image space than audio space. Because the FFT is discrete, the frequencies run from 0 to the nyquist frequency. In images, the first term (DC) is usually the largest, and so a good candidate for use in normalization if that is your aim. I don't know if that is also true for audio (I doubt it)</p>
1,426,239
Can ML functors be fully encoded in .NET (C#/F#)?
<p>Can ML functors be practically expressed with .NET interfaces and generics? Is there an advanced ML functor use example that defies such encodings?</p> <p><strong>Answers summary</strong>:</p> <p>In the general case, the answer is NO. ML modules provide features (such as specification sharing via signatures [<a href="https://stackoverflow.com/questions/1426239/can-ml-functors-be-fully-encoded-in-net-c-f/1448352#1448352">1</a>]) that do not directly map to .NET concepts. </p> <p>However, for certain use cases the ML idioms can be translated. These cases include not only the basic <code>Set</code> functor [<a href="http://web.archive.org/web/20111112224618/http://blog.matthewdoig.com/?p=152" rel="nofollow noreferrer">2</a>], but also the functorial encoding of monads [<a href="http://gist.github.com/192353" rel="nofollow noreferrer">3</a>], and even more advanced uses of Haskell, such as finally tagless interpreters [<a href="http://higherlogics.blogspot.com/2007/12/ml-modules-in-c.html" rel="nofollow noreferrer">4</a>, <a href="http://higherlogics.blogspot.com/2009/06/mobile-code-in-c-via-finally-tagless.html" rel="nofollow noreferrer">5</a>].</p> <p>Practical encodings require compromises such as semi-safe downcasts. Your mileage will wary.</p> <p>Blogs and code: </p> <ol> <li><a href="http://web.archive.org/web/20111112224618/http://blog.matthewdoig.com/?p=152" rel="nofollow noreferrer">blog.matthewdoig.com</a></li> <li><a href="http://higherlogics.blogspot.com/2007/12/ml-modules-in-c.html" rel="nofollow noreferrer">higherlogics.blogspot.com</a></li> <li><a href="http://gist.github.com/192353" rel="nofollow noreferrer">monad functor in F#</a></li> </ol>
1,448,352
5
0
2009-09-15 21:52:45.377 UTC
2009-09-15 09:57:00.06 UTC
12
2013-05-21 01:12:13.643 UTC
2017-05-23 10:29:36.727 UTC
null
-1
null
386,685
null
1
18
.net|f#|functor
3,831
<p>One of the key features of ML modules is sharing specifications. There's no mechanism in .NET that would be able to emulate them - the required machinery is just too different.</p> <p>You can try to do it by turning the shared types into parameters, but this can't faithfully emulate the ability to define a signature, and then later apply sharing to it, perhaps in multiple different ways.</p> <p>In my opinion, .NET would benefit from something that did have this kind of machinery - it would then come closer to truly supporting the diversity of modern languages. Hopefully including more recent advances in modules systems like those in MixML, which in my opinion is the future of module systems. <a href="http://www.mpi-sws.org/~rossberg/mixml/" rel="noreferrer">http://www.mpi-sws.org/~rossberg/mixml/</a> </p>
1,749,314
Is Solr available for .Net?
<p>I want to learn Solr. May I know some good tutorial/links for it?</p> <p>Also, is Solr available for .NET?</p>
1,749,759
5
2
null
2009-11-17 14:37:29.2 UTC
12
2017-06-05 17:30:44.06 UTC
2012-12-26 16:05:44.537 UTC
null
1,250,033
null
55,717
null
1
35
.net|lucene|solr
26,358
<p>If you mean running the Solr server on .Net instead of Java, then no, there is no port. I've been trying to run it with <a href="http://www.ikvm.net/" rel="noreferrer">IKVM</a> <a href="http://code.google.com/p/mausch/source/browse/trunk/SolrIKVM/" rel="noreferrer">here</a> but it's low-priority to me so I can't put much time on it. It'd be great if someone can help out with this.</p> <p>If you mean using/connecting to Solr from a .Net application, then yes, you can use <a href="https://github.com/mausch/SolrNet" rel="noreferrer">SolrNet</a> or <a href="http://solrsharp.codeplex.com/" rel="noreferrer">SolrSharp</a> for that.</p> <p>I <a href="http://bugsquash.blogspot.com/2009/10/untangling-mess-solr-solrnet-nhibernate.html" rel="noreferrer">blogged about this</a> not long ago.</p> <p>UPDATE: I made <a href="http://bugsquash.blogspot.com/2011/02/running-solr-on-net.html" rel="noreferrer">significant progress with Solr + IKVM</a>.</p>
1,505,754
C# Could not load file or assembly 'Microsoft.SharePoint.Library'
<p>I am developing on a 64bit version of Windows 7, running MOSS (SharePoint), this is my dev machine. </p> <p>Now when I deploy my web service app to a test server Windows 2003 32bit (no Sharepoint installed) I get this error. </p> <p>Could not load file or assembly 'Microsoft.SharePoint.Library, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified</p> <p>The DLL has clearly been copied to the bin directory (Microsoft.Sharepoint.dll). </p> <p>Any ideas?</p>
1,505,965
6
5
null
2009-10-01 18:47:09.483 UTC
2
2011-11-24 16:48:09.997 UTC
null
null
null
null
41,543
null
1
5
c#|sharepoint
40,659
<p>If you are using sharepoint dll's it will only work on a machine with sharepoint installed.</p> <p>Even if you managed to hack it and get it to work, you would probably be breaking a license agreement.</p>
2,129,593
UITextField, automatically move to next after 1 character
<p>Scenario: I have 4 UITextFields that only accept 1 character. Easy.</p> <p>Problem: After I enter the 1 character, I want the next TextField to become active automatically without having to press next (i.e. I'm using the UIKeyboardTypeNumberPad, and theres no NEXT button. (I KNOW I can actually create a next button programmatically, but I dont want to go that far, just need the next field to become active automatically after the 1 character is entered.</p> <pre><code>#define MAX_LENGTH 1 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; for (int i = 0; i &lt; [string length]; i++) { unichar c = [string characterAtIndex:i]; if (![myCharSet characterIsMember:c]) { return NO; } } NSUInteger newLength = [textField.text length] + [string length] - range.length; return (newLength &gt; 1) ? NO : YES; } -(BOOL)textFieldShouldReturn:(UITextField *)textField { if (textField == pc1) { [pc2 becomeFirstResponder]; }else if (textField == pc2) { [pc3 becomeFirstResponder]; }else if (textField == pc3) { [pc4 becomeFirstResponder]; }else if (textField == pc4) { [textField resignFirstResponder]; } return YES; } </code></pre>
3,410,922
6
0
null
2010-01-25 00:45:24.52 UTC
12
2020-02-24 23:36:30.35 UTC
2014-02-12 00:03:23.673 UTC
null
171,206
null
171,206
null
1
15
delegates|keyboard|uitextfield
15,861
<p>I arrived at a solution by modifying some code I found here: <a href="http://www.thepensiveprogrammer.com/2010/03/customizing-uitextfield-formatting-for.html" rel="noreferrer">http://www.thepensiveprogrammer.com/2010/03/customizing-uitextfield-formatting-for.html</a></p> <p>First set the your view controller to be the delegate of the textfields.</p> <p>Then do something like this:</p> <pre><code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { BOOL shouldProcess = NO; //default to reject BOOL shouldMoveToNextField = NO; //default to remaining on the current field int insertStringLength = [string length]; if(insertStringLength == 0){ //backspace shouldProcess = YES; //Process if the backspace character was pressed } else { if([[textField text] length] == 0) { shouldProcess = YES; //Process if there is only 1 character right now } } //here we deal with the UITextField on our own if(shouldProcess){ //grab a mutable copy of what's currently in the UITextField NSMutableString* mstring = [[textField text] mutableCopy]; if([mstring length] == 0){ //nothing in the field yet so append the replacement string [mstring appendString:string]; shouldMoveToNextField = YES; } else{ //adding a char or deleting? if(insertStringLength &gt; 0){ [mstring insertString:string atIndex:range.location]; } else { //delete case - the length of replacement string is zero for a delete [mstring deleteCharactersInRange:range]; } } //set the text now [textField setText:mstring]; [mstring release]; if (shouldMoveToNextField) { // //MOVE TO NEXT INPUT FIELD HERE // } } //always return no since we are manually changing the text field return NO; } </code></pre>
1,673,347
LINQ: Determine if two sequences contains exactly the same elements
<p>I need to determine whether or not two sets contains exactly the same elements. The ordering does not matter.</p> <p>For instance, these two arrays should be considered equal:</p> <pre><code>IEnumerable&lt;int&gt; data = new []{3, 5, 6, 9}; IEnumerable&lt;int&gt; otherData = new []{6, 5, 9, 3} </code></pre> <p>One set cannot contain any elements, that are not in the other.</p> <p>Can this be done using the built-in query operators? And what would be the most efficient way to implement it, considering that the number of elements could range from a few to hundreds?</p>
1,673,388
7
3
null
2009-11-04 11:57:29.173 UTC
15
2018-05-19 11:09:09.54 UTC
2018-05-19 11:07:46.383 UTC
null
63,550
null
13,627
null
1
72
c#|.net|linq
37,863
<p>If you want to treat the arrays as "sets" and ignore order and duplicate items, you can use <a href="http://msdn.microsoft.com/en-us/library/bb346516.aspx" rel="noreferrer"><code>HashSet&lt;T&gt;.SetEquals</code> method</a>:</p> <pre><code>var isEqual = new HashSet&lt;int&gt;(first).SetEquals(second); </code></pre> <p>Otherwise, your best bet is probably sorting both sequences in the same way and using <code>SequenceEqual</code> to compare them.</p>
1,497,777
Freemarker iterating over hashmap keys
<p>Freemarker has two collection datatypes, lists and hashmaps Is there a way to iterate over hashmap keys just as we do with lists?</p> <p>So if I have a var with data lets say:</p> <pre><code>user : { name : "user" email : "[email protected]" homepage : "http://nosuchpage.org" } </code></pre> <p>I would like to print all the user's properties with their value. This is invalid, but the goal is clear:</p> <pre><code>&lt;#list user.props() as prop&gt; ${prop} = ${user.get(prop)} &lt;/#list&gt; </code></pre>
1,497,802
7
0
null
2009-09-30 12:22:02.353 UTC
14
2018-07-23 16:09:56.423 UTC
2012-03-13 15:52:18.753 UTC
null
8,418
null
165,697
null
1
93
java|freemarker
122,365
<p><strong>Edit:</strong> Don't use this solution with FreeMarker 2.3.25 and up, especially not <code>.get(prop)</code>. See other answers.</p> <p>You use the built-in <a href="http://freemarker.sourceforge.net/docs/ref_builtins_hash.html" rel="noreferrer">keys</a> function, e.g. this should work:</p> <pre><code>&lt;#list user?keys as prop&gt; ${prop} = ${user.get(prop)} &lt;/#list&gt; </code></pre>
1,680,528
How to avoid having class data shared among instances?
<p>What I want is this behavior:</p> <pre><code>class a: list = [] x = a() y = a() x.list.append(1) y.list.append(2) x.list.append(3) y.list.append(4) print(x.list) # prints [1, 3] print(y.list) # prints [2, 4] </code></pre> <p>Of course, what really happens when I print is:</p> <pre><code>print(x.list) # prints [1, 2, 3, 4] print(y.list) # prints [1, 2, 3, 4] </code></pre> <p>Clearly they are sharing the data in class <code>a</code>. How do I get separate instances to achieve the behavior I desire?</p>
1,680,555
7
1
null
2009-11-05 13:19:55.693 UTC
38
2019-02-15 11:34:35.117 UTC
2018-03-31 15:22:26.607 UTC
null
2,301,450
null
150,564
null
1
175
python|class
34,172
<p>You want this:</p> <pre><code>class a: def __init__(self): self.list = [] </code></pre> <p>Declaring the variables inside the class declaration makes them "class" members and not instance members. Declaring them inside the <code>__init__</code> method makes sure that a new instance of the members is created alongside every new instance of the object, which is the behavior you're looking for.</p>
1,789,543
How to find number of bytes taken by python variable
<p>Is there anyway i can know how much bytes taken by particular variable in python. E.g; lets say i have</p> <pre><code>int = 12 print (type(int)) </code></pre> <p>it will print</p> <pre><code>&lt;class 'int'&gt; </code></pre> <p>But i wanted to know how many bytes it has taken on memory? is it possible?</p>
1,789,567
9
0
null
2009-11-24 11:41:47.077 UTC
5
2021-12-07 20:51:20.56 UTC
2009-11-24 18:24:38.747 UTC
null
10,661
null
146,603
null
1
28
python
50,641
<p>You can find the functionality you are looking for <a href="http://docs.python.org/library/sys.html#sys.getsizeof" rel="noreferrer">here</a> (in <code>sys.getsizeof</code> - Python 2.6 and up).</p> <p>Also: don't shadow the <code>int</code> builtin!</p> <pre><code>import sys myint = 12 print(sys.getsizeof(myint)) </code></pre>
1,525,444
How to connect SQLite with Java?
<p>I am using one simple code to access the SQLite database from Java application . My code is</p> <pre><code> import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ConnectSQLite { public static void main(String[] args) { Connection connection = null; ResultSet resultSet = null; Statement statement = null; try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db"); statement = connection.createStatement(); resultSet = statement .executeQuery("SELECT EMPNAME FROM EMPLOYEEDETAILS"); while (resultSet.next()) { System.out.println("EMPLOYEE NAME:" + resultSet.getString("EMPNAME")); } } catch (Exception e) { e.printStackTrace(); } finally { try { resultSet.close(); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } } } </code></pre> <p>But this code gives one exception like</p> <pre><code>java.lang.ClassNotFoundException: org.sqlite.JDBC </code></pre> <p>How can I slove this,please help me.</p>
1,525,453
9
1
null
2009-10-06 13:02:55.467 UTC
26
2017-03-31 06:28:10.677 UTC
2012-04-15 06:28:02.527 UTC
null
632,447
null
131,062
null
1
51
java|sqlite|jdbc|classpath
199,900
<p>You need to have a SQLite JDBC driver in your classpath.</p> <p>Taro L. Saito (xerial) forked the Zentus project and now maintains it under the name <a href="https://github.com/xerial/sqlite-jdbc" rel="noreferrer">sqlite-jdbc</a>. It bundles the native drivers for major platforms so you don't need to configure them separately.</p>
1,952,153
What is the best way to find all combinations of items in an array?
<p>What is the best way to find all combinations of items in an array in c#?</p>
1,952,242
10
4
null
2009-12-23 11:11:49.537 UTC
34
2020-04-30 21:17:12.73 UTC
2013-04-18 17:29:17.21 UTC
null
815,724
null
13,911
null
1
54
c#|algorithm
75,523
<p>It is O(n!)</p> <pre><code>static List&lt;List&lt;int&gt;&gt; comb; static bool[] used; static void GetCombinationSample() { int[] arr = { 10, 50, 3, 1, 2 }; used = new bool[arr.Length]; used.Fill(false); comb = new List&lt;List&lt;int&gt;&gt;(); List&lt;int&gt; c = new List&lt;int&gt;(); GetComb(arr, 0, c); foreach (var item in comb) { foreach (var x in item) { Console.Write(x + ","); } Console.WriteLine(""); } } static void GetComb(int[] arr, int colindex, List&lt;int&gt; c) { if (colindex &gt;= arr.Length) { comb.Add(new List&lt;int&gt;(c)); return; } for (int i = 0; i &lt; arr.Length; i++) { if (!used[i]) { used[i] = true; c.Add(arr[i]); GetComb(arr, colindex + 1, c); c.RemoveAt(c.Count - 1); used[i] = false; } } } </code></pre>
1,670,970
How to cherry-pick multiple commits
<p>I have two branches. Commit <code>a</code> is the head of one, while the other has <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> on top of <code>a</code>. I want to move <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> to first branch without commit <code>b</code>. Using cherry pick it is easy: checkout first branch cherry-pick one by one <code>c</code> to <code>f</code> and rebase second branch onto first. But is there any way to cherry-pick all <code>c</code>-<code>f</code> in one command?</p> <p>Here is a visual description of the scenario (thanks <a href="/users/356895/JJD">JJD</a>):</p> <p><img src="https://i.stack.imgur.com/7k9Ev.png" alt="enter image description here"></p>
3,933,416
17
1
null
2009-11-04 00:07:03.587 UTC
391
2022-08-04 15:08:17.153 UTC
2012-09-28 19:02:45.27 UTC
null
356,895
null
96,823
null
1
1,317
git|git-rebase|cherry-pick
808,961
<p>Git 1.7.2 introduced the ability to cherry pick a range of commits. From the <a href="https://raw.github.com/git/git/master/Documentation/RelNotes/1.7.2.txt" rel="noreferrer">release notes</a>:</p> <blockquote> <p><code>git cherry-pick</code> learned to pick a range of commits (e.g. <code>cherry-pick A..B</code> and <code>cherry-pick --stdin</code>), so did <code>git revert</code>; these do not support the nicer sequencing control <code>rebase [-i]</code> has, though.</p> </blockquote> <p>To cherry-pick all the commits from commit <code>A</code> to commit <code>B</code> (where <code>A</code> is older than <code>B</code>), run:</p> <pre><code>git cherry-pick A^..B </code></pre> <p>If you want to <em>ignore</em> A itself, run:</p> <pre><code>git cherry-pick A..B </code></pre> <p>Notes from comments:</p> <ul> <li><code>A</code> should be older than <code>B</code>, or <code>A</code> should be from another branch.</li> <li>On Windows, it should be <code>A^^..B</code> as the caret needs to be escaped, or it should be <code>&quot;A^..B&quot;</code> (double quotes).</li> <li>In <code>zsh</code> shell, it should be <code>'A^..B'</code> (single quotes) as the caret is a special character.</li> <li>For an exposition, see <a href="https://stackoverflow.com/a/69472178/4561887">the answer by Gabriel Staples</a>.</li> </ul> <p><em>(Credits to damian, J. B. Rainsberger, sschaef, Neptilo, Pete and TMin in the comments.)</em></p>