input
stringlengths
51
42.3k
output
stringlengths
18
55k
Youtube API: Revert video thumbnail to the default thumbnail <p>I am trying to revert the thumbnail of youtube videos, via the v3 API, to the thumbnail that is automatically generated by YouTube from a screenshot of the video when it's uploaded.</p> <p>So, basically, I wanna delete the custom thumbnail I uploaded.</p> <p>The documentation, as far as I can tell, only shows how to set a new thumbnail by uploading an Image, but has nothing on how to delete/revert thumbnails.</p> <p><a href="https://developers.google.com/youtube/v3/docs/thumbnails/set" rel="nofollow">https://developers.google.com/youtube/v3/docs/thumbnails/set</a></p> <p>Any pointers appreciated.</p>
<p>The only thing I can think of is that you grab one of the three automatically generated thumbnails:</p> <pre><code>http://img.youtube.com/vi/{video_id}/1.jpg http://img.youtube.com/vi/{video_id}/2.jpg http://img.youtube.com/vi/{video_id}/3.jpg </code></pre> <p>You could then upload either of them via the API. Unfortunately, they are in very poor quality. Maybe there is a way to get a high-quality version of them?</p>
multi-level sort and displaying details <p>The task I have at hand is "Write a SQL Statement to find the number of sessions scheduled for each screen in every branch. Display the screen details (id of branch and screen) and their corresponding number of sessions. Perform a multi-level sort with branchid and the number of sessions."</p> <pre><code>SELECT SCREENID, BRANCHID FROM SCREEN NATURAL JOIN SESSIONS; </code></pre> <p><strong>Table SCREEN:</strong></p> <pre><code>--------------------------------------- ScreenID | BranchID | Screencapacity --------------------------------------- S1 | B1 | 120 S1 | B2 | 185 S2 | B1 | 230 S2 | B4 | 165 S2 | B3 | 185 S1 | B3 | 210 S2 | B4 | 170 S2 | B1 | 150 S3 | B2 | 135 S1 | B4 | 128 --------------------------------------- </code></pre> <p><strong>Table SESSION:</strong></p> <pre><code>+-----------+----------+----------+---------+-------------+--------------+ | SESSIONID | BRANCHID | SCREENID | MOVIEID | SESSIONDATE | SESSIONPRICE | +-----------+----------+----------+---------+-------------+--------------+ | SS01 | B1 | S1 | M1 | 03-MAY-16 | 12.5 | | SS03 | B1 | S2 | M2 | 03-MAY-16 | 12.67 | | SS09 | B2 | S3 | M4 | 13-MAY-16 | 17.9 | | SS04 | B4 | S2 | M4 | 13-MAY-16 | 14.56 | | SS07 | B4 | S2 | M3 | 14-MAY-16 | 21.78 | | SS05 | B3 | S2 | M5 | 23-MAY-16 | 14.56 | | SS06 | B3 | S1 | M5 | 03-JUN-16 | 16.32 | | SS02 | B2 | S1 | M2 | 04-JUN-16 | 19.45 | | SS10 | B4 | S1 | M3 | 06-JUN-16 | 16.37 | | SS08 | B1 | S2 | M2 | 06-JUN-16 | 16.82 | +-----------+----------+----------+---------+-------------+--------------+ </code></pre> <p>I am completely lost and am not sure where to begin on this problem</p>
<pre><code>select screenid, branchid, count(1) as no_of_sessions from screen A join session B on B.screenid = A.screenid and B.branchid = A.branchid group by screenid, branchid order by branchid, no_of_sessions ; </code></pre> <p>First, you join the two tables on <code>screenid</code> and <code>branchid</code>. Then, you aggregate (<code>group by</code>) the joined data to groups by <code>screenid</code> and <code>branchid</code> and simply count the number of rows in each group (<code>count(1)</code>). Then, you order the results by <code>branchid</code> and the number of sessions in the group (<code>no_of_sessions</code>).</p> <p>Enjoy!</p>
d3 4.0 - import statement gives __moduleExports wrapper <p>I'm having trouble with an import statement in D3 4.0 and Ionic2/Angular2 project.</p> <p>I believe I am using the correct import statement, and everything compiles. </p> <pre><code>import * as d3Request from 'd3-request'; export class HomePage { constructor() { d3Request.xml('assets/mysvg.svg') .mimeType("image/svg+xml") .get(function(error, xml) { if (error) throw error; document.body.appendChild(xml.documentElement); }); } } </code></pre> <p>Gets compiled to:</p> <pre><code>var d3Request$1 = unwrapExports(d3Request); var d3Request$2 = Object.freeze({ default: d3Request$1, __moduleExports: d3Request }); ... d3Request$2.xml('assets/mysvg.svg') .mimeType("image/svg+xml") .get(function (error, xml) { if (error) throw error; document.body.appendChild(xml.documentElement); }); </code></pre> <p>However, at runtime the <code>xml</code> function does not exist on <code>d3Request$2.xml</code>. It only exists on <code>d3Request$2.__moduleExports.xml</code>, but the code does not compile to that. What gives?</p> <p>I also tried <code>import d3Request from 'd3-request'</code> which also compiles but still doesnt work. Results in: </p> <pre><code>var d3Request$1 = unwrapExports(d3Request); ... d3Request$1.xml('assets/emojis/laughing.svg') .mimeType("image/svg+xml")... </code></pre> <p>However, this still doesn't work because <code>d3Request$1</code> end up being undefined. <code>d3Request.xml</code> exists but the code doesnt compile to that, it compiles to <code>d3Request$1.xml</code>!</p>
<p>The <code>unwrapExports(...)</code> and <code>__moduleExports</code> indicate that you're importing a CommonJS file (and transforming it with <a href="https://github.com/rollup/rollup-plugin-commonjs" rel="nofollow">rollup-plugin-commonjs</a>), not the ES module version. It's odd that it doesn't work, but no matter – you can bypass the transformation altogether by importing the correct file.</p> <p>Without seeing your Rollup config file it's impossible to be certain, but I would guess that you're using <a href="https://github.com/rollup/rollup-plugin-node-resolve" rel="nofollow">rollup-plugin-node-resolve</a>? If so, the solution is to ensure that the <code>jsnext: true</code> option is set, so that Rollup can find <a href="https://unpkg.com/d3-request@1.0.2/index.js" rel="nofollow">this file</a> rather than <a href="https://unpkg.com/d3-request@1.0.2" rel="nofollow">this file</a>. </p>
UPDATE query is not working in DBI <pre><code>use DBI; my $jobID = 1; $dbh = DBI-&gt;connect("dbi:mysql:$database:$db_server", $user, $password) or die "Connection ERROR!"; $dbh-&gt;do('USE MultiRunScheduler'); $dbh-&gt;do('UPDATE Scheduler SET RequestStatus="CANCELED" WHERE ID="$jobID";') print "Scheduled Jobs deleted"; </code></pre> <p>I'm trying to change the <code>RequestStatus</code> field of a database based on <code>ID</code> but it's not working through the <code>UPDATE</code> statement. It prints out <code>Scheduled Jobs deleted</code> and the entire program runs successfully but it doesn't update the database <code>RequestStatus</code> field. If I remove <code>ID="$jobID"</code> and change it to <code>ID=1</code> then the <code>RequestStatus</code> entry in the database changes. </p> <p>Any idea how to get around this?</p>
<p>Perl does not expand variables inside single-quoted strings.</p> <p><a href="http://perldoc.perl.org/perldata.html#Scalar-value-constructors" rel="nofollow">http://perldoc.perl.org/perldata.html#Scalar-value-constructors</a> says in part:</p> <blockquote> <p>String literals are usually delimited by either single or double quotes. They work much like quotes in the standard Unix shells: double-quoted string literals are subject to backslash and variable substitution; single-quoted strings are not (except for \' and \ ).</p> </blockquote> <p>Also you should use single-quotes for string delimiters inside your SQL.</p> <p>So this:</p> <pre><code>$dbh-&gt;do('UPDATE Scheduler SET RequestStatus="CANCELED" WHERE ID="$jobID";') </code></pre> <p>Should be this:</p> <pre><code>$dbh-&gt;do("UPDATE Scheduler SET RequestStatus='CANCELED' WHERE ID='$jobID'"); </code></pre> <p>If you want to really use best practices, use bind parameters in your SQL instead of putting variables inside strings. Then you don't need to worry about what kind of quotes you use. Even if the parameter is a string type, you don't put the parameter placeholder in quotes in SQL.</p> <p>Example:</p> <pre><code>$dbh-&gt;do("UPDATE Scheduler SET RequestStatus='CANCELED' WHERE ID=?", undef, $jobID); </code></pre>
Generic Json To Object transformer <p>Is there any way to set the value of "type" attribute of a JsonToObject transformer dynamically ? For ex, A message header will tell you the target Java Object to which incoming Json payload should be converted to. Something like,</p> <pre><code>&lt;int:json-to-object-transformer input-channel="jsonTransformationChannel" type="headers['targetJavaObject']" output-channel="payloadTransformationChannel" /&gt; </code></pre> <p>NOTE : "type" attribute does not support SpEL expressions.</p>
<p>Starting with version 3, the JTOT uses similar headers to the Spring AMQP JSON message converters. See <a href="https://github.com/spring-projects/spring-integration/blob/master/spring-integration-core/src/main/java/org/springframework/integration/mapping/support/JsonHeaders.java#L39" rel="nofollow"><code>JsonHeaders</code></a>.</p> <p>For a simple type, set the <code>json__TypeId__</code> header to the fully qualified class name and <strong>do not</strong> configure a <code>type</code>.</p>
TYPO3 meta description - Use closest <p>I have set the description meta using:</p> <pre><code>page.meta.description.field = description </code></pre> <p>Can I make it so child pages use the description from the closest page that has one set?</p> <p>So if the root page has description1 then all sub-pages use it, unless a sub-page has it's own description2 in which case it and any sub-pages of it would use description2 and so on...</p>
<p>two parts: </p> <ol> <li><p>in your typoscript: </p> <p><code>page.meta.description.data = levelfield:-1, description, slide</code></p></li> <li><p>in your Install-Tool add the field to the fields which should slide:</p> <p><code>$GLOBALS['TYPO3_CONV_VARS']['FE']['addRootLineFields'] = 'description';</code></p></li> </ol> <p>added:<br> aside from straight slide to first non empty entry, you also have options to <a href="https://docs.typo3.org/typo3cms/TyposcriptReference/7.6/ContentObjects/Content/" rel="nofollow">collect</a> all the entries along the rootpath:</p> <p><strong><code>.slide</code></strong> If set and no content element is found by the select command, the rootLine will be traversed back until some content is found.<br> Possible values are "-1" (slide back up to the siteroot), "1" (only the current level) and "2" (up from one level back). Use -1 in combination with collect:<br> <strong><code>.slide.collect</code></strong>: (integer /stdWrap) If set, all content elements found on the current and parent pages will be collected. Otherwise, the sliding would stop after the first hit. Set this value to the amount of levels to collect on, or use "-1" to collect up to the siteroot.<br> <strong><code>.slide.collectFuzzy</code></strong>: (boolean /stdWrap) Only useful in collect mode. If no content elements have been found for the specified depth in collect <strong>mode, traverse further until at least one match has occurred.<br> <code>.slide.collectReverse</code></strong>: (boolean /stdWrap) Reverse order of elements in collect mode. If set, elements of the current page will be at the bottom.</p>
Get unique records where column type is JSONB <p>I have a complicated Postgres query I'm trying to make, mainly because my columns / data is in the JSONB type.</p> <p>I need to get all records</p> <ul> <li>where <code>Auth.status</code> is <code>valid</code></li> <li><code>UserId</code> is <code>1</code></li> <li>Excluding duplicates on <code>Details.reference.card.number</code> </li> </ul> <p>Here's my table:</p> <pre><code>+-----------------------+---------------------------------------------+--------+ | Auth | Details | UserId | +-----------------------+---------------------------------------------+--------+ | {"status": "valid"} | {"reference": {"card": {"number": "4444"}}} | 1 | | {"status": "valid"} | {"reference": {"card": {"number": "3321"}}} | 1 | | {"status": "valid"} | {"reference": {"card": {"number": "4444"}}} | 1 | | {"status": "Invalid"} | {"reference": {"card": {"number": "3331"}}} | 1 | | {"status": "valid"} | {"reference": {"card": {"number": "4444"}}} | 1 | +-----------------------+---------------------------------------------+--------+ </code></pre> <p>This query above should return:</p> <pre><code>+-----------------------+---------------------------------------------+--------+ | Auth | Details | UserId | +-----------------------+---------------------------------------------+--------+ | {"status": "valid"} | {"reference": {"card": {"number": "4444"}}} | 1 | | {"status": "valid"} | {"reference": {"card": {"number": "3321"}}} | 1 | +-----------------------+---------------------------------------------+--------+ </code></pre> <p>What I have so far.</p> <pre><code>SELECT * FROM table WHERE "Auth" @&gt; '{"status": "valid"}' AND "UserId" = 1 </code></pre>
<pre><code>WITH sample_table AS ( SELECT "userId", p."Auth"-&gt;&gt;'status' as "authStatus", p."Detail"-&gt;'"reference"'-&gt;'card'-&gt;&gt;'number' as "referenceCardNumber", FROM my_table p ) SELECT DISTINCT ON ("referenceCardNumber") "referenceCardNumber", * FROM sample_table WHERE "authStatus" = 'valid' AND "userId" = 1 </code></pre>
javascript: Alter the output of a function to the specified demical place <p>I am not very good with my javascript but recently needed to work with a library to output an aggregated table. Was using <a href="https://github.com/openfin/fin-hypergrid" rel="nofollow">fin-hypergrid</a>.</p> <p>There was a part where I need to insert a sum function (rollups.sum(11) in this example)to an object so that it can compute an aggregated value in a table like so:</p> <pre><code>aggregates = {Value: rollups.sum(11)} </code></pre> <p>I would like to change this value to return 2 decimal places and tried:</p> <pre><code>rollups.sum(11).toFixed(2) </code></pre> <p>However, it gives the error : "rollups.sum(...).toFixed is not a function"</p> <p>If I try something like:</p> <pre><code>parseFloat(rollups.sum(11)).toFixed(2) </code></pre> <p>it throws the error: "can't assign to properties of (new String("NaN")): not an object"</p> <p>so it has to be a function object.</p> <p>May I know if there is a way to alter the function rollups.sum(11) to return a function object with 2 decimal places?</p> <p>(side info: rollups.sum(11) comes from a module which gives:</p> <pre><code>sum: function(columnIndex) { return sum.bind(this, columnIndex); } </code></pre> <p>)</p> <p>Sorry I could not post sample output here due to data confidentiality issues. However, here is the code from the example I follow. I basically need to change rollups.whatever to give decimal places. The "11" in sum(11) here refers to a "column index".</p> <pre><code>window.onload = function() { var Hypergrid = fin.Hypergrid; var drillDown = Hypergrid.drillDown; var TreeView = Hypergrid.TreeView; var GroupView = Hypergrid.GroupView; var AggView = Hypergrid.AggregationsView; // List of properties to show as checkboxes in this demo's "dashboard" var toggleProps = [{ label: 'Grouping', ctrls: [ { name: 'treeview', checked: false, setter: toggleTreeview }, { name: 'aggregates', checked: false, setter: toggleAggregates }, { name: 'grouping', checked: false, setter: toggleGrouping} ] } ]; function derivedPeopleSchema(columns) { // create a hierarchical schema organized by alias var factory = new Hypergrid.ColumnSchemaFactory(columns); factory.organize(/^(one|two|three|four|five|six|seven|eight)/i, { key: 'alias' }); var columnSchema = factory.lookup('last_name'); if (columnSchema) { columnSchema.defaultOp = 'IN'; } //factory.lookup('birthState').opMenu = ['&gt;', '&lt;']; return factory.schema; } var customSchema = [ { name: 'last_name', type: 'number', opMenu: ['=', '&lt;', '&gt;'], opMustBeInMenu: true }, { name: 'total_number_of_pets_owned', type: 'number' }, { name: 'height', type: 'number' }, 'birthDate', 'birthState', 'employed', { name: 'income', type: 'number' }, { name: 'travel', type: 'number' } ]; var peopleSchema = customSchema; // or try setting to derivedPeopleSchema var gridOptions = { data: people1, schema: peopleSchema, margin: { bottom: '17px' } }, grid = window.g = new Hypergrid('div#json-example', gridOptions), behavior = window.b = grid.behavior, dataModel = window.m = behavior.dataModel, idx = behavior.columnEnum; console.log('Fields:'); console.dir(behavior.dataModel.getFields()); console.log('Headers:'); console.dir(behavior.dataModel.getHeaders()); console.log('Indexes:'); console.dir(idx); var treeView, dataset; function setData(data, options) { options = options || {}; if (data === people1 || data === people2) { options.schema = peopleSchema; } dataset = data; behavior.setData(data, options); idx = behavior.columnEnum; } // Preset a default dialog options object. Used by call to toggleDialog('ColumnPicker') from features/ColumnPicker.js and by toggleDialog() defined herein. grid.setDialogOptions({ //container: document.getElementById('dialog-container'), settings: false }); // add a column filter subexpression containing a single condition purely for demo purposes if (false) { // eslint-disable-line no-constant-condition grid.getGlobalFilter().columnFilters.add({ children: [{ column: 'total_number_of_pets_owned', operator: '=', operand: '3' }], type: 'columnFilter' }); } window.vent = false; //functions for showing the grouping/rollup capabilities var rollups = window.fin.Hypergrid.analytics.util.aggregations, aggregates = { totalPets: rollups.sum(2), averagePets: rollups.avg(2), maxPets: rollups.max(2), minPets: rollups.min(2), firstPet: rollups.first(2), lastPet: rollups.last(2), stdDevPets: rollups.stddev(2) }, groups = [idx.BIRTH_STATE, idx.LAST_NAME, idx.FIRST_NAME]; var aggView, aggViewOn = false, doAggregates = false; function toggleAggregates() { if (!aggView){ aggView = new AggView(grid, {}); aggView.setPipeline({ includeSorter: true, includeFilter: true }); } if (this.checked) { grid.setAggregateGroups(aggregates, groups); aggViewOn = true; } else { grid.setAggregateGroups([], []); aggViewOn = false; } } function toggleTreeview() { if (this.checked) { treeView = new TreeView(grid, { treeColumn: 'State' }); treeView.setPipeline({ includeSorter: true, includeFilter: true }); treeView.setRelation(true, true); } else { treeView.setRelation(false); treeView = undefined; delete dataModel.pipeline; // restore original (shared) pipeline behavior.setData(); // reset with original pipelline } } var groupView, groupViewOn = false; function toggleGrouping(){ if (!groupView){ groupView = new GroupView(grid, {}); groupView.setPipeline({ includeSorter: true, includeFilter: true }); } if (this.checked){ grid.setGroups(groups); groupViewOn = true; } else { grid.setGroups([]); groupViewOn = false; } } </code></pre>
<p>you may try:</p> <pre><code>(rollups.sum(11)).toFixed(2) </code></pre> <p>enclosing number in parentheses seems to make browser bypass the limit that identifier cannot start immediately after numeric literal</p> <p>edited #2:</p> <pre><code>//all formatting and rendering per cell can be overridden in here dataModel.getCell = function(config, rendererName) { if(aggViewOn) { if(config.columnName == "total_pets") { if(typeof(config.value) == 'number') { config.value = config.value.toFixed(2); } else if(config.value &amp;&amp; config.value.length == 3 &amp;&amp; typeof(config.value[1]) == 'number') { config.value = config.value[1].toFixed(2); } } } return grid.cellRenderers.get(rendererName); }; </code></pre>
scala futures execution in parallel using for-loop <pre><code>package p1 import scala.util.Failure import scala.util.Success import scala.concurrent.Await import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ object modCheck extends App { def getStudentRoolNo(name: String) = Future { println("getStudentRoolNo") name match { case "name1" =&gt; 1 case "name2" =&gt; 2 case _ =&gt; throw new Exception("No doesnt exist") } } def getRank(roolNo: Int) = Future { println("getRank") Thread.sleep(500) roolNo match { case 1 =&gt; "1" case 2 =&gt; "2" case _ =&gt; throw new Exception("No roolNo exist") } } def getDetails(roolNo: Int) = Future { println("getDetails") roolNo match { case 1 =&gt; "details 1" case 2 =&gt; "Details 2" case _ =&gt; throw new Exception("No details exist") } } def getStudentRecord(name: String) = { for { rollNo &lt;- getStudentRoolNo(name) rank &lt;- getRank(rollNo) details &lt;- getDetails(rollNo) } yield (rank + details) } getStudentRecord("name1").onComplete { case Success(ground) =&gt; println(s"got my Details $ground") case Failure(ex) =&gt; println("Exception!" + ex) } Thread.sleep(2000) } </code></pre> <p>I want to execute functions <code>getrank</code> and <code>getDetails</code> in parallel in below code(once the <code>getStudentRollNo</code> is returned). How can I achieve this?</p> <p>I Tried below way, It seems it still executing in sequentially</p> <p>Please let me know , How to execute in parallel</p>
<p>Future starts computation when it's created.</p> <p><code>for (a &lt;- x; b &lt;- y) yield ???</code> is desugared to <code>x.flatMap(a =&gt; y.map(b =&gt; ???))</code> <code>flatMap()</code> and <code>map()</code> execute it's argument after a Future is completed.</p> <p><code>getDetails()</code> can start before completion of <code>getRank()</code> by separating creation of <code>Future</code> and <code>flatMap()</code> invocation.</p> <pre><code>for { rollNo &lt;- getStudentRoolNo(name) rankFuture = getRank(rollNo) detailsFuture = getDetails(rollNo) rank &lt;- rankFuture details &lt;- detailsFuture } yield (rank + details) </code></pre>
web services throwing errors intermittently <p>I have a web service running on server but once in a while it throws an error. This is happening when calling one particular method and all other method works fine but on calling this method I receive following error:- </p> <blockquote> <p>An error occurred while receiving the HTTP response to <a href="https://xxx/xxx/xxx.svc" rel="nofollow">https://xxx/xxx/xxx.svc</a>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.</p> </blockquote> <p>Currently it happened after running fine for 2 weeks. Strangely the method started working fine again after few hours. I am wondering where should I start looking to troubleshoot this issue? Any pointers to troubleshoot shall be helpful.</p> <p>Just to add to this today I received below error:-</p> <blockquote> <p>The underlying connection was closed: A connection that was expected to be kept alive was closed by the server</p> </blockquote> <p>Can both of the error be related to each other?</p> <p>Thanks for the help!</p>
<p>I've also encountered that error. I encountered that error when almost thousands of user simultaneously accessing the web service.</p> <p>I put this piece of code..</p> <pre><code> ServiceClient = new ServiceClient (); var customBinding = new CustomBinding(ServiceClient.Endpoint.Binding); var transportElement = customBinding.Elements.Find&lt;HttpTransportBindingElement&gt;(); transportElement.KeepAliveEnabled = false; ServiceClient.Endpoint.Binding = customBinding; ServiceClient.Open(); </code></pre>
Programmaticaly find next state for max(Q(s',a')) in q-learning using R <p>I am writing a simple grid world q-learning program using R. This is my grid world</p> <p><a href="http://i.stack.imgur.com/I4RQD.png" rel="nofollow"><img src="http://i.stack.imgur.com/I4RQD.png" alt="enter image description here"></a></p> <p>This simple grid world has 6 states in which state 1 and state 6 are starting and ending state. I avoided adding a fire pit, wall, wind so to keep my grid world as simple as possible. For reward matrix I have starting state value-0.1 and ending state a +1 and rest of the state 0. A -0.1 reward for starting state is to discourage the agent from coming back to the start position.</p> <pre><code>#Reward and action-value matrix Row=state(1:6) Column=actions(1:4)[Left,Right,Down,Up in that order] </code></pre> <p>I wrote my program in R and its working but with a problem in finding next state when current state is greater than 4th row. The Q matrix doesn't update after 4th row.</p> <pre><code>#q-learning example #https://en.wikipedia.org/wiki/Q-learning # 2x3 grid world # S for starting grid G for goal/terminal grid # actions left right down up # 4 5 6 state ######### # [0,0,G] # [S,0,0] ######### # 1 2 3 state #setting seed set.seed(2016) #number of iterations N=10 #discount factor gamma=0.9 #learning rate alpha=0.1 #target state tgt.state=6 #reward matrix starting grid has -0.1 and ending grid has 1 R=matrix( c( NA, 0, NA, 0, -0.1, 0, NA, 0, 0, NA, NA, 1, NA, 0,-0.1, NA, 0, 1, 0, NA, 0, NA, 0, NA ), nrow=6,ncol=4,byrow = TRUE) #initializing Q matrix with zeros Q=matrix( rep( 0, len=dim(R)[1]*dim(R)[2]), nrow = dim(R)[1],ncol=dim(R)[2]) for (i in 1:N) { ## for each episode, choose an initial state at random cs &lt;- 1 ## iterate until we get to the tgt.state while (1) { ## choose next state from possible actions at current state ## Note: if only one possible action, then choose it; ## otherwise, choose one at random next.states &lt;- which(R[cs,] &gt; -1) if (length(next.states)==1) ns &lt;- next.states else ns &lt;- sample(next.states,1) ## this is the update Q[cs,ns] &lt;- Q[cs,ns] + alpha*(R[cs,ns] + gamma*max(Q[ns, which(R[ns,] &gt; -1)]) - Q[cs,ns]) ## break out of while loop if target state is reached ## otherwise, set next.state as current.state and repeat if (ns == tgt.state) break cs &lt;- ns Sys.sleep(0.5) print(Q) } } </code></pre> <p>Currently when my algorithm starts the agent always start from the state-1. In the first state(first row of R) there are two actions either Right(R(1,2)) or Up(R(1,4)). If randomly selected an action say <strong>Up (R(1,4))</strong> then the agent move to next state as the action Q(4,action). </p> <p>But now consider state-4(forth row or R) it has two action Right-R(4,2) and Down-R(4,3) this cause problem for my algorithm and if randomly select an action say, Right. Logically it should move to 5th state but my above code uses the action 2 as the next state. so instead of going to 5th state it goes to 2nd state.</p> <p>In the end my algorithm will work perfectly if the dimension of state and action matrices are same(m x m) but in my problem my state and action matrices are different (m x n). I tried to find a solution to this problem but failed to find an logical approach to find next state for $max(Q(s',a'))$ currently I am stuck?</p>
<p>(The comments in your code don't correspond to what you are actually doing. Try to avoid this always.)</p> <p>You are conflating the transition and the reward matrices. For a non-stochastic environment, they should look something like this:</p> <pre><code>R &lt;- matrix(c( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, -1, -1, -1, -1, -1, 10, -1, -1, 10, 10, -1, -1), nrow=6, ncol=4, byrow=T) T &lt;- matrix(c( 1, 2, 1, 4, 1, 3, 2, 5, 2, 3, 3, 6, 4, 5, 1, 4, 4, 6, 2, 5, 6, 6, 3, 5), nrow=6, ncol=4, byrow=T) </code></pre> <p>The ε-greedy strategy would be:</p> <pre><code>greedy &lt;- function(s) which(Q[s,] == max(Q[s,])) egreedy &lt;- function(s, e) if (runif(1, 0, 1) &lt; e) greedy(s) else sample(1:ncol(Q), 1) ca &lt;- egreedy(cs, epsilon) </code></pre> <p>Then choosing the next state is just:</p> <pre><code>ns &lt;- T[cs, ca] </code></pre>
How do I find the smallest number in a list of random integers on Python without using min()? <p>I'm trying to figure out why this code isn't working! The only part not working is the smallestNumber, it always comes back at zero? What am I doing wrong?</p> <pre><code>import random X = random.randint(10,15) pickedNumber =int( input("Please enter a number: ")) print("Generating", (pickedNumber), "random Numbers between 20 and 50:") for numberCount in range(1,pickedNumber+1): numberCount = random.randint(20,50) sum = 0 sum += numberCount print(numberCount) print('The sum = ',sum) print('the average = ', sum/pickedNumber) for pickedNumber in range(0,X,1): number = random.randint(20,50) if pickedNumber== 0 or pickedNumber &lt; smallestNumber: smallestNumber = pickedNumber print('The smallest = ',smallestNumber) </code></pre>
<p>There are several problems with your code that I won't address directly, but as for finding the smallest item in a list of integers, simply sort the list and return the first item in the list:</p> <pre><code>some_list = [5,7,1,9] sorted_list = sorted(some_list) smallest = sorted_list[0] &gt;&gt;&gt; smallest 1 </code></pre> <p>You don't necessarily need to create a second list to store the sorted result, it is simply there to illustrate the difference.</p> <p>EDIT: You could also just store the first random int generated as <code>smallestNumber</code> and then as each new random int is created, compare it to <code>smallestNumber</code> and if the new int is smaller, set <code>smallestNumber</code> to it.</p> <p>Example:</p> <pre><code>//stuff to generate random int done here smallest = new_random_int //generate the next random int if next_random_int &lt; smallest: smallest = next_random_int </code></pre> <p>And so on, where <code>new_random_int</code> is the very first random integer you generate, and <code>next_random_int</code> is any random int you generate after that.</p> <p>Also, welcome to Stack Overflow!</p>
How to override the existing content inside the HTML element by jQuery <p>I want to override the existing content inside the HTML element. I tried with method append() to the element but then it only append content to the existing, I was wonder is there anyway to override the whole content in the element ?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('input.append').click(function() { $('span').append('append') }) $('input.html').click(function() { $('span').html('html') })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;span&gt;span value&lt;/span&gt; &lt;input type='button' class='append' value='Append' /&gt; &lt;input type='button' class='html' value='Html' /&gt;</code></pre> </div> </div> </p> <ol> <li>use .html() to change. </li> <li>append() will just add.</li> </ol>
How to execute test Method by gradle test task? <blockquote> <p>When i run my testing.xml as testNG suit its run properly but when run gradle test task it doesn't execute test</p> <p>testing.xml</p> </blockquote> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"&gt; &lt;suite guice-stage="DEVELOPMENT" name="Default suite"&gt; &lt;test verbose="2" name="test"&gt; &lt;classes&gt; &lt;class name="com.example.EmpBusinessLogicTest"/&gt; &lt;/classes&gt; &lt;/test&gt; &lt;!-- Default test --&gt; &lt;/suite&gt; &lt;!-- Default suite --&gt; </code></pre> <blockquote> <p>build.gradle</p> <p>buildscript { ext { springBootVersion = '1.4.1.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } }</p> <pre><code>apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'spring-boot' jar { baseName = 'demo' version = '0.0.1-SNAPSHOT' } sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') compile('org.testng:testng:6.9.10') } test { useTestNG() { suites 'src/main/resources/testing.xml' } } </code></pre> <p>can anyone help me to execute gradle test task ?</p> </blockquote>
<p>As option you can generate xml directly in gradle in test task, it works fine in our project</p> <pre><code>useTestNG() { suiteXmlBuilder().suite(name: 'Default suite') { test(name : 'test') { classes('') { 'class'(name: 'com.example.EmpBusinessLogicTest') } } } } </code></pre> <p>To execute this test task e.g. with Jenkins you will need to pass system properties to it:</p> <pre><code>systemProperties System.getProperties() systemProperty 'user.dir', project.projectDir </code></pre>
Dagger2 : Cannot find symbol @Autofactory classes <p>I want to migrate my project from dagger 1 to dagger 2. after adding dagger 2 dependent libraries i am getting " error: cannot find symbol class MyClassFactory" error for all @Autofactory classes in my project. However i see that these classes are generated but not recognised by IDE. This Classes worked fine with dagger1. could someone help me if they faced similar issue ?</p> <p>i am using following libraries.</p> <pre><code>compile('com.google.auto.factory:auto-factory:1.0-beta3') { exclude module: 'guava' exclude module: 'javawriter' exclude module: 'dagger' } apt 'com.google.auto.factory:auto-factory:1.0-beta3' compile('com.google.auto.service:auto-service:1.0-rc2') { exclude module: 'guava' } apt 'com.google.auto.service:auto-service:1.0-rc2' //Dagger 2 compile 'com.google.dagger:dagger:2.7' apt 'com.google.dagger:dagger-compiler:2.7' compile 'javax.annotation:jsr250-api:1.0' </code></pre> <p>Please help.</p>
<p>You probably have other compilation failures which block AutoFactory from generating any code. Try looking through the entire error log or increasing the error count as a javac flag to see if there's a dagger issue. This works in general - we have a dagger+ AutoFactory integration test</p>
Java Jenkins.war error <p>I install jenkins on my mac os X 10.6.8, after successfully install jenkins, I browse it in the browser with the default address <a href="http://localhost:8080" rel="nofollow">http://localhost:8080</a> but the tomcat page display not the jenkins home page. I read the documentaion on jenkins that it will need to execute command java -jar jenkins.war --httpPort=8080</p> <p>When execute command <strong>java -jar jenkins.war --httpPort=8080</strong></p> <p>having this error</p> <blockquote> <p>2016-09-15 22:50:56.106 java[46344:a07] *** NSInvocation: warning: object 0x1160db440 of class 'ThreadUtilities' does not implement doesNotRecognizeSelector: -- abort Trace/BPT trap</p> </blockquote> <p>I don't know what is wrong, please help.</p> <p>Thanks, dave</p>
<p>You should be able to deploy Jenkins out of the box, just go to:</p> <p>localhost:8080/html</p> <p>Select you jenkins.war and thats it.</p> <p>Just be sure you can deploy files with that size.</p> <p>You can follow up this link:</p> <p><a href="https://maxrohde.com/2011/04/27/large-war-file-cannot-be-deployed-in-tomcat-7/" rel="nofollow">https://maxrohde.com/2011/04/27/large-war-file-cannot-be-deployed-in-tomcat-7/</a></p>
Could not find method android() for arguments in Android Studio 2.2 Windows 7 32bit <p>I am new to Android Studio. While trying to build first android app I got stuck with this issue.</p> <p>See the attached screen-shot</p> <p><a href="http://i.stack.imgur.com/McTGM.jpg" rel="nofollow">my-application-screen-shot</a></p>
<p>I found something similar already asked, I dont know if it is a duplicate but have a look at this link, it might be the solution. It looks like something with the Gradle version or build you are using.</p> <p><a href="http://stackoverflow.com/questions/37250493/could-not-find-method-android-for-arguments">Could not find method android() for arguments</a></p>
select all products and join main category through sub-categories (unknown level) <p>I have 2 tables</p> <p>Categories</p> <pre> id - name - parent 1 - Category A - 0 2 - Category B - 0 3 - Category C - 0 4 - Category D - 0 5 - Subcategory Of 1 - 1 6 - Subcategory Of 5 - 5 7 - Subcategory Of 5 - 5 </pre> <p>Product</p> <pre> id - name - category - description 1 - Name - 5 - Description </pre> <p>How to select all products and join main category through sub-categories? Product categories can has only 1 or 2 or 3 or 4 levels (Unknown level).</p> <p>I use "WITH RECURSIVE" in categories table but can't find the way to combine product table with 1 time query</p> <pre> WITH RECURSIVE category_child AS ( SELECT * FROM categories as c WHERE c.id = 5 UNION ALL SELECT c2.* FROM categories AS c2 JOIN category_child as c3 ON c3.parent_id = c2.id ) </pre> <p>What's the best way to do this ?</p> <p>Expected Result</p> <pre> id - name - category - description - root - sub category id 1 - sub category id 2 - sub category id 3 </pre> <p>OR </p> <pre> id - name - category - description - root id - name - category - description - sub category id 1 id - name - category - description - sub category id 2 id - name - category - description - sub category id 3 </pre>
<p>As you want the complete path to a category, you can't start your non-recursive part with <code>c.id = 5</code> you have to start at the root using <code>where parent_id is null</code> (you should <strong>not</strong> identify the root nodes with a non-existing category ID, that prevents creating a proper foreign key for the parent_id column).</p> <p>In the recursive part you can then aggregate the full path to the root category:</p> <pre><code>with recursive tree as ( select *, id as root_category, concat('/', name) as category_path from category where parent_id is null union all select c.*, p.root_category, concat(p.category_path, '/', c.name) from category c join tree p on c.parent_id = p.id ) select p.id as product_id, p.name as product_name, t.root_category, t.category_path from tree t join product p on p.category = t.id </code></pre> <p>Using the following sample data:</p> <pre><code>create table category (id integer, name text, parent_id integer); create table product (id integer, name text, category integer, description text); insert into category values (1, 'Category A', null), (2, 'Category B', null), (3, 'Category C', null), (4, 'Category D', null), (5, 'Subcategory Of 1', 1), (6, 'Subcategory Of 5', 5), (7, 'Subcategory Of 5', 5), (8, 'Subcategory of D', 4) ; insert into product values (1, 'Product One', 5, 'Our first product'), (2, 'Product Two', 8, 'The even better one'); </code></pre> <p>This returns:</p> <pre><code>product_id | product_name | root_category | category_path -----------+--------------+---------------+----------------------------- 1 | Product One | 1 | /Category A/Subcategory Of 1 2 | Product Two | 4 | /Category D/Subcategory of D </code></pre>
SGPLOT Procedure STYLEATTRS Statement <p><a href="http://support.sas.com/documentation/cdl/en/grstatproc/67909/HTML/default/viewer.htm#p1dt33l6a6epk6n1chtynsgsjgit.htm" rel="nofollow">Official document</a> said 6 style options are available</p> <pre><code>BACKCOLOR=color DATACOLORS=(color-list) DATACONTRASTCOLORS=(color-list) DATALINEPATTERNS=(line-pattern-list) DATASYMBOLS=(marker-symbol-list) WALLCOLOR=color </code></pre> <p>However, when I try something like below</p> <pre><code>proc sgplot data=test; styleattrs backcolor=vpal; ... run; </code></pre> <p>Error messages pop up: </p> <pre><code>ERROR 22-322: Syntax error, expecting one of the following: ;, DATACOLORS, DATACONTRASTCOLORS, DATALINEPATTERNS, DATASYMBOLS. ERROR 202-322: The option or parameter is not recognized and will be ignored. </code></pre> <p>Is it a SAS version problem? I'm using EG 6.1.</p> <p>The main reason I want to use this option is to have within procedure control on graph background color. I have 4 graphs in one page in PDF and I want to control the background color for each graph with macro variable based on some criteria. So changing the ODS output style doesn't work for me - it changes EVERY graph background.</p>
<p>BACKCOLOR is only available as of SAS 9.4 TS1M3. You have TS1M1. </p> <p>See the Note in the documentation you linked to under BACKCOLOR. </p> <p><a href="http://i.stack.imgur.com/RWajI.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/RWajI.jpg" alt="Documentation Note"></a></p>
Cassandra : cant see any progress with the insertion of data <p>Am newbie to cassandra. My process workers are trying to insert into the cassandra db. After some few hours I cant see any progress of insertion.</p> <p>My debug logs are saying the below across nodes of cassandra:</p> <blockquote> <p>WARN [SharedPool-Worker-48] 2016-10-07 00:59:04,025 BatchStatement.java:287 - Batch of prepared statements for [my_database.my_table] is of size 14264, exceeding specified threshold of 5120 by 9144. WARN [SharedPool-Worker-1] 2016-10-07 00:59:04,025 BatchStatement.java:287 - Batch of prepared statements for [my_database.my_table] is of size 14272, exceeding specified threshold of 5120 by 9152. WARN [SharedPool-Worker-62] 2016-10-07 00:59:04,025 BatchStatement.java:287 - Batch of prepared statements for [my_database.my_table] is of size 14304, exceeding specified threshold of 5120 by 9184. WARN [SharedPool-Worker-56] 2016-10-07 00:59:04,026 BatchStatement.java:287 - Batch of prepared statements for [my_database.my_table] is of size 14240, exceeding specified threshold of 5120 by 9120.</p> <p>DEBUG [GossipStage:1] 2016-10-07 07:43:38,765 FailureDetector.java:456 - Ignoring interval time of 2710773843 for /10.157.47.131 DEBUG [GossipStage:1] 2016-10-07 07:43:38,766 FailureDetector.java:456 - Ignoring interval time of 2000307543 for /10.157.41.234 DEBUG [GossipStage:1] 2016-10-07 07:43:57,769 FailureDetector.java:456 - Ignoring interval time of 2069384918 for /10.157.43.166 DEBUG [GossipStage:1] 2016-10-07 07:44:07,702 FailureDetector.java:456 - Ignoring interval time of 2000430166 for /10.157.43.166 DEBUG [GossipStage:1] 2016-10-07 07:44:14,772 FailureDetector.java:456 - Ignoring interval time of 2000475716 for /10.157.43.166 DEBUG [GossipStage:1] 2016-10-07 07:44:15,772 FailureDetector.java:456 - Ignoring interval time of 2000349080 for /10.157.41.234 DEBUG [GossipStage:1] 2016-10-07 07:44:17,773 FailureDetector.java:456 - Ignoring interval time of 2000373755 for /10.157.43.166</p> </blockquote> <p>Is this is the cause of concern. Any help/information/solution would be helpful</p> <p>Thanks a ton.</p>
<p>A batch is used in Cassandra to "bundle" related operations in a single execution, similar to a explicit transaction in a relational database.</p> <p>If what you want is to upload large volumes of data into Cassandra, you can use <a href="https://docs.datastax.com/en/cassandra/3.x/cassandra/tools/toolsBulkloader.html" rel="nofollow">Bulk loader</a>, external tools like <a href="https://docs.datastax.com/en/datastax_enterprise/4.5/datastax_enterprise/ana/anaSqpTOC.html" rel="nofollow">Sqoop</a>, or asynchronous prepared statements.</p>
Generate table using jquery <p><a href="http://i.stack.imgur.com/36ogy.png" rel="nofollow"><img src="http://i.stack.imgur.com/36ogy.png" alt="Updated Image"></a></p> <pre><code> var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); subGroup.push(now.getFullYear()); for (var i = 1; i &lt; 7; ++i) { var future = now.setMonth(now.getMonth() + 1, i); if ((months[now.getMonth()]) == "January") { subGroup.push((now.getFullYear())) } subGroup.push(months[now.getMonth()]); } subGroups.push(subGroup); }); alert(subGroups); //debugger; var array = subGroups.toString().split(','); var arrayLength = array.length; var theTable = document.createElement('table'); tr = document.createElement('tr'); for (var i = 0, tr, td; i &lt; arrayLength; i++) { td = document.createElement('td'); td.appendChild(document.createTextNode(array[i])); tr.appendChild(td); theTable.appendChild(tr); } document.getElementById('table').appendChild(theTable);` </code></pre> <p>I have a multi select dropdown and based on the number of selection of dropdown I have to dynamically generate the table Like the following attached image . Future 6 Months will be displayed based on the current month. Please Can anybody help me !! <a href="http://i.stack.imgur.com/wyfD5.png" rel="nofollow"><img src="http://i.stack.imgur.com/wyfD5.png" alt="Dynamic generation of table based on dropdown selection"></a></p>
<p>You should use a binding library such as Knockkout, when your drop down changes, build a view model with the month and empty value.</p> <p>ex: Include KnockoutJS in your page, download it from here <a href="http://knockoutjs.com/" rel="nofollow">http://knockoutjs.com/</a></p> <p>build a model, ex:</p> <pre><code>var MonthViewModel = function(monthID, value) { this.monthID= ko.observable(monthID); this.monthValue= ko.observable(value); }; var ViewModel = function( var that = this; that.months = ko.obserabaleArray(); that.addMonth = function(month){ that.months.push(month); }; ){}; var viewModel = new ViewModel(); ko.applyBindings(viewModel); // This makes Knockout get to work </code></pre> <p>Your HTML should be something like this:</p> <pre><code>&lt;table id="months"&gt; &lt;tr data-bind="foreach:months"&gt; &lt;td&gt; &lt;span data-bind="text:monthID"&gt;&lt;/span&gt; &lt;input type="text" data-bind="value:monthValue"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>In your event that fires on changing the drop down selection, you should get the selected months, add it to the <code>viewModel</code> variable and the HTML will bind automatically</p>
Data saving and data reading ( C Programming ) <p>The code below will ask for input, and is supposed to print it after. <br><br>However, I've encountered several problems.<br><hr><strong>Problems</strong></p> <ul> <li>program stops working after I confirm the entry.</li> <li>when it is supposed to print the input, it instead prints out weird symbols.</li> </ul> <hr> <p><strong>Questions</strong>: </p> <ul> <li><p>How do I print the whole value of the variable?<br><br> <strong>For ex</strong> :- When I input " <em>John Lemon</em> " for when it asks for " <em>Name:</em> ". <br><br>I would be able to print " <em>John Lemon</em> " instead of " <em>John</em> ".<br><br></p></li> <li><p>After printing the first value of the variable, how do I continue to print the second value and the third value of the variable wholly?<br><br> <strong>For ex</strong> :<br><br><strong><em>Sample Output</em></strong><br><br> Name: John Lemon<br><br>Age: 21<br><br>Address: 41, 2/2 Apple Street</p></li> </ul> <p><hr>What can I do to rectify this problem?</p> <p>If possible, please explain in layman terms as I'm new to C programming.<br><br>Sorry if this looks messy. I've tried my best to keep it as simple as possible.</p> <pre><code>#include&lt;stdio.h&gt; char fname[]={"guest.dat"}; struct text { char name; int age; char address; }; void printing () { struct text t1; FILE *fp; fp=fopen(fname,"r"); printf("\nName: %c",t1.name); printf("\nAge: %d",t1.age); printf("\nAddress: %s",t1.address); } int main () { FILE *fp; int choice; struct text t1; fp=fopen(fname,"a+"); fread(&amp;t1,sizeof(t1),1,fp); printf("\nPlease enter name: "); scanf("%c",&amp;t1.name); fflush(stdin); printf("\nPlease enter age: "); scanf("%d",&amp;t1.age); fflush(stdin); printf("\nPlease enter address: "); scanf("%s",&amp;t1.address); fflush(stdin); printf("\nConfirm? (Y/N): "); scanf("%c",&amp;choice); if ( choice == 'y' | choice == 'Y') { fp=fopen(fname,"a+"); fwrite(&amp;t1,sizeof(t1),1,fp); fclose(fp); fflush(stdin); system("cls"); printing(); } else if ( choice == 'n' | choice == 'N') { fflush(stdin); system("cls"); printing(); } else fflush(stdin); system("cls"); printf("Please try again!"); system("pause"); } </code></pre>
<p>Your program prints "weird symbols" because <code>t1</code> is never initialized in the <code>printing</code> function.</p> <p>Here you never read from file:</p> <pre><code>void printing () { struct text t1; FILE *fp; fp=fopen(fname,"r"); // Missing read from file printf("\nName: %c",t1.name); printf("\nAge: %d",t1.age); printf("\nAddress: %s",t1.address); } </code></pre> <p>Further, this line:</p> <pre><code>printf("\nAddress: %s",t1.address); </code></pre> <p>is wrong. You use <code>%s</code> which is for <code>char*</code> but <code>address</code> is a <code>char</code>. So you must use <code>%c</code>. The same applies for the <code>scanf</code> of <code>address</code>. </p> <p>Maybe you really wanted <code>struct text</code> to hold strings!? If so you should have used a <code>char array</code>. Currently the struct can only hold char (i.e. a single letter for name and address). Maybe you really wanted to do:</p> <pre><code>struct text { char name[100]; int age; char address[100]; }; </code></pre> <p>and then use <code>%s</code> instead of <code>%c</code> for both <code>printf</code> and <code>scanf</code>.</p> <p>Also here you have some "strange" code:</p> <pre><code>int main () { FILE *fp; int choice; struct text t1; // Why do you have the next to lines? Seems to be a mistake - remove them fp=fopen(fname,"a+"); fread(&amp;t1,sizeof(t1),1,fp); </code></pre> <p>Besides that, your code lacks all kind of checks of return values. Always check the value returned by <code>fopen</code>, <code>fread</code>, <code>fwrite</code> and <code>scanf</code>.</p>
Eclipse Oomph windows 64 bit installer downloading linux tools <p>I am installing eclipse using Oomph installer tool provided, I am seeing in logs that linux tools are getting downloaded which is taking time as well. I would like to understand the reason and if we are installing eclipse using Oomph we are not sure of what all the plugins and jars will be downloaded, how does this work? Collecting 1 artifacts from <a href="http://download.eclipse.org/linuxtools/updates-docker-nightly/" rel="nofollow">http://download.eclipse.org/linuxtools/updates-docker-nightly/</a> Downloading org.bouncycastle.bcprov Fetching org.bouncycastle.bcprov_1.52.0.v20160915-1535.jar from <a href="http://download.eclipse.org/linuxtools/updates-docker-nightly/plugins/" rel="nofollow">http://download.eclipse.org/linuxtools/updates-docker-nightly/plugins/</a></p>
<p>Java lives on dependencies. For instance, bouncycastle is a crypto library. It's used for many things, including securing connections. It's probably a dependency of at least 10 other tools in Eclipse.</p> <p>Whenever a Java tool in Eclipse declares a dependency, the installer is going to go out to a public repository and fetch that dependency so your program will build properly. That's generally true of installers and build tools beyond Eclipse as well.</p>
Image slideshow useing Python ttk <p>I am looking for a way to display multiple photos in a slide show format.</p> <p>I have not tried anything as I have no idea of what I'm doing to get to that stage as there is no information anywhere that solves my problem.</p> <p>thank you. </p>
<p>NOT MY OWN CODE, TAKEN FROM <a href="https://www.daniweb.com/programming/software-development/code/468841/tkinter-image-slide-show-python" rel="nofollow">https://www.daniweb.com/programming/software-development/code/468841/tkinter-image-slide-show-python</a>`</p> <pre><code>''' tk_image_slideshow3.py create a Tkinter image repeating slide show tested with Python27/33 by vegaseat 03dec2013 ''' from itertools import cycle try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk class App(tk.Tk): '''Tk window/label adjusts to size of image''' def __init__(self, image_files, x, y, delay): # the root will be self tk.Tk.__init__(self) # set x, y position only self.geometry('+{}+{}'.format(x, y)) self.delay = delay # allows repeat cycling through the pictures # store as (img_object, img_name) tuple self.pictures = cycle((tk.PhotoImage(file=image), image) for image in image_files) self.picture_display = tk.Label(self) self.picture_display.pack() def show_slides(self): '''cycle through the images and show them''' # next works with Python26 or higher img_object, img_name = next(self.pictures) self.picture_display.config(image=img_object) # shows the image filename, but could be expanded # to show an associated description of the image self.title(img_name) self.after(self.delay, self.show_slides) def run(self): self.mainloop() # set milliseconds time between slides delay = 3500 # get a series of gif images you have in the working folder # or use full path, or set directory to where the images are image_files = [ 'Slide_Farm.gif', 'Slide_House.gif', 'Slide_Sunset.gif', 'Slide_Pond.gif', 'Slide_Python.gif' ] # upper left corner coordinates of app window x = 100 y = 50 app = App(image_files, x, y, delay) app.show_slides() app.run() </code></pre>
Using Python to Read Rows of CSV Files With Column Content containing Comma <p>I am trying to parse this CSV and print out the various columns separately.</p> <p>However my code is having difficulty doing so possibly due to the commas in the addresses, making it hard to split them into 3 columns.</p> <p>How can this be done?</p> <p><strong>Code</strong></p> <pre><code>with open("city.csv") as f: for row in f: print row.split(',') </code></pre> <p><strong>Result</strong></p> <pre><code>['original address', 'latitude', 'longitude\n'] ['"2 E Main St', ' Madison', ' WI 53703"', '43.074691', '-89.384168\n'] ['"Minnesota State Capitol', ' St Paul', ' MN 55155"', '44.955143', '-93.102307\n'] ['"500 E Capitol Ave', ' Pierre', ' SD 57501"', '44.36711', '-100.346342\n'] </code></pre> <p><strong>city.csv</strong></p> <pre><code>original address,latitude,longitude "2 E Main St, Madison, WI 53703",43.074691,-89.384168 "Minnesota State Capitol, St Paul, MN 55155",44.955143,-93.102307 "500 E Capitol Ave, Pierre, SD 57501",44.36711,-100.346342 </code></pre>
<p>If you just want to parse the file, I would recommend using <a href="http://pandas.pydata.org/" rel="nofollow">Pandas Library</a> </p> <pre><code>import pandas as pd data_frame = pd.read_csv("city.csv") </code></pre> <p>which gives you a data frame that looks like this in iPython notebook. <a href="http://i.stack.imgur.com/ZPW6j.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZPW6j.png" alt="resulting data frame"></a></p>
Is it possible to check for global variables in IPython when running a file? <p>I have a file like so:</p> <pre><code>import pandas a pd def a_func(): print 'doing stuff' if __name__ == "__main__": if 'data' not in globals(): print 'loading data...' data = pd.read_csv('datafile.csv') </code></pre> <p>When I run the file in IPython with <code>run file.py</code>, it always loads the data, but when I print <code>globals.keys()</code> in IPython, I can see the <code>data</code> variable. Is there a way to access the global variables from IPython from within my <code>file.py</code> script, so I don't have to load the data every time I run the script in IPython?</p>
<p>Everytime a python file is executed the globals() dictionary is reset by the interpreter. So if you will try to do something like </p> <pre><code>print globals().keys() </code></pre> <p>you can see that 'data' is not in globals. This dictionary gets updated as the program runs. So I don't think you can refer to the globals() of the IPython in the program.</p> <p>check this <a href="https://docs.python.org/2/faq/programming.html#how-can-i-have-modules-that-mutually-import-each-other" rel="nofollow">link</a> ,according to it, globals are emptied.</p>
Mod rewrite refer 500 internal error error <p>I have written an rewrite rule for a folder in my website.</p> <p>its looks like this : </p> <pre><code>#page rewrites RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^([\w-]+)/note $1/addednote_file.php [NC,L] </code></pre> <p>as my htaccess rule above, if any of my folders on my root directory has the addednote_file.php can be accessed by "/notes". </p> <p><strong>This script works fine,</strong></p> <p>But when i try to access that file with and, if that folder doesn't exist on my root directory give my 500 internal server error.</p> <p>in a example this link "myweb/test/events" . "/test/ is the folder and it is exist on my root directory. but "myweb/notexist/events" . "/notexists/" is a folder and it doesn't exists on my root. and when i access this link "myweb/notexist/events" it display 500 internal server erro instead of showing my erro page. </p> <p>my errodocuments are like this :</p> <pre><code>ErrorDocument 404 /myweb/page-couldnt-fine-reporting.php ErrorDocument 403 /myweb/page-couldnt-fine-reporting.php ErrorDocument 304 /myweb/page-couldnt-fine-reporting.php </code></pre> <p>please tell me how to add this error to my erro document . Thank you !</p>
<p>When you get a 500 error code there should be something in the error log. If there is nothing then it is the PHP that is being executed and crashing.</p> <p>The second argument to <code>ErrorDocument</code> is the HTTP return code. So you can use <code>ErrorDocument 500</code> to override the default page.</p> <p>If you do get something in the error log then add it to your question. You should also consider adding mod_rewrite logging in order to see what is going on. Details on how to do this are here as it is different in Apache v2.2 and v2.4:<a href="http://wiki.apache.org/httpd/RewriteLog" rel="nofollow">http://wiki.apache.org/httpd/RewriteLog</a></p>
High latency between the azure web app and azure sql database <p>I create azure web app in west europe and azure sql database in west europe. When app connecting to sql database and execute simple select it takes 4 sec (even in local cheap hosting it takes 200-300ms). Its horrible. I create MySQL clear db and the same problem, horrible latency. The both services are in the same datacenter, why it takes so long time? How to fix it?</p>
<p>First what you can try is to scale your pricing plan on database server and App service. Besides, Azure has build in tool - Database Advisor, which can help you to fix your possible db issues (like add index). Finally - check out database metric (there is possibility to edit chart) to know for sure that this is network or db latency.</p>
How the transcript of a video should be visible to accomplish WCAG 2.0? <p>I'm building a website that has to achieve the AA Conformance to WCAG.</p> <p>We are going to provide videos and to do it right there has to be a transcript of this video, my question is, in html were is the correct order to put this transcript before, after. there is a valid tag to comply this.</p> <p>Thanks for your time. </p>
<p>Ideally, the transcript should be placed before the video. There is no tag specifically for transcripts - you will need to mark up the speech and descriptions using paragraph tags and any other useful markup like headings, strong, emphasis, etc. I like to use a link just above the video to show/hide the transcript so it doesn't take up too much room on the page until the user decides they want to read it. This <a href="http://www.iheni.com/accessible-media-player-resources/" rel="nofollow">list of accessible media player resources</a> should give you some good examples.</p>
Sed Command modification to make it work <p>In sed I just want to replace a range of text to a blank space from 13 to 21 line number and print rest all the line as it is. Please help me out.</p>
<p>If you want to delete lines 13 through 21</p> <pre><code>sed -i '13,21d' file </code></pre> <p>That will remove the lines from the file, if you don't want to actually delete them, but just remove them from your output</p> <pre><code>sed -e '13,21d' file </code></pre>
How to view the source code of numpy.random.exponential? <p>I want to see if <code>numpy.random.exponential</code> was implemented using F^{-1} (U) method, where F is the c.d.f of exponential distribution and U is uniform distribution. </p> <p>I tried <code>numpy.source(random.exponential)</code>, but returned '<em>Not available for this object'</em>. Does it mean this function is not written in Python?</p> <p>I also tried <code>inspect.getsource(random.exponential)</code>, but returned an error saying it's not module, function, etc.</p>
<p>numpy's sources are <a href="https://github.com/numpy/numpy" rel="nofollow">at github</a> so you can use github's <a href="https://github.com/numpy/numpy/search?utf8=%E2%9C%93&amp;q=exponential" rel="nofollow">source-search</a>.</p> <p>As often, these parts of the library are not implemented in pure python.</p> <p>The python-parts (in regards to your question) are <a href="https://github.com/numpy/numpy/blob/7ccf0e08917d27bc0eba34013c1822b00a66ca6d/numpy/random/mtrand/mtrand.pyx" rel="nofollow">here</a>:</p> <p>The more relevant code-part is from <a href="https://github.com/numpy/numpy/blob/c90d7c94fd2077d0beca48fa89a423da2b0bb663/numpy/random/mtrand/distributions.c" rel="nofollow">distributions.c</a>:</p> <pre><code>double rk_standard_exponential(rk_state *state) { /* We use -log(1-U) since U is [0, 1) */ return -log(1.0 - rk_double(state)); } double rk_exponential(rk_state *state, double scale) { return scale * rk_standard_exponential(state); } </code></pre>
How to track recurring payment details with paypal in php? <p>I am using paypal as my payment gateway in one of my cakephp 3.3. </p> <p>I have already done with recurring payment and it is working fine.But i am not able to track every payment of specific user after the recurring payment start.</p> <p>So please help me on this, how can i track each payment details which occurs with recurring payment. I want to keep this record in my database.</p> <p>Thanks in advance.</p>
<p>Take a look at <a href="https://developer.paypal.com/docs/classic/products/instant-payment-notification/" rel="nofollow">Instant Payment Notification (IPN)</a>. </p> <p>Each time a transaction occurs on your PayPal account, PayPal will send a POST request of the transaction data to a URL that you specify. </p> <p>Your script / URL can receive that data and process it however you need to. It happens automatically, and in most cases instantly when the transaction occurs. </p> <p>You can build updates to your database, email notifications, hits to 3rd party web services, etc. into an IPN solution.</p> <p><strong>UPDATE</strong></p> <p>For those using the REST API then instead of IPN you would use <a href="https://developer.paypal.com/docs/integration/direct/rest/webhooks/" rel="nofollow">Webhooks</a>. They're technically the same thing, but function slightly differently. </p>
How to insert using different table based on condition in same query <p>I am merging data in one table from tables of 2 database. Structure is as per below:</p> <blockquote> <p><strong>Table in new Database</strong> :</p> <p>User Table : {UserName,Email}</p> <p><strong>Table in Database1</strong> :</p> <p>User Table : {UserName,Email,LastLogin}</p> <p><strong>Table in Database2</strong> :</p> <p>User Table : {UserName,Email,LastLogin}</p> </blockquote> <p>Now i need to write query that if Email address are same in 2 tables from database 1 and database2 then we need to insert record where LastLogin is latest.</p> <p>Can someone suggest over this.</p>
<p>I think you are in need of this.. :)</p> <p>Try modifying it accordingly..</p> <pre><code>declare @Email_1 nvarchar(100),@Email_2 nvarchar(100),@UserName nvarchar(100),@Lastlogin_1 datetime,@Lastlogin_2 datetime,@loop int=0 use [Database1] while @loop != (select count(Distinct Email) from [User Table]) BEGIN use [Database1] set @Email_1 = (select Distinct Email from [User Table] order by email asc offset @loop rows fetch next 1 rows only) set @LastLogin_1 = (select top 1 max(LastLogin) from [User Table] where email=@Email_1) use [Database2] set @Email_2 = (select top 1 Email from [User Table] where Email like '%@Email_1%') set @LastLogin_2 = (select top 1 max(LastLogin) from [User Table] where email=@Email_2) if @email_1=@email_2 BEGIN if @LastLogin_1&gt;@LastLogin_2 BEGIN use [Database_1] set @username = (select top 1 Username from [user table] where email=@email_1 and lastlogin=@Lastlogin_1) use [New Database] insert into [User Table] select @username,@email_1 END else if @LastLogin_1&lt;@LastLogin_2 BEGIN use [Database_2] set @username = (select top 1 Username from [user table] where email=@email_2 and lastlogin=@Lastlogin_2) use [New Database] insert into [User Table] select @username,@email_1 use [Database1] END END set @loop=@loop+1 END </code></pre>
Firebase and UISearchbarController searching via the server and not the client -Swift iOS <p>Does anyone have any info on how to incorporate Firebase into a UISearchController delegate? I can't find any solid info on it. There may possibly be thousands of employees.</p> <p>I know how to use the search controller delegates <code>updateSearchResultsForSearchController</code> and using a <code>NSPredicate</code> to filter what I'm looking for if I was using NSUserDefaults but using Firebase I'm uncertain.</p> <p>I've added some more code to my question</p> <p>I have a custom data model object saved in FirebaseDatabase and I'd like to search on all of the following properties within the object.</p> <pre><code>lastName idNumber deptNumber position </code></pre> <p>Searching any of these properties should first show a partial string inside the table cells until the entire string i'm looking for is shown. So if I typed in the letter "S" then all employee last names beginning with "S" should show. If I enter "Sa" the in would filter to those letters". From my understanding I should use "\u{f8ff}" to get the partial search string but no data is returned.</p> <p>Anyhow here's all the code</p> <p>My object is:</p> <pre><code>class Employee{ var firstName: String? var lastName: String? var idNumber: String? var deptNumber: String? var position: String? } </code></pre> <p>My paths</p> <pre><code>-root -users -uid |_"email":"emailAddress" |_"userID":"uid" |_"firstName":"firstName" |_"lastName":"lastName" -employees -hireDate -uid //this is the same uid from the users node so I know who's who |_"firstName":"firstName" |_"lastName":"lastName" |_"idNum":"idNumber" |_"deptNumber":"deptNumber" |_"position":"position" </code></pre> <p>My rules:</p> <p>What's happening here is the day an employee is hired they are asked to create a company account using their email address and pw. At the same time a "employees" path is created with a child being a "hireDate" path and finally the employees "uid" path. This employee "uid" is the path I want to search on from the "employees" node</p> <pre><code>{ "rules": { "users" : { "$uid" : { ".read": true, ".write": "auth != null &amp;&amp; auth.uid == $uid" } }, "employees": { "$hireDate": { "$uid": { ".read": true, ".indexOn": ["lastName", "idNumber", "deptNumber", "position"] } } } } } </code></pre> <p>My searchController</p> <pre><code>import UIKit class SearchController: UIViewController{ @IBOutlet var tableView: UITableView! var searchController: UISearchController! var employeesToFilter = [Employee]() var filteredSearchResults = [Employee]() override func viewDidLoad() { super.viewDidLoad() self.searchController = UISearchController(searchResultsController: nil) self.tableView.delegate = self //all searchController properties get set here no need to include them though let ref = FIRDatabase.database().reference() let employeeRef = ref.child("employees") employeeRef?.queryOrderedByChild("lastName").queryStartingAtValue("\u{f8ff}").queryLimitedToFirst(20).observeEventType(.ChildAdded, withBlock: { (snapshot) in if let dict = snapshot.value as? [String:AnyObject]{ let firstName = dict["firstName"] as! String let lastName = dict["lastName"] as! String let idNumber = dict["idNumber"] as! String let deptNumber = dict["deptNumber"] as! String let position = dict["position"] as! String let employee = Employee() employee.firstName = firstName employee.lastName = lastName employee.idNumber = idNumber employee.deptNumber = deptNumber employee.position = position self.employeesToFilter.append(employee) } }) self.tableView.reloadData() } override func viewDidAppear(animated: Bool) { self.searchController.active = true } deinit { self.searchController = nil } } //MARK:- TableView Datasource extension SearchBuildingController: UITableViewDataSource, UITableViewDelegate{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return self.filteredSearchResults.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("SearchCell", forIndexPath: indexPath) as! SearchCell let searchString = self.filteredSearchResults[indexPath.row] cell.firstNameLabel.text = searchString.firstName cell.lastNameLabel.text = searchString.lastName cell.idNumberLabel.text = searchString.idNumber cell.deptNumberLabel.text = searchString.deptNumber cell.positionLabel.text = searchString.position return cell } } //MARK:- SearchController Delegates extension SearchController: UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate{ func searchBarTextDidBeginEditing(searchBar: UISearchBar) { tableView.reloadData() } func updateSearchResultsForSearchController(searchController: UISearchController) { self.employeesToFilter.removeAll(keepCapacity: false) self.filteredSearchResults.removeAll(keepCapacity: false) let searchText = self.searchController.searchBar.text let searchPredicate = NSPredicate(format: SELF.lastName CONTAINS [c] %@ OR SELF.idNumber CONTAINS [c] %@ OR SELF.deptNumber CONTAINS[c] %@ OR SELF.position CONTAINS [c] %@", searchText!, searchText!, searchText!, searchText!) let array = (self.employeesToFilter as NSArray).filteredArrayUsingPredicate(searchPredicate) self.filteredSearchResults = array as! [Employee] tableView.reloadData() } } </code></pre>
<p>Here is an example of how I have accomplished this using Firebase building a list of campuses. This method loads all of the data that is in the table view up front making it easy to search and filter.</p> <p>My campus object is pretty simple with an id and a name.</p> <pre><code>struct Campus { var id: String var name: String } </code></pre> <p>In the view controller I have two arrays. One is to hold the list of all campuses returned and the other array is for the filtered campuses.</p> <pre><code>let campuses = [Campus]() let filteredCampuses = [Campus]() </code></pre> <p>I then called a method that I had set up to load the campuses from Firebase.</p> <pre><code>override func viewDidLoad() { ... getAllCampusesFromFirebase() { (campuses) in self.campuses = campuses dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } } </code></pre> <p>Then when performing the search I filter out the campuses comparing the campus name to the search text from the search bar.</p> <pre><code>func updateSearchResultsForSearchController(searchController: UISearchController) { guard let searchText = searchController.searchBar.text else { return } filteredCampuses = campuses.filter { campus in return campus.name.lowercaseString.containsString(searchText.lowercaseString) } tableView.reloadData() } </code></pre> <p>If you are not loading all of the data up front then Firebase provides some handy methods to call that you can use to filter the data based on the reference path. <a href="https://firebase.google.com/docs/database/ios/lists-of-data" rel="nofollow">https://firebase.google.com/docs/database/ios/lists-of-data</a></p> <p><code>queryStarting(atValue)</code> or <code>queryStarting(atValue:childKey:)</code> would probably be the one that you'd want to use in this case.</p> <pre><code>ref.queryStarting(atValue: Any?) ref.queryStarting(atValue: Any?, childKey: String?) </code></pre>
how to determine the total free disk space in windows PC using Win APIs <p>I am wring a C++ code to determine the available free disk space in PC running Windows 10. I have tried a Win API GetDiskFreeSpaceEx which returns the free space size of one particular drive at a time. Is there any API or a way to get the total amount of free space available in my PC.</p>
<p>Try below code, which gives you available system memory:</p> <pre><code>MEMORYSTATUSEX stex; stex.dwLength=sizeof(stex); GlobalMemoryStatusEx(&amp;stex); </code></pre> <p>stex will have total physical, available physical, total page file,total virtual, available virtual memories....</p> <p>Below is documentation <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx</a></p>
Python PIL image warping / Affine transformations <p>Using Python PIL I want to transform input images in such a way that they seem to be in perspective. Most of the answers I have found are about rotating etc. The images below show one of the effects I am aiming at. Similarly I would like to do this not only from front to back, but also from left to right and vice versa. Another effect I would like is to warp the image in a way that the center is closer and the edges are more distant.</p> <p>How should I call <code>im.transform</code> to get this effect? And why? </p> <p>Input Image:</p> <p><a href="http://i.stack.imgur.com/dHGcB.png" rel="nofollow"><img src="http://i.stack.imgur.com/dHGcB.png" alt="Input Image"></a></p> <p>Output Effect:</p> <p><a href="http://i.stack.imgur.com/GicNm.png" rel="nofollow"><img src="http://i.stack.imgur.com/GicNm.png" alt="Ouput Image"></a></p>
<p>I believe you are looking for <a href="https://en.wikipedia.org/wiki/3D_projection" rel="nofollow">perspective transformations</a>. You can do it with Pillow in following way:</p> <pre><code>transformed = image.transform( image.size, Image.PERSPECTIVE, [ a0, a1, a2, a3, a4, a5, a6, a7 ], Image.BILINEAR ) </code></pre> <p>Where a0-a7 is coefficients used for transformation in this way (from sources, Geometry.c):</p> <pre><code>xout = (a0 * xin + a1 * yin + a2) / (a6 * xin + a7 * yin + 1); yout = (a3 * xin + a4 * yin + a5) / (a6 * xin + a7 * yin + 1); </code></pre>
ng2-datepicker isn't working <p>I am trying to use <a href="https://www.npmjs.com/package/ng2-datepicker" rel="nofollow">ng2-datepicker</a> in my Angular 2 app. I followed the instructions given in the above page but the date-picker is not showing up. The console logs following error.</p> <pre><code>url_resolver.js:248 Uncaught TypeError: uri.match is not a function </code></pre> <p>My <strong>app.module.ts</strong></p> <pre><code>import { DatePicker } from 'ng2-datepicker/ng2-datepicker'; @NgModule({ declarations: [ AppComponent, DatePicker ], </code></pre> <p><strong>app.component.html</strong></p> <pre><code>&lt;datepicker [(ngModel)]="date" [expanded]="true"&gt;&lt;/datepicker&gt; </code></pre> <p><strong>Angular version 2.0.0</strong></p> <p><strong>package.json</strong></p> <pre><code>"dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/core": "2.0.0", "@angular/forms": "2.0.0", "@angular/http": "2.0.0", "@angular/platform-browser": "2.0.0", "@angular/platform-browser-dynamic": "2.0.0", "@angular/router": "3.0.0", "@material2-extra/calendar": "0.0.14-1", "core-js": "^2.4.1", "moment": "^2.15.1", "ng2-datepicker": "^1.1.0", "rxjs": "5.0.0-beta.12", "ts-helpers": "^1.1.1", "zone.js": "^0.6.23" }, </code></pre> <p>Any suggestions ?</p> <p>Thank You</p>
<p><a href="https://github.com/angular/material2/issues/974" rel="nofollow">https://github.com/angular/material2/issues/974</a></p> <p>What is the module builder, that use?</p> <p>don't use module.id in the component.</p>
"Potential Infinite Loop" Confusion <p>When I run the below function I get this error:</p> <p>"Error: Potential infinite loop."</p> <p>The problem seems to be the "0" I use in the splice method, because when I change it to any other number (1 - 9) I don't get this error. </p> <p>I'm not sure how this would create an infinite loop. </p> <p>Is the "0" I'm using in the splice method getting confused with "i" or something? </p> <p>Help is greatly appreciated, thank you.</p> <pre><code>function spinalCase(str) { var array = str.split(""); for (i = 0; i &lt; array.length; i++) { if (array[i] !== array[i].toLowerCase()) { array.splice(i, 0, " "); } } return array; } spinalCase('AllThe-small Things'); </code></pre>
<p><code>array.splice(i, 0, " ");</code> says to insert a new element at the current <code>i</code> index. Which means the item that was at <code>i</code> gets pushed up to be at <code>i + 1</code>. So then on the next iteration of the loop you process that same item again, resulting in another insert, etc., forever.</p> <p>You could increment <code>i</code> an extra time inside the <code>if</code> block, but I prefer to loop <em>backwards</em>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function spinalCase(str) { var array = str.split(""); for (i = array.length - 1; i &gt;= 0; i--) { if (array[i] !== array[i].toLowerCase()) { array.splice(i, 0, " "); } } return array; } console.log(spinalCase('AllThe-small Things'));</code></pre> </div> </div> </p>
Sorting by maximum value and display a different column than the one used for sorting <p>I have data in a file that looks like :</p> <pre><code>id Name records 1 joe 3 1 james 4 1 jacky 4 2 mike 10 2 mat 8 2 peter 10 3 bob 3 3 alice 1 3 wis 1 </code></pre> <p>All records with the same id belongs to one person but the names may be different. I need to find the id with maximum records . In the above eg id 2 has records equal to 10+8+10 = 28 and is the maximum value as compared to other ids. So the result of my query should be any one of the given names i.e either mike or mat or peter,I need to this using awk;</p> <p>I tried the following:</p> <pre><code>awk '{arr[$1]+=$3} END {for (i in arr){if(arr[i]&gt;max) max=arr[i] ; name=i} } END {print name}' </code></pre>
<p>A couple of issues:</p> <ul> <li>you aren't ignoring the header row</li> <li>you aren't saving the name (<code>$2</code>) anywhere,</li> <li>you have 2 <code>END</code>s.</li> </ul> <p>I think you want this:</p> <pre><code>awk 'NR&gt;1{count[$1]+=$3;name[$1]=$2;} END{for(i in count){if(count[i]&gt;m){m=count[i]; n=name[i]}};print m,n}' file 28 peter </code></pre>
CPython 2.7 + Java <p>My major program is written in Python 2.7 (on Mac) and need to leverage some function which is written in a Java 1.8, I think CPython cannot import Java library directly (different than Jython)?</p> <p>If there is no solution to call Java from CPython, could I integrate in this way -- wrap the Java function into a Java command line application, Python 2.7 call this Java application (e.g. using <code>os.system</code>) by passing command line parameter as inputs, and retrieve its console output?</p> <p>regards, Lin</p>
<ul> <li>If you have lot of dependcieis on Java/JVM, you can consider using <code>Jython</code>.</li> <li>If you would like to develop a scalable/maintainable application, consider using microservices and keep Java and Python components separate.</li> <li>If your call to Java is simple and it is easy to capture the output and failure, you can go ahead with this running the system command to invoke Java parts.</li> </ul>
Converting a JObject to a dynamic object <p>I'm using a library developed by another developer in our company. One of the calls in this library returns a JObject. What I need to do is convert this JObject to a dynamic object and return it to my caller. </p> <p>I've found lots of answers to create a dynamic with NewtonSoft JSON.Net but all the answers use JsonConvert.DeserializeObject which is not applicable in my case as I already have a JsonObject in hand.</p> <p>Any solutions?</p>
<p>Well, I don't really understand your problem, but you can convert it like this:</p> <pre><code>dynamic result = yourJobject; </code></pre>
How to set default value of a new attribute for earlier items in dynamodb table? <p>I have a table with only hash key, now use case requires to create a GSI with creationDate as range key.</p> <p>I am achieving this by specifying creationDate value as a number in all new items.</p> <p>But the table already has about 5000 entries with no value set for creationDate and those entries are not included in the result of scan or query operation on GSI. As a solution to this I want to use a default value for all entries with currently no value for creationDate. How do I do this using dynamodbmapper in Java, or is there a way to do it using AWS console ?</p>
<p>The existing items have to be updated individually. </p> <ul> <li>DynamoDB API doesn't allow to update item without the Hash key value either using <strong>UpdateItemSpec</strong> or <strong>DynamoDBMapper</strong></li> <li>DynamoDB doesn't have a feature to default some value when the new attribute is added to the table using <strong>UpdateTableSpec</strong> class</li> </ul> <p><strong>Update the item if the attribute doesn't exists for the given Hash key:-</strong></p> <blockquote> <p>If the attribute already exists, the following example does nothing; otherwise it sets the attribute to a default value.</p> </blockquote> <pre><code> UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("orderId", "75246c41-02c7-48c4-8d4c-d202483e6d2b") .withReturnValues(ReturnValue.ALL_NEW).withUpdateExpression("set #createDate = if_not_exists (#createDate, :val1)") .withNameMap(new NameMap().with("#createDate", "createDate")) .withValueMap(new ValueMap().withNumber(":val1", 1)); UpdateItemOutcome outcome = table.updateItem(updateItemSpec); </code></pre>
How do i use the OnTriggerExit function and check inside if my ship collided? <p>I want to check if my ship/s collided and not some other objects. So this is the script that i attached to a GameObject and the GameObject have box collider and Rigidbody. The box collider: Is Trigger set to on. And he size is 500 600 500. The Rigidbody i didn't change anything and Use Gravity is on.</p> <p>When running the game i have many cloned gameobjects each one Tagged as "Sphere" but in the script when i check the tag name the collider is "Untagged".</p> <p>What i'm trying to do is to make sure the collided object is a cloned spaceship.</p> <pre><code>using UnityEngine; using System.Collections; public class InvisibleWalls : MonoBehaviour { public float smooth = 1f; private Vector3 targetAngles; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerExit(Collider other) { if (other.tag == "Sphere") { targetAngles = other.transform.eulerAngles + 180f * Vector3.up; other.transform.eulerAngles = Vector3.Lerp (other.transform.eulerAngles, targetAngles, smooth * Time.deltaTime); } } } </code></pre> <p>This is the part where i'm trying to check and make that a ship is collided:</p> <pre><code>if (other.tag == "Sphere") </code></pre> <p>But when using break point it does stop on this line when the pbject collided but the other.tag the tag is "Untagged".</p> <p>Screenshot showing the object spaceship cloned that is tagged as "Sphere"</p> <p><a href="http://i.stack.imgur.com/2s38Z.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/2s38Z.jpg" alt="Sphere Tag"></a></p> <p>And this screenshot showing the gameobject with the box collider and the rigidbody</p> <p><a href="http://i.stack.imgur.com/60RNP.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/60RNP.jpg" alt="Collider gameobject"></a></p>
<p>From what i can gather,</p> <p>You CrashLandedShip objects do not have colliders, adding colliders should work.</p> <p>Also note that for triggers to work, One of the objects (the terrain or the ship) has to be a non-trigger (2 triggers will not cause a collision or trigger event)</p> <p>So try this : Add a sphere collider to your <code>CrashLandedShip_UpsideDown</code> prefab and make sure they are <strong>not</strong> set with IsTrigger</p> <p>The rest of your code looks fine.</p>
Aggregate match pipeline not equal to in MongoDB <p>I am working on an aggregate pipeline for MongoDB, and I am trying to retrieve items where the user is not equal to a variable.</p> <p>For some reason, I couldn't make it work. I tried to use <code>$not</code>, <code>$ne</code> and <code>$nin</code> in different possible way but can't make it to work.</p> <p>This is how it looks like:</p> <p>Data sample:</p> <pre><code>[{ "_id": { "$oid": "565674e2e4b030fba33d8fdc" }, "user": { "$oid": "565674832b85ce78732b7529" } }, { "_id": { "$oid": "565674e2e4b030fba33d8fdc" }, "user": { "$oid": "565674832b85ce78732b7529" } }, { "_id": { "$oid": "565674e2e4b030fba33d8fdc" }, "user": { "$oid": "56f9dfc5cc03ec883f7675d0" } }] </code></pre> <p>Pipeline sample (simplified for this question):</p> <p>Where <code>req.query.user.id = "565674832b85ce78732b7529"</code></p> <pre><code>collection.aggregate([ { $match: { user: { $nin: [ req.query.user.id ], } } } ] </code></pre> <p>This should return only the last item.</p> <p>Do you have any idea how to retrieve the data that doesn't match the user?</p> <p>Thanks</p> <p><strong>Edit:</strong> The following doesn't work either:</p> <pre><code>collection.aggregate([ { $match: { 'user.$oid': { $nin: [ req.query.user.id ], } } } ]); </code></pre> <p>I also tried with <code>ObjectID()</code> and mongodb complains: <code>[MongoError: Argument must be a string]</code></p> <pre><code>var ObjectID = require('mongodb').ObjectID; // Waterline syntax here MyCollection.native(function (err, collection) { collection.aggregate([ { $match: { 'user': { $nin: [ ObjectID(req.query.user.id) ], } } } ], function (err, result) { console.log(err, result); }); }); </code></pre> <p>But this line works in the shell:</p> <pre><code>db.collection.aggregate([{$match:{"user":{"$nin":[ObjectId("565674832b85ce78732b7529")]}}}]) </code></pre>
<p>Based on the answer <a href="http://stackoverflow.com/a/38606392/1611791">here</a>, you can change</p> <pre><code>var ObjectId = require('mongodb'). ObjectID; </code></pre> <p>to </p> <pre><code>var ObjectId = require('sails-mongo/node_modules/mongodb').ObjectID; </code></pre>
JAX-RS does not work with Spring Boot 1.4.1 <p>I am trying to develop a simple JAX-RS based web service using Spring Boot version 1.4.1.RELEASE. However getting this exception - </p> <pre><code>java.lang.IllegalStateException: No generator was provided and there is no default generator registered at org.glassfish.hk2.internal.ServiceLocatorFactoryImpl.internalCreate(ServiceLocatorFactoryImpl.java:308) ~[hk2-api-2.5.0-b05.jar:na] at org.glassfish.hk2.internal.ServiceLocatorFactoryImpl.create(ServiceLocatorFactoryImpl.java:268) ~[hk2-api-2.5.0-b05.jar:na] at org.glassfish.jersey.internal.inject.Injections._createLocator(Injections.java:138) ~[jersey-common-2.23.2.jar:na] at org.glassfish.jersey.internal.inject.Injections.createLocator(Injections.java:123) ~[jersey-common-2.23.2.jar:na] at org.glassfish.jersey.server.ApplicationHandler.&lt;init&gt;(ApplicationHandler.java:330) ~[jersey-server-2.23.2.jar:na] at org.glassfish.jersey.servlet.WebComponent.&lt;init&gt;(WebComponent.java:392) ~[jersey-container-servlet-core-2.23.2.jar:na] at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177) ~[jersey-container-servlet-core-2.23.2.jar:na] at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369) ~[jersey-container-servlet-core-2.23.2.jar:na] </code></pre> <p>Here are my program details -</p> <p>Dependencies included in POM.xml -</p> <pre><code>&lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-jersey&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>And here is JerseyConfig file - </p> <pre><code>package com.test.main; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; import com.test.resources.TutorialResource; @Component public class JerseyConfig extends ResourceConfig{ public JerseyConfig() { register(TutorialResource.class); packages("com.test.resources"); } } </code></pre>
<h2>The layout of the JAR has changed in Spring Boot 1.4.1</h2> <p>The <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.4-Release-Notes#executable-jar-layout" rel="nofollow">layout of executable jars has changed</a> in Spring Boot 1.4.1: application’s dependencies are now packaged in <code>BOOT-INF/lib</code> rather than <code>lib</code>, and application’s own classes are now packaged in <code>BOOT-INF/classes</code> rather than the root of the jar. And it affects Jersey:</p> <blockquote> <p><a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.4-Release-Notes#jersey-classpath-scanning-limitations" rel="nofollow"><strong>Jersey classpath scanning limitations</strong></a></p> <p>The change to the layout of executable jars means that a <a href="https://java.net/jira/browse/JERSEY-2085" rel="nofollow">limitation in Jersey’s classpath scanning</a> now affects executable jar files as well as executable war files. To work around the problem, classes that you wish to be scanned by Jersey should be packaged in a jar and included as a dependency in <code>BOOT-INF/lib</code>. The Spring Boot launcher should then be <a href="http://docs.spring.io/spring-boot/docs/1.4.x/reference/htmlsingle/#howto-extract-specific-libraries-when-an-executable-jar-runs" rel="nofollow">configured to unpack those jars on start up</a> so that Jersey can scan their contents.</p> </blockquote> <p>I've found that registering classes instead of packages works. See below the steps to create an application with Spring Boot and Jersey.</p> <h2>Creating web application with Spring Boot and Jersey</h2> <p>Ensure your <code>pom.xml</code> file declares <code>spring-boot-starter-parent</code> as the parent project:</p> <pre class="lang-xml prettyprint-override"><code>&lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.4.1.RELEASE&lt;/version&gt; &lt;/parent&gt; </code></pre> <p>You also need the following dependencies:</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-jersey&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>And the Spring Boot Maven plugin:</p> <pre class="lang-xml prettyprint-override"><code>&lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>For example purposes, create a Jersey resource class annotated with <a href="https://jersey.java.net/apidocs/2.23/jersey/javax/ws/rs/Path.html" rel="nofollow"><code>@Path</code></a> and define a resource method to handle <code>GET</code> requests, producing <a href="https://jersey.java.net/apidocs/2.23/jersey/javax/ws/rs/core/MediaType.html#TEXT_PLAIN" rel="nofollow"><code>text/plain</code></a>:</p> <pre class="lang-java prettyprint-override"><code>@Path("/greetings") public class GreetingResource { @GET @Produces(MediaType.TEXT_PLAIN) public Response getGreeting() { return Response.ok("Hello, World!").build(); } } </code></pre> <p>Then create a class that extends <a href="https://jersey.java.net/apidocs/2.23/jersey/org/glassfish/jersey/server/ResourceConfig.html" rel="nofollow"><code>ResourceConfig</code></a> or <a href="https://jersey.java.net/apidocs/2.23/jersey/javax/ws/rs/core/Application.html" rel="nofollow"><code>Application</code></a> to register the Jersey resources and annotated it with <a href="https://jersey.java.net/apidocs/2.23/jersey/javax/ws/rs/ApplicationPath.html" rel="nofollow"><code>@ApplicationPath</code></a>. Registering classes instead of registering packages works with Spring Boot 1.4.1:</p> <pre class="lang-java prettyprint-override"><code>@Component @ApplicationPath("api") public class JerseyConfig extends ResourceConfig { @PostConstruct private void init() { registerClasses(GreetingResource.class); } } </code></pre> <p>And finally create a Spring Boot class to execute the application:</p> <pre class="lang-java prettyprint-override"><code>@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } </code></pre> <p>If you want to test this web service, you can use the <a href="https://jersey.java.net/apidocs/2.23/jersey/javax/ws/rs/client/package-summary.html" rel="nofollow">JAX-RS Client API</a>:</p> <pre class="lang-java prettyprint-override"><code>@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class GreetingResourceTest { @LocalServerPort private int port; private URI uri; @Before public void setUp() throws Exception { this.uri = new URI("http://localhost:" + port); } @Test public void testGreeting() { Client client = ClientBuilder.newClient(); Response response = client.target(uri).path("api").path("greetings") .request(MediaType.TEXT_PLAIN).get(); String entity = response.readEntity(String.class); assertEquals("Hello, World!", entity); } } </code></pre> <p>To compile and run the application, follow these steps:</p> <ul> <li>Open a command line window or terminal.</li> <li>Navigate to the root directory of the project, where the <code>pom.xml</code> resides.</li> <li>Compile the project: <code>mvn clean compile</code>.</li> <li>Package the application: <code>mvn package</code>.</li> <li>Look in the target directory. You should see a file with the following or a similar name: <code>spring-jersey-1.0-SNAPSHOT.jar</code>.</li> <li>Change into the target directory.</li> <li>Execute the JAR: <code>java -jar spring-jersey-1.0-SNAPSHOT.jar</code>.</li> <li>The application should available at <code>http://localhost:8080/api/greetings</code>.</li> </ul> <p>When producing JSON, ensure you have a <a href="http://stackoverflow.com/a/38866558/1426227">JSON provider registered</a>.</p>
Orders of growth involving both recursion and two inner for loops <p>I have attempted the below question but I am uncertain whether I am correct or not. I have arrived at the conclusion that it is a big theta of n^2 function. My reasoning is that the inner 2 loops for i and for j will amount to a sequence of operations, 0, 1, 2, 3, 4, 5....x -1, which can be translated into (x * x - 1) /2 by the arithmetic operation. However, the outer recursive call kind of trips me up. I am tempted to look at the outer recursive call as yet another while loop but I fought it off because it isn't exactly another while loop or for loop because x also changes. Can someone help me arrive at a better understanding of the below question? </p> <pre><code> def foo(x): if x &lt; 1: return 'boo' for i in range(x): for j in range(i): return foo(i + j) return foo(x-1) </code></pre> <p>REVISION: I just ran this code through my python interpreter and turns out it will be constant time as it is a trick question. The reason being, the return statement will just evaluate to foo(1), and then 'boo' gets outputted no matter what size of n you are at. </p> <p>But----> What if I were to change my code to the following. Is the run time now theta(n^2) or theta(n^3)? </p> <pre><code> def foo(x): if x &lt; 1: return 'boo' for i in range(x): for j in range(i): print(i + j) return foo(x-1) </code></pre>
<p><strong>EDIT:</strong> First there was <code>i+i</code> in question but now there is <code>i+j</code> so now my answer is wrong.</p> <hr> <p>When <code>x &lt; 1</code> it prints 'boo' - nothing intersting.</p> <p>When <code>x &gt;= 1</code> then you can reach loops</p> <pre><code>for i in range(x): for j in range(i): return foo(i+i) </code></pre> <p>so let <code>x = 1</code> and you have</p> <pre><code>for i in range(1): for j in range(i): return foo(i+i) </code></pre> <p>so let <code>i = 0</code> - and you have </p> <pre><code> for j in range(0): </code></pre> <p>and it will newer run </p> <p>so let <code>i = 1</code> - and you have </p> <pre><code> for j in range(1): </code></pre> <p>and for <code>j = 0</code> you can run </p> <pre><code> return foo(2) </code></pre> <p>and you return to the beginnig of this description.<br> And you will again get <code>return foo(2)</code>. Check it on your own. </p> <p>So for 'x >= 1' you always get <code>return foo(2)</code>.<br> So you can reduce this code to </p> <pre><code>def foo(x): if x &lt; 1: return 'boo' return foo(2) </code></pre> <p>(you will never reach <code>return foo(x-1)</code>)</p> <p>You have infinite function.</p> <p>(I hope I'm right)</p>
jQuery append() not working for concatenated String <p>(Full code below)</p> <p>This</p> <pre><code>$('#' + id).parent().append('&lt;div id="pop-up"&gt;hello&lt;/div&gt;'); </code></pre> <p>does work. But this</p> <pre><code>$('#' + id).parent().append('&lt;div id="pop-up-' + id + '"&gt;hello&lt;/div&gt;'); </code></pre> <p>doesn't.</p> <p>The fact that the first version works lets me assume that the problem is not the <code>id</code> variable...</p> <p>So the full code is</p> <pre><code>function clickOnElement(id) { var obj = {}; obj.clicked = String(id); var jsonData = JSON.stringify(obj); $.ajax({ type: 'POST', url: '../db/RequestHandler.ashx', data: jsonData, contentType: 'application/json; charset-utf-8', success: function (response) { // Add the div for the dialog-box $('&lt;div&gt;Hello&lt;/div&gt;', { "id": "pop-up" + id }).appendTo($('#' + id).parent()); }, error: function () { console.log("request error"); } }); } </code></pre>
<p>Use <strong><a href="http://api.jquery.com/appendto/" rel="nofollow">.appendTo()</a></strong></p> <ul> <li>The <code>.append()</code> and <code>.appendTo()</code> methods perform the same task.</li> <li>The major difference is in the syntax-specifically, in the placement of the content and target. </li> <li>With .append(), the selector expression preceding the method is the container into which the content is inserted. </li> <li>With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.</li> </ul> <p><strong>Code Example</strong></p> <pre><code>$('&lt;div&gt;Hello&lt;/div&gt;', { "id": "pop-up" + id }).appendTo($('#' + id).parent()); </code></pre> <p>FYI, </p> <p>Please make sure the element exists in the DOM and you're appending it in correct selector.</p> <p>Hope this helps.</p>
strange syntax error in node-apn library <p>I am trying to implement push notification server with nodejs. I downloaded node-apn library and tried to initiate sample code. When I run sample code file, I got an error "unexpected syntax token ,". So I looked code line where syntax error occurs.</p> <pre><code>const Endpoint = require("./lib/protocol/endpoint")({ tls, protocol, }); </code></pre> <p>This seems strange syntax but everybody else use node-apn library fine except me. I get syntax error if includes only one line of code below.</p> <p>require("apn");</p> <p>is there anyone who experienced this? or is there anybody who successfully implemented this node-apn library? any assistance will be appreciated. thanks in advance.</p>
<p>That's ES6 code for an <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer" rel="nofollow">object initializer</a> and it's shorthand for:</p> <pre><code>const Endpoint = require("./lib/protocol/endpoint")({ tls: tls, protocol: protocol, }); </code></pre> <p>If you're using an older version of Node, which comes with an older version of V8, you may have syntax errors.</p>
stop animation when button pressed <p>in my app I have a button and set below animation to it</p> <pre><code>&lt;set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/bounce_interpolator" &gt; &lt;scale android:duration="2000" android:fromXScale="0.9" android:toXScale="1.0" android:fromYScale="0.9" android:toYScale="1.0" android:pivotX="50%" android:pivotY="50%" android:repeatCount="infinite" /&gt; &lt;/set&gt; </code></pre> <p>by this java code:</p> <pre><code> myAnim = AnimationUtils.loadAnimation(this, R.anim.anim_button); Button myButton = (Button) findViewById(R.id.run_button); myButton.setAnimation(myAnim); myButton.startAnimation(myAnim); </code></pre> <p>now I want when button is focused (or pressed) the animation stopped and the size of my button reduced (for example from width 120dp to width 100dp) how can I do it? also I set below XML for my button</p> <pre><code>&lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:drawable="@drawable/ic_button_focuses" android:state_pressed="true" android:state_enabled="true"/&gt; &lt;item android:drawable="@drawable/ic_button_focuses" android:state_focused="true" android:state_enabled="true"/&gt; &lt;item android:drawable="@drawable/ic_button" /&gt; &lt;/selector&gt; </code></pre>
<p>in your java code to stop the animation</p> <pre><code>myButton.clearAnimation(); myButton.clearFocus(); </code></pre> <p>to resize your button</p> <pre><code>myButton.setLayoutParams(new LinearLayout.LayoutParams(10, 100)); </code></pre> <p>hope this may help you.!</p>
Converting RAW byte data to Bitmap <p>I am taking a screenshot of an android device using ADB and receiving the screenshot as raw byte data.</p> <p>I know the raw byte data coming through is in the format rgba</p> <p>Red is offset 0, Green offset 8, Blue offset 16, Alpha offset 24, each value is 1 byte. This makes up the entire byte array.</p> <p>I am trying to convert this byte array to a Bitmap in C# and it is working for the most part, the image looks correct in every way apart from the fact that it is coming through with a 'blue hue' -- the coloring is off.</p> <p>The following is the code I'm using to convert my raw byte data:</p> <pre><code>int WriteBitmapFile(string filename, int width, int height, byte[] imageData) { using (var stream = new MemoryStream(imageData)) using (var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb)) { BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); IntPtr pNative = bmpData.Scan0; Marshal.Copy(imageData, 0, pNative, imageData.Length); bmp.UnlockBits(bmpData); bmp.Save(filename); } return 1; } </code></pre> <p>I've read in <a href="http://stackoverflow.com/questions/8104461/pixelformat-format32bppargb-seems-to-have-wrong-byte-order" title="this post">this post</a> that it could be to do with the byte order of the actual rgba values. As you can see in the code above, I tried casting my bmpData.Scan0 to int* and it is still coming through with a blue hue.</p> <p>I'm wracking my brain as to what I can do now to get this image to come through with the correct colors. I'm assuming it's reading red as blue and blue as red or vice versa.</p> <p>I thought I could manipulate the raw byte data so that it is in the correct byte order when converting it to a bitmap, however I'm not sure how I can go about doing that.</p> <p>Any suggestions?</p>
<p>Did you have a look at this <a href="http://stackoverflow.com/questions/32513379/how-to-record-screen-and-take-screenshots-using-android-api">post</a> ? You're stating that every 'value' is 8 bytes, so 1 pixel is 4x8 = 32 bytes? But you are using 32bpp image format, so 32 bits per pixel -> 1 pixel = 4 bytes.</p> <p>Also pay attention to little/big endian, if you're acquiring the image from another processor/network/...</p>
How to send interrupt/ ctrl C during execution of expect script <p>I am trying to execute some commands and one of which will not come back to console and need to explicitly bring it using ctrl+ c. After that I need to execute some more commands in that script. </p> <pre><code>expect "$ " send "sh /root/jboss-eap-6.3/bin/standalone.sh\r" set timeout 10 expect "$ " </code></pre> <p>I have to run other commands after executing standalone.sh script. But it will hold and not come back to console. I tried </p> <pre><code>trap { send \x03 send_user "You pressed Ctrl+C\n" } SIGINT </code></pre> <p>. But that also didn't worked. </p> <p>Thanks in advance.</p>
<p>There are all sorts of ways to kill a process in <code>bash</code>. If you by some chance know the name of your (jboss eap) process you could run <code>pkill processName</code>, <code>killall processName</code> or <code>kill pidof processName</code> instead of trying to send key-strokes.</p>
Join two objects by key <p>I stuck on mergin 2 objects into one. Let's say I have 2 arrays of objects: One is childs:</p> <pre><code>let childsWithMoreInfo = [{ id: 1, name: 'somename', parent: { id: 2 }, }, { id: 2, name: 'some child name', parent: { id: 4 } }]; </code></pre> <p>And the second one is Parents:</p> <pre><code>let parents = [{ id: 1, parentName: 'The first', child: {} }, { id: 2, parentName: 'The second', child: {} }, { id: 3, parentName: 'The third', child: {} }, { id: 4, parentName: 'The fourth', child: {} }]; </code></pre> <p>And I would to merge these objects like this:</p> <pre><code> let combined = [ { id: 1, parentName: The first, child: {} }, { id: 2, parentName: The second, child: { id: 1, name: somename, } }, { id: 3, parentName: The third, child: {} }, { id: 4, parentName: The fourth, child: { id: 2 name: some child name, } }, ] ]; </code></pre> <p>So basically it should be something like: <code>let combinedList = parents.child = childsWithMoreInfo where parents.id = childsWithMoreInfo.parent.id</code> . On which method I should take a look? Do you have any ideas how can easily achieve that?</p>
<p>I really know how to use forEach, I wanted to avoid it.</p> <p>This is what I made:</p> <pre><code> this.combined = _.map(parents, (parent) =&gt; { parent.child = childs.find(child =&gt; child.parent.id === parent.id); return parent; }); </code></pre> <p>Thank you for all of your answers.</p>
android studio Error:Unable to start the daemon process <p>Version of Android Studio 2.2 OS version: Windows 10 Java JRE/JDK version: 1.8.0_51</p> <blockquote> <p>Error:Unable to start the daemon process. This problem might be<br> caused by incorrect configuration of the daemon. For example, an<br> unrecognized jvm option is used. Please refer to the user guide<br> chapter on the daemon at<br> <a href="https://docs.gradle.org/2.14.1/userguide/gradle_daemon.html" rel="nofollow">https://docs.gradle.org/2.14.1/userguide/gradle_daemon.html</a> Please<br> read the following process output to find out more:<br> ----------------------- Error occurred during initialization of VM Could not reserve enough space for 1572864KB object heap</p> </blockquote>
<p>Try deleting your <strong>.gradle</strong> from <code>C:\Users\&lt;username&gt;</code> directory and try again.</p>
How can I change SharedSection in registry using NSIS? <p>Regarding to <a href="http://stackoverflow.com/questions/24382462/how-can-i-change-sharedsection-in-registry-using-c">this stackoverflow entry</a> in need to implement this functionality for a nsis update.</p> <p>In the registry <code>System\\CurrentControlSet\\Control\\Session Manager\\SubSystems</code> I have to change the <code>windows</code> > string parameter <code>SharedSection=1024,20480,768</code> value. The third value <strong>768</strong> needs to be increased up to <strong>1536</strong>.</p> <p>With the basic <code>WriteRegStr</code> and <code>ReadRegStr</code> functions i am not able to do this.</p>
<p>The registry functions cannot perform string manipulation. If you need to manipulate a string you can take a look at some of the helper macros that ship with NSIS or write your own.</p> <p>I ended up with a hybrid that does a bit of both:</p> <pre><code>!include LogicLib.nsh !include StrFunc.nsh ${StrLoc} Section ReadRegStr $0 HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems" "Windows" ${StrLoc} $7 $0 "SharedSection=" "&gt;" ; Find "SharedSection=" StrCpy $R1 $0 $7 ; Save the stuff before "SharedSection=" StrCpy $R2 $0 "" $7 ${StrLoc} $8 $R2 " " "&gt;" ; Find the end of "SharedSection=#,#,#" by looking for a space ${IfThen} $8 = 0 ${|} StrLen $8 $R2 ${|} StrCpy $R3 $R2 "" $8 ; Save the stuff after "SharedSection=#,#,#" StrCpy $R2 $0 $8 $7 ; Save "SharedSection=#,#,#" ; We can now parse "SharedSection=#,#,#": StrLen $8 $R2 findcomma: IntOp $8 $8 - 1 StrCpy $1 $R2 1 $8 StrCmp $1 "," findcomma_end StrCmp $1 "" findcomma_end findcomma findcomma_end: IntOp $9 $8 + 1 StrCpy $2 $R2 "" $9 ${If} $1 != "" ; Only edit if we found the comma.. ${AndIf} $2 != "" ; ..And there was something after the comma StrCpy $R2 $R2 $8 ; Copy the first part of the string StrCpy $R2 "$R2,1536" ; Append the final comma and number ${EndIf} StrCpy $0 "$R1$R2$R3" ; Build the final string DetailPrint Result=$0 # TODO: WriteRegStr HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems" "Windows" $0 SectionEnd </code></pre>
Visual Studio crashes on 'add reference' <p>Visual Studio crashes when opening any solution and right-clicking 'references' and choosing 'add reference'. The dialog opens for a few seconds, VS crashes and restarts. Tried uninstalling and reinstalling VS2013, then uninstalling again with VS Uninstaller and reinstalling, and installing VS2015. Problem persists on both new installations. Had Beckhoff TwinCAT 3.1 installed but uninstalled also this before first reinstalling Visual Studio, to no avail.</p> <p>Is there a registry key or specific locations where all VS installations look for packages?</p>
<p>This was solved by doing another reinstall of Visual Studio, but this time cleaning remnants manually. VS Uninstaller <strong>DOES NOT</strong> do a complete uninstall.</p>
MySQL php login <p>I am try to check if an activation link is valid or invalid, however I am always getting the $activated_message from my code even if the activation token or email is incorrect. What's wrong with my sql statement or functions? Thanks</p> <pre><code>&lt;?php include("mysql_functions.php"); // Check if all fields are not empty. if (!empty($_GET['email']) &amp;&amp; !empty($_GET['activation_token'])) { // MySQL database select query. $mysql_select_query = "SELECT * FROM Accounts WHERE email='" . $_GET['email'] . "' AND activation_token='" . $_GET['activation_token'] . "' AND activated='0' LIMIT 1"; // Execute the MySQL database select query and check if POST password matches MySQL database hashed password. if(mysql_execute_query($mysql_server, $mysql_username, $mysql_password, $mysql_database_name, $mysql_select_query, false)) { // Valid activation link. // MySQL database update query. $mysql_update_query = "UPDATE Accounts SET activated='1' WHERE email='" . $_GET['email'] . "' AND activation_token='" . $_GET['activation_token'] . "' AND activated='0' LIMIT 1"; // Execute the MySQL database update query to activate the account and check if it is successful. if (mysql_execute_query($mysql_server, $mysql_username, $mysql_password, $mysql_database_name, $mysql_update_query, false)) { // The account was successfully activated. echo $activated_message; } else { echo $not_activated_message; } } else { // Invalid activation link. echo $invalid_activation_link; } } else { echo $not_activated_message; } // ------------------------ FUNCTION: MYSQL QUERY EXECUTOR ----------------------- // Function for executing MySQL queries. function mysql_execute_query($mysql_server, $mysql_username, $mysql_password, $mysql_database_name, $mysql_query, $return_mysql_query_result_boolean) { // Create the MySQL database connection. $mysql_database_connection = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database_name); // Check if connected to MySQL database. if ($mysql_database_connection) { // Connected to the MySQL database. // Execute the MySQL query. if ($mysql_query_result = mysqli_query($mysql_database_connection, $mysql_query)) { // MySQL query has executed successfully. // Check if any data needs to be returned. if ($return_mysql_query_result_boolean) { // Get an associated array from the MySQL result. $mysql_query_result = mysqli_fetch_assoc($mysql_query_result); } // Close the MySQL database connection. mysqli_close($mysql_database_connection); // Return the MySQL query result. return $mysql_query_result; } else { // MySQL query has not executed successfully. echo "Error: " . mysqli_error($mysql_database_connection); return false; } } else { // Could not connect to the MySQL database. die("Error connecting to MySQL database: " . mysqli_connect_error()); return false; } } </code></pre> <p>?></p>
<p>The problem is in the fact that <code>mysql_execute_query</code> always returns a result that resolves to <code>TRUE</code> when the given query is correct.</p> <p>You should read the results of the select statement, and base your logic on that, not on the fact that the query worked or not.</p> <p>That being said, there is a lot wrong with your code:</p> <ul> <li>the nested-if structure in your main code is not very readable or maintanable</li> <li>you are open to SQL injection attacks, check out <a href="https://en.wikipedia.org/wiki/Prepared_statement" rel="nofollow">prepared statements</a></li> <li>connecting to the database for each query is unnecessary</li> </ul> <p>Hope I helped you a little, good luck, and happy coding!</p>
Faster mail () php <p>So I was creating a mailing script for my customer support Basically what it's gonna be used for is when a user forgets their password a temporary password will be sent to their phone which they can use to reset their password</p> <p>The issue I'm having while testing it goes as follows</p> <p>I sent a test txt to my phone and it appeared within maybe 5mins or so</p> <p>I made some tweaks for headers in order to prevent my server domain showing as the reply email</p> <p>I sent another text and it's been at 20mins and still haven't received the text</p> <p>I'm not sure if the headers are incorrect (if they are please let me know) but even without the headers the text is still way to slow and I need to make it faster</p> <p>The text received looks like this</p> <p>`(noReply) Testing</p> <hr> <p>To report abuses or spam please follow this link: <a href="http://sp.altervista.it/s.php/a290OTB8L21vdmllSG9zdGluZy9zbXMvc21zLnBocA==" rel="nofollow">http://sp.altervista.it/s.php/a290OTB8L21vdmllSG9zdGluZy9zbXMvc21zLnBocA==</a>`</p> <p>I would also like to get rid of that line and the text below it</p> <p>To be completely clear I do not want to use phpmailer or any other third party frameworks I want to keep everything nice and neatly coded in php</p> <p>Here is my code (sorry it's messed up I'm on my phone doing this)</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;test message&lt;/title&gt; &lt;meta charset="utf-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post"&gt; &lt;input type="text" name="number" placeholder="xxx-xxx-xxxx"&gt; &lt;select name="carrier"&gt; &lt;option value="verizon"&gt;Verizon&lt;/option&gt; &lt;/select&gt; &lt;input type="text" name="message" placeholder="Message"&gt; &lt;input type="submit" name="submit" value="Send"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; &lt;? if(isset($_POST['submit'])){ $number = $_POST['number']; $carrier = $_POST['carrier']; $message = $_POST['message']; if($carrier === "verizon"){ $ext = "@vtext.com"; } $to = $number . $ext; $sub = "noReply"; $msg = $message; $headers = 'From: noReply@anon.com' . "\r\n" . 'Reply-To: noReply@anon.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to,$sub,$msg,$headers); echo "&lt;script&gt;alert('Messages sent')&lt;/script&gt;"; } ?&gt; </code></pre>
<p>If you want to keep doing it via email (which I don't reccommend), you could use <a href="http://mailgun.com" rel="nofollow">Mailgun</a>. It's by Rackspace and is incredibly easy to use. Your first 10k emails per month are free. </p> <pre><code># Include the Autoloader (see "Libraries" for install instructions) require 'vendor/autoload.php'; use Mailgun\Mailgun; # Instantiate the client. $mgClient = new Mailgun('YOUR_API_KEY'); $domain = "YOUR_DOMAIN_NAME"; # Make the call to the client. $result = $mgClient-&gt;sendMessage($domain, array( 'from' =&gt; 'Excited User &lt;mailgun@YOUR_DOMAIN_NAME&gt;', 'to' =&gt; 'Baz &lt;YOU@YOUR_DOMAIN_NAME&gt;', 'subject' =&gt; 'Hello', 'text' =&gt; 'Testing some Mailgun awesomness!' )); </code></pre> <p>This is copied from the docs and shows a basic way of sending mails. </p> <p>Check the <a href="https://documentation.mailgun.com/quickstart-sending.html#send-via-api" rel="nofollow">Mailgun Docs</a> and the <a href="https://github.com/mailgun/mailgun-php" rel="nofollow">PHP Repo</a> for more extended examples. </p> <hr> <p>If you would rather use a cloud communications provider, like <a href="http://twilio.com" rel="nofollow">Twilio</a> take a look at <a href="https://www.twilio.com/blog/2016/07/send-sms-with-php-and-twilio-in-60-seconds.html" rel="nofollow">this</a> great blog post about it. Here is the code sample:</p> <pre><code>&lt;?php require "vendor/autoload.php"; include 'settings.php'; $client = new Services_Twilio($account_sid, $auth_token); $client-&gt;account-&gt;messages-&gt;create(array( "From" =&gt; $twilio_phone_number, "To" =&gt; "13123131434", "Body" =&gt; "Whaddup from PHP!")); </code></pre>
SWI-Prolog: How to get unicode char from escaped string? <p>I have a problem, I've got an escaped string for example "\\u0026" and I need this to transform to unicode char '\u0026'.</p> <p>Tricks like string_concat('\\', S, "\\u0026"), write(S). didn't help, because it will remove \ not only the escape . So basically my problem is, how to remove escape chars from the string.</p> <p>EDIT: Oh, I've just noticed, that stackoverflow also plays with escape \.</p> <p>write_canonical/1 gives me "\\u0026", how to transform that into a single '&amp;' char?</p>
<p>In ISO Prolog a char is usually considered an atom of length 1. Atoms and chars are enclosed in single quotes, or written without quotes if possible. Here are some examples:</p> <pre><code>?- X = abc. /* an atom, but not a char */ X = abc ?- X = a. /* an atom and also a char */ X = a ?- X = '\u0061'. X = a </code></pre> <p>The \u <a href="http://stackoverflow.com/a/32100409/502187">notation</a> is SWI-Prolog specific, and not found in the ISO Prolog. In SWI-Prolog there is a data type string again not found in the ISO Prolog, and always enclosed in double quotes. Here are some examples:</p> <pre><code>?- X = "abc". /* a string */ X = "abc" ?- X = "a". /* again a string */ X = "a" ?- X = "\u0061". X = "a" </code></pre> <p>If you have a string at hand of length 1, you can convert it to a char via the predicate <a href="http://www.swi-prolog.org/pldoc/doc_for?object=atom_string/2" rel="nofollow">atom_string/2</a>. This is a SWI-Prolog specific predicate, not in ISO Prolog:</p> <pre><code>?- atom_string(X, "\u0061"). X = a ?- atom_string(X, "\u0026"). X = &amp; </code></pre> <p>Some recommendation. Start learning the ISO Prolog atom predicates first, there are quite a number. Then learn the SWI-Prolog atom and string predicates.</p> <p>You dont have to learn so many new SWI-Prolog predicates, since in SWI-Prolog most of the ISO Prolog predicates also accept strings. Here is an example of the ISO Prolog predicate atom_codes/2 used with a string in the first argument:</p> <pre><code>?- atom_codes("\u0061\u0026", L). L = [97, 38]. ?- L = [0'\u0061, 0'\u0026]. L = [97, 38]. ?- L = [0x61, 0x26]. L = [97, 38]. </code></pre> <p>P.S: The 0' notation is defined in the ISO Prolog, its neither a char, atom or string, but it represents an integer data type. The value is the code of the given char after the 0'. I have combined it with the SWI-Prolog \u notation.</p> <p>P.P.S: The 0' notation in connection of the \u notation is of course redundant, in ISO Prolog one can directly use the hex notation prefix 0x for integer values.</p>
Is there something wrong with this Rails Console error message? <p>Very new to Rails, so bear with me -</p> <p>Currently paranoid that my ruby and gem versions aren't up to date because I'd occasionally get error messages when running <code>rails test</code>. Previously had rvm and rbenv both installed, but wow I've removed both and reinstalled rvm only.</p> <p>When I go into a <code>irb</code> and call an action that doesn't work, such as: <code>"foo".select</code>, I get a simple error message:<br></p> <pre><code>NoMethodError: private method 'select' called for "foo":String from (irb):4 from /Users/Joseph/.rvm/rubies/ruby-2.3.1/bin/irb:11:in '&lt;main&gt;' </code></pre> <p>However, when I type the same command <code>"foo".select</code> in <code>rails console</code> instead, I get:</p> <pre><code>NoMethodError: private method `select' called for "foo":String from (irb):1 from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands/console.rb:65:in `start' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in `start' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:in `console' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `&lt;top (required)&gt;' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `block in require' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require' from /Users/Joseph/workspace/sample_app/bin/rails:9:in `&lt;top (required)&gt;' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `block in load' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/commands/rails.rb:6:in `call' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/command_wrapper.rb:38:in `call' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:191:in `block in serve' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:161:in `fork' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:161:in `serve' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:131:in `block in run' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:125:in `loop' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:125:in `run' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application/boot.rb:19:in `&lt;top (required)&gt;' from /Users/Joseph/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from /Users/Joseph/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from -e:1:in `&lt;main&gt;' </code></pre> <p>Is this normal? Or is there something wrong with my gems here?</p>
<p>There's nothing wrong with your gems. The thing is that when you run irb, it's just that. You only run the ruby interactive. When you run <code>rails console</code> in order to show you the console it needs to go and set it for you with ActiveRecord, rails core, etc. So this (below) is all it does before it's set.</p> <pre><code>from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands/console.rb:65:in `start' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in `start' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:in `console' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `&lt;top (required)&gt;' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `block in require' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require' from /Users/Joseph/workspace/sample_app/bin/rails:9:in `&lt;top (required)&gt;' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `block in load' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/commands/rails.rb:6:in `call' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/command_wrapper.rb:38:in `call' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:191:in `block in serve' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:161:in `fork' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:161:in `serve' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:131:in `block in run' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:125:in `loop' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application.rb:125:in `run' from /Users/Joseph/.rvm/gems/ruby-2.3.1@sample_app/gems/spring-1.7.2/lib/spring/application/boot.rb:19:in `&lt;top (required)&gt;' from /Users/Joseph/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from /Users/Joseph/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from -e:1:in `&lt;main&gt;' </code></pre> <p>Notice that irb is executed really fast, while rails console takes its time, depending on your initializers, configurations, etc.</p>
How can I redirect social URL when user clicks on social icon by php? <p>html code:</p> <pre><code>&lt;a href="http://www.facebook.com/sharer.php?u=https://simplesharebuttons.com" target="_blank"&gt;&lt;i class="fa fa-facebook"&gt;&lt;/i&gt;&lt;/a&gt; </code></pre> <p>My problem is, I want to redirect the user when the user clicks on the facebook button to its facebook URL like $facebookid = facebook URL</p>
<p>Let say you have facebook url:</p> <pre><code>$facebookid = "https://web.facebook.com/abcxyz..."; </code></pre> <p>just put it in html code:</p> <pre><code>&lt;a href="&lt;?php echo $facebookid?&gt;" target="_blank"&gt;&lt;i class="fa fa-facebook"&gt;&lt;/i&gt;&lt;/a&gt; </code></pre> <p>Hope this helps..</p>
The import org.springframework.beans.Beanutils cannot be resolved <p>I am using spring 4.3.3.RELEASE in my project.</p> <p>As per spring <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/" rel="nofollow">documentation</a> </p> <p>I can see BeanUtils is in <code>package org.springframework.beans.BeanUtils</code></p> <p>Now when I try to reference </p> <pre><code>import org.springframework.beans.BeanUtils; </code></pre> <p><a href="http://i.stack.imgur.com/HBTt8.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/HBTt8.jpg" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/UDt8c.png" rel="nofollow"><img src="http://i.stack.imgur.com/UDt8c.png" alt="enter image description here"></a></p> <p>I am getting error by eclipse </p> <blockquote> <p>The import org.springframework.beans.Beanutils cannot be resolved</p> </blockquote> <p>However when I change to <code>spring 4.2.2.RELEASE</code> it works fine?</p> <p>So my question is that since its there in <code>4.3.3</code> why its showing as error.</p>
<p>If you are building with eclipse and maven use the command as mvn eclipse:eclipse.</p>
Interacting with Gmail inbox using Selenium webdriver <p>I'm working in project where I have to buy a product from some website. I'll get a mail in Gmail I have to click on Received Email (Unread Mail) and interact with the clicked element.</p> <p>So far I have bought the product and now I'm stuck with the Gmail; I'm not able to open the unread mail and interact with the element when I click 'Unread Mail'. here is my code</p> <p>driver.get("<a href="https://www.gmail.com" rel="nofollow">https://www.gmail.com</a>"); driver.manage().window().maximize();</p> <pre><code> JavascriptExecutor exe = (JavascriptExecutor) driver; Integer numberOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString()); System.out.println("Number of iframes on the page are " + numberOfFrames); driver.findElement(By.id("Email")).sendKeys("your mail"); driver.findElement(By.xpath(".//*[@id='next']")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); WebElement ele4=driver.findElement(By.xpath("//*[@id='Passwd']")); new WebDriverWait(driver, 30).until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//*[@id='Passwd']")))); ele4.sendKeys("yourpassword"); driver.findElement(By.xpath("//*[@id='signIn']")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); List&lt;WebElement&gt; unreademeil = driver.findElements(By.xpath("//*[@id=':3d']")); String MyMailer = "StrapUI"; for(int i=0;i&lt;unreademeil.size();i++) { if(unreademeil.get(i).isDisplayed()==true) { if(unreademeil.get(i).getText().equals(MyMailer)) { System.out.println("Yes we have got mail form " + MyMailer); break; } else { System.out.println("No mail form " + MyMailer); } } } driver.findElement(By.xpath("//*[@id=':3d']")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); Thread.sleep(10000); driver.switchTo().frame(0); Thread.sleep(5000); ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)", ""); Thread.sleep(3000); } </code></pre> <p>}</p>
<p>Why do you want to interact with the email using Selenium? Unless you're creating automated tests for Google there shouldn't be a reason to do this with Selenium. The reason for this is that every little change Google makes to Gmail has a chance to break your script and requires modification.</p> <p>Instead I'd recommend using an 'IMAP' library to help you with this. You can login and get the new messages. Using this you can check whatever it is you want to check in your email.</p> <p>For example: I was creating integration tests for a company I used to work at. When I used a certain feature an email would be send containing a url. To verify this worked correctly I had to get this email and find the url in it. Next I used Selenium to get the url that was in the email and verified if it redirected me where I expected. I collected the email using <code>imaplib</code> for <code>Python</code>. I logged in, collected my INBOX and fetched the unread messages.</p>
SELECT ONE WORD FROM ONE STATEMENT <p>I have rule_query table which has number of query with constant variable appends to each query . In every query , variable takes input from another table, appends it and execute that query as result.</p> <p>But i want to return that variable too i.e coming from another table and appends here in query of rule_query table.</p> <p>I want to know for what value of variable which append on this query and execution done</p> <pre><code>RULE_QUERY ---------- SELECT GMID FROM @FIPSNAME+ADMIN1 SELECT GMID FROM @FIPSNAME+ADMIN2 SELECT GMID FROM @FIPSNAME+ADMIN3 COUNTRYTABLE USA UK FRA SA </code></pre> <p>In every value of countrytable loop i am able to get gmid value. But i am not able to get for what from country table does this gmid returns.</p> <p>Kindly suggest solutions.</p>
<p>You can select </p> <pre><code> SELECT GMID, @FIPSNAME FROM @FIPSNAME+ADMIN1 </code></pre> <p>or </p> <pre><code>SELECT @FIPSNAME FROM @FIPSNAME+ADMIN1 </code></pre> <p>or </p> <pre><code> SELECT @FIPSNAME+ADMIN1 FROM @FIPSNAME+ADMIN1 </code></pre>
No static method canDrawOverlays <p>I've noticed someone who is using my app reported a crash which logged by the Google Developer Console:</p> <pre><code>java.lang.NoSuchMethodError: No static method canDrawOverlays(Landroid/content/Context;)Z in class Landroid/provider/Settings; or its super classes (declaration of 'android.provider.Settings' appears in /system/framework/framework.jar) at com.pack.MainActivity.checkDrawOverlayPermission(MainActivity.java:311) at com.pack.MainActivity.onCreate(MainActivity.java:127) at android.app.Activity.performCreate(Activity.java:6033) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5268) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697) </code></pre> <p>The <code>canDrawOverlays</code> is an API 23+ method and I Use it like that:</p> <pre><code> /** code to post/handler request for permission */ public final static int REQUEST_CODE = 100; /*(see edit II)*/ @SuppressLint("NewApi") public void checkDrawOverlayPermission() { /** check if we already have permission to draw over other apps */ if (!Settings.canDrawOverlays(this)) { /** if not construct intent to request permission */ Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); /** request permission via start activity for result */ startActivityForResult(intent, REQUEST_CODE); } } </code></pre> <p>And I have this in my MainActivity:</p> <pre><code>checkDrawOverlayPermission(); </code></pre> <p>The device which crashed using Android 5.1</p> <p>HOw I can make sure my app will work on ANdroid 5.1? (API 22 and below) who don't have this method which available from API 23 and up?</p>
<p>Check the current API of the device which runs your code. If it >= 23, you can use the code</p> <pre><code>if(Build.VERSION.SDK_INT &gt;= 23) { // if (!Settings.canDrawOverlays(this)) { // }else{ // another similar method that supports device have API &lt; 23 } </code></pre>
Home screen shortcut to another application <p>I am making an app which makes a home screen shortcut for another app of mine if user has it installed.</p> <p>It works partially. On API level less then 23 it works perfectly. On android 6 it creates the shortcut, but bypasses <code>Intent.EXTRA_SHORTCUT_NAME</code> and <code>Intent.EXTRA_SHORTCUT_ICON_RESOURCE</code> and leaves original icon and name, which I don't want to use.</p> <p>Here is the code example I am using:</p> <pre><code>ApplicationInfo selectedApp; //app that should be used for shortcut Intent shortcutIntent = new Intent(getPackageManager().getLaunchIntentForPackage(selectedApp.packageName)); shortcutIntent.setAction(Intent.ACTION_MAIN); addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "MyNewShortcut"); addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic1)); addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); addIntent.putExtra("duplicate", false); getApplicationContext().sendBroadcast(addIntent); </code></pre> <p>Manifest:</p> <pre><code>&lt;uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /&gt; </code></pre> <p>Is there anything different that I should do on <em>Android Marshmallow</em>?</p> <p><strong>EDIT</strong></p> <p>Ok, this is a bit confusing. I managed to make it work somehow.<br> When I add this line:</p> <pre><code>shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "asd"); </code></pre> <p>It creates a shortcut on the main screen, but with name that I set on <code>addIntent</code>, and not <code>"asd"</code> like on the new line. Is there any logic explanation for that?</p>
<p>It seems that there is some kind of a bug for Android <strong>M</strong>.</p> <p>For shortcut to get new icon and name, I had to put extra name to the first intent too. And it could be an empty string because the name will stay from second intent. It is working like this now:</p> <pre><code>ApplicationInfo selectedApp; //app that should be used for shortcut Intent shortcutIntent = new Intent(getPackageManager().getLaunchIntentForPackage(selectedApp.packageName)); shortcutIntent.setAction(Intent.ACTION_MAIN); shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "asd"); //EDIT additional string for first intent that fixes Android M addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "MyNewShortcut"); addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic1)); addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); addIntent.putExtra("duplicate", false); getApplicationContext().sendBroadcast(addIntent); </code></pre>
Error installing language pack magento2 on ubuntu <p>I am trying to install a language pack for magento using ubuntu 14.04. First I installed the language pack, after that i put it in the root of the magento installation. </p> <p><a href="http://i.stack.imgur.com/SaY4h.png" rel="nofollow"><img src="http://i.stack.imgur.com/SaY4h.png" alt="enter image description here"></a></p> <p>Then in my ubuntu virtual box i navigated to the Magento root dir and there i ran this command <code>bin/magento i18n:pack -m replace -d source_nl_NL.csv langpack nl_NL</code> But the output was not what i hoped it to be take a look: </p> <p><a href="http://i.stack.imgur.com/ZYNPz.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZYNPz.png" alt="enter image description here"></a></p> <p>In text:</p> <pre><code>InvalidArgumentException] Cannot open dictionary file: "source_nl_NL.csv". i18n:pack [-m|--mode="..."] [-d|--allow-duplicates] source pack locale </code></pre> <p><b>Additional information:</b></p> <p>Machine Ubuntu 14.04</p> <p>Magento version 2.0 php version running in virtualbox 5.6</p> <p>Feel free to ask for more info in the comment section. </p> <p>Thanks in advance, </p> <p>Kevin</p>
<p>Please check the file have proper permission for it</p>
How to create a TensorProto in c#? <p>This is a snipped of the c# client I created to query the tensorflow server I set up using this tutorial: <a href="https://tensorflow.github.io/serving/serving_inception.html" rel="nofollow">https://tensorflow.github.io/serving/serving_inception.html</a></p> <pre><code> var channel = new Channel("TFServer:9000", ChannelCredentials.Insecure); var request = new PredictRequest(); request.ModelSpec = new ModelSpec(); request.ModelSpec.Name = "inception"; var imgBuffer = File.ReadAllBytes(@"sample.jpg"); ByteString jpeg = ByteString.CopyFrom(imgBuffer, 0, imgBuffer.Length); var jpgeproto = new TensorProto(); jpgeproto.StringVal.Add(jpeg); jpgeproto.Dtype = DataType.DtStringRef; request.Inputs.Add("images", jpgeproto); // new TensorProto{TensorContent = jpeg}); PredictionClient client = new PredictionClient(channel); </code></pre> <p>I found out that most classes needed to be generated from proto files using protoc </p> <p>The only thing which I cant find is how to construct the TensorProto. The error I keep getting is : Additional information: Status(StatusCode=InvalidArgument, Detail="tensor parsing error: images")</p> <p>There is a sample client (<a href="https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/inception_client.py" rel="nofollow">https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/inception_client.py</a>) byt my Python skills are not sufficient to understand the last bit.</p>
<p>I also implemented that client in another language (Java). </p> <p>Try to change </p> <pre><code>jpgeproto.Dtype = DataType.DtStringRef; </code></pre> <p>to </p> <pre><code>jpgeproto.Dtype = DataType.DtString; </code></pre> <p>You may also need to add a tensor shape with a dimension to your tensor proto. Here's my working solution in Java, should be similar in C#:</p> <pre><code>TensorShapeProto.Dim dim = TensorShapeProto.Dim.newBuilder().setSize(1).build(); TensorShapeProto shape = TensorShapeProto.newBuilder().addDim(dim).build(); TensorProto proto = TensorProto.newBuilder() .addStringVal(ByteString.copyFrom(imageBytes)) .setTensorShape(shape) .setDtype(DataType.DT_STRING) .build(); ModelSpec spec = ModelSpec.newBuilder().setName("inception").build(); PredictRequest r = PredictRequest.newBuilder() .setModelSpec(spec) .putInputs("images", proto).build(); PredictResponse response = blockingStub.predict(r); </code></pre>
How to test java reflections code using JUnit <p>I have a java class that invoke a method via reflection. That method create database connection and perform database operations. i want to test my reflections code using junit. Is there any way to do that?</p> <p>Please find my code snippet below.</p> <pre><code> Class DaoImpl { public void setResult(String result) { this.result = result } public String getResult() { return this.result; } public void doDBoperation() { Connection connection = getConnection(); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("Select column_name from table"); if(rs.next()) { result = "value"; } } } Class ReflectionClass { public void invoke() { Class&lt;?&gt; noParam = {}; Class&lt;?&gt; clazz = Class.forname("DaoImpl"); Method method = clazz.getDeclaredMethod("doDBoperation", noParam); method.invoke(clazz.getNewInstance); System.out.println("This is it"); } } </code></pre> <p>How to write JUnit test case for my ReflectionClass?</p>
<p>There is no real "pure unit test" way of testing *ReflectionClass**. Normally, you would do a unit test by providing a <strong>mocked</strong> instance of that class to your production code; then you could use the mocking framework to verify that the expected method was called.</p> <p>But in your case, you created code that is simply <strong>hard</strong> to test (if you want to learn how to address that part, you might want to watch these <a href="https://www.youtube.com/playlist?list=PLD0011D00849E1B79" rel="nofollow">videos</a>). You are basically calling "new" directly in your production code; thus there is no way to insert a mocked object. And beyond that, you also can't mock those reflection methods.</p> <p>The only option to <strong>maybe</strong> get this code tested would be to use Mokito together with PowerMock. But I am not an expert in that area, and can't promise you that it will work. </p> <p>My recommendation to you: step back first and figure if you can get <strong>away</strong> from using reflection, or at least: to separate concerns here. Because as said: your <strong>production design</strong> looks <strong>weird</strong>; and instead of spending hours to get that somehow unit tested; you should rather spent a fraction of that time to improve your design! "Hard to test" typically means "design could be improved"!</p> <p>Meaning: first you create an <strong>interface</strong> that denotes the function that you want to test. Then you separate your production code of <em>ReflctionClass</em>, like:</p> <ol> <li>One part is responsible for providing an instance of that interface (and that code could be using <strong>reflection</strong> to do its job, if that is really required)</li> <li>The other part then calls the method(s) you want to be called on that interface object.</li> </ol> <p>By doing so, you get <strong>two</strong> parts that you can test independently of each other!</p> <p>Edit: what I mean by "bad design" - why are you using reflection to do both - <em>object creation</em> and <em>method invocation</em>? You see, you could simply cast that created object to its correct class (at least if you have an interface defined there) and then do a ordinary method call on that typed object.</p>
show all check box elements with the same id in html page <p>I'm creating an HTML page that contains a table , and at the header of the table above some columns there exist a button that when user click on it should show all checkbox that exist on each row of this column.</p> <p>I tries to create an empty CSS class , and the tried to show this check boxes using a jQuery <code>('.label.checkbox-label').show();</code> from inside a javascript method but it doesn't work.</p> <p>how to make this, I can make one <code>id</code> for all check boxes or depend on CSS class but both doesn't work.</p> <p>Below is my code that contains the HTML, I just set a different <code>id</code>s for the checkboxes to show my idea and what I'm supposed to do. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> function showDiv(x) { document.getElementById('1').style.display = "block"; document.getElementById('edit1').style.visibility = "hidden"; document.getElementById('td1').style.backgroundColor = "cadetblue"; document.getElementById('tdd1').style.backgroundColor = "cadetblue"; document.getElementById('tddd1').style.backgroundColor = "cadetblue"; //$('.label.checkbox-label').show(); document.getElementById('Column5_1').style.visibility = "visible"; document.getElementById('Column5_2').style.visibility = "visible"; document.getElementById('Column5_3').style.visibility = "visible"; document.getElementById('Column5_4').style.visibility = "visible"; } function HideDialog(x) { document.getElementById('1').style.display = "none"; document.getElementById('edit1').style.visibility = "visible"; document.getElementById('td1').style.backgroundColor = "transparent"; document.getElementById('tdd1').style.backgroundColor = "transparent"; document.getElementById('tddd1').style.backgroundColor = "transparent"; } $(document).ready(function() { jQuery("#tree ul").hide(); jQuery("#tree li").each(function() { var handleSpan = jQuery("&lt;span&gt;&lt;/span&gt;"); handleSpan.addClass("handle"); handleSpan.prependTo(this); if (jQuery(this).has("ul").size() &gt; 0) { handleSpan.addClass("collapsed"); handleSpan.click(function() { var clicked = jQuery(this); clicked.toggleClass("collapsed expanded"); clicked.siblings("ul").toggle(); }); } }); })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul { list-style-type: none; padding: 0; margin: 0; } li { padding-left: 0.5em; } table.classname td { background-color: antiquewhite; } .handle { background: transparent url(/images/spacer.png); background-repeat: no-repeat; background-position: center bottom; display: block; float: left; width: 10px; height: 11px; } .collapsed { background: transparent url(/images/plus-black.png); background-repeat: no-repeat; background-position: center bottom; cursor: pointer; } .expanded { background: transparent url(/images/minus-black.png); background-repeat: no-repeat; background-position: center bottom; cursor: pointer; } label.checkbox-label { /*some styles here*/ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="page-header"&gt; &lt;h1&gt;hello&lt;/h1&gt; &lt;div class="class=" col-lg-7 "&gt; &lt;p class="bs-component "&gt; &lt;a href="# " class="btn btn-primary "&gt;Expand All&lt;/a&gt; &lt;a href="# " class="btn btn-primary "&gt;Show hide regions&lt;/a&gt; &lt;/p&gt; &lt;p class="bs-component "&gt; &lt;a href="# " class="btn btn-primary "&gt;Collapse All&lt;/a&gt; &lt;a href="# " class="btn btn-primary "&gt;Show hide countries&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="container " style="overflow: auto;border:groove;height:4% "&gt; &lt;div id="table-header " style="padding-left:2% "&gt; &lt;table class="table table-striped table-hover "&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td id="td1 "&gt;&lt;div id="1 " style="display:none;background-color:cadetblue " &gt; &lt;label&gt;insert&lt;/label&gt;&lt;input type="text " /&gt; &lt;div class="class=" col-lg-7"&gt; &lt;p class="bs-component"&gt; &lt;a href="#" class="btn btn-xs btn-primary" onclick="HideDialog();"&gt;Add for selected&lt;/a&gt; &lt;a href="#" class="btn btn-xs btn-primary"&gt;Clear and insert&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td id="tdd1"&gt;&lt;a id="edit1" href="#" class="btn btn-xs btn-primary" onclick="showDiv(1)"&gt;edit&lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;a href="#" class="btn btn-xs btn-primary"&gt;edit&lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="#" class="btn btn-xs btn-primary"&gt;edit&lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;a href="#" class="btn btn-xs btn-primary"&gt;edit&lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="#" class="btn btn-xs btn-primary"&gt;edit&lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;a href="#" class="btn btn-xs btn-primary"&gt;edit&lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="#" class="btn btn-xs btn-primary"&gt;edit&lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;a href="#" class="btn btn-xs btn-primary"&gt;edit&lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td id="tddd1"&gt;Comment&lt;/td&gt; &lt;td&gt;Region&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;Comment&lt;/td&gt; &lt;td&gt;Region&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;Comment&lt;/td&gt; &lt;td&gt;Region&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;Comment&lt;/td&gt; &lt;td&gt;Region&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; &lt;/div&gt; &lt;div id="tabel-details"&gt; &lt;ul id="tree"&gt; &lt;li&gt; Section A &lt;ul&gt; &lt;li&gt; Line Item &lt;ul&gt; &lt;li&gt; &lt;table class="table table-striped table-hover"&gt; &lt;thead style="visibility:hidden"&gt; &lt;tr&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;Comment&lt;/td&gt; &lt;td&gt;Region&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;Comment&lt;/td&gt; &lt;td&gt;Region&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;Comment&lt;/td&gt; &lt;td&gt;Region&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;Comment&lt;/td&gt; &lt;td&gt;Region&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tr&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt; &lt;input id="Column5_1" class="label.checkbox-label" type="checkbox" style="visibility:hidden" /&gt;xxxxx &lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt; &lt;input id="Column5_2" type="checkbox" style="visibility:hidden" /&gt;xxxxx &lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt; &lt;input id="Column5_3" type="checkbox" style="visibility:hidden" /&gt;xxxxx &lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt; &lt;input id="Column5_4" type="checkbox" style="visibility:hidden" /&gt;xxxxx &lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;td&gt;xxxxx&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="footer"&gt; &lt;div class="class=" col-lg-7 "&gt; &lt;p class="bs-component "&gt; &lt;a href="# " class="btn btn-primary "&gt;Manage sections&lt;/a&gt; &lt;a href="# " class="btn btn-primary "&gt;Manage Columns&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
<p>try this best and simple pure javascript Example <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function togglecheckboxes(master,group){ var cbarray = document.getElementsByClassName(group); for(var i = 0; i &lt; cbarray.length; i++){ var cb = document.getElementById(cbarray[i].id); cb.checked = master.checked; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="checkbox" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbgroup1')"&gt; Toggle All &lt;br&gt;&lt;br&gt; &lt;input type="checkbox" id="cb1_1" class="cbgroup1" name="cbg1[]" value="1"&gt; Item 1&lt;br&gt; &lt;input type="checkbox" id="cb1_2" class="cbgroup1" name="cbg1[]" value="2"&gt; Item 2&lt;br&gt; &lt;input type="checkbox" id="cb1_3" class="cbgroup1" name="cbg1[]" value="3"&gt; Item 3&lt;br&gt; &lt;input type="checkbox" id="cb1_4" class="cbgroup1" name="cbg1[]" value="4"&gt; Item 4&lt;br&gt;</code></pre> </div> </div> </p>
Are there any softwares that implemented the multiple output gauss process? <p>I am trying to implement bayesian optimization using gauss process regression, and I want to try the multiple output GP firstly. </p> <p>There are many softwares that implemented GP, like the <code>fitrgp</code> function in MATLAB and the ooDACE toolbox. </p> <p>But I didn't find any available softwares that implementd the so called multiple output GP, that is, the Gauss Process Model that predict vector valued functions.</p> <p>So, Are there any softwares that implemented the multiple output gauss process that I can use directly?</p>
<p>I am not sure my answer will help you as you seem to search matlab libraries.</p> <p>However, you can do co-kriging in R with <code>gstat</code>. See <a href="http://www.css.cornell.edu/faculty/dgr2/teach/R/R_ck.pdf" rel="nofollow">http://www.css.cornell.edu/faculty/dgr2/teach/R/R_ck.pdf</a> or <a href="https://github.com/cran/gstat/blob/master/demo/cokriging.R" rel="nofollow">https://github.com/cran/gstat/blob/master/demo/cokriging.R</a> for more details about usage.</p> <p>The lack of tools to do cokriging is partly due to the relative difficulty to use it. You need more assumptions than for simple kriging: in particular, modelling the dependence between in of the cokriged outputs via a cross-covariance function (<a href="https://stsda.kaust.edu.sa/Documents/2012.AGS.JASA.pdf" rel="nofollow">https://stsda.kaust.edu.sa/Documents/2012.AGS.JASA.pdf</a>). The covariance matrix is much bigger and you still need to make sure that it is positive definite, which can become quite hard depending on your covariance functions...</p>
update query execution in python <p>I am executing this query on sql developer and it is working fine</p> <pre><code>update TABLE_X set COL_SID='19' where ID='1'; </code></pre> <p>But when I am doing this via python code </p> <pre><code>cur=conn.cursor() updt_query='update TABLE_X set COL_SID=? where ID=?' cur.execute(updt_query,('19','1')) cur.close() </code></pre> <p>I am getting error</p> <pre><code>cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number </code></pre> <p>Please let me know where I am doing the mistake.</p>
<p>Could be the ID are number and not string so you should use </p> <pre><code> cur.execute(updt_query,(19,1)) </code></pre>
How to group json array data if exits the same value android studio <p>I have Json like this, I want to group by sub_name to get array of Phone, Mobile Operation(Every array have the same data value get only one of array).</p> <pre><code> category: { cate: [ { sub_id: "568", sub_name: "Phones", ns_id: "17002", ns_name: "Mobile Phone" }, { sub_id: "568", sub_name: "Phones", ns_id: "18787", ns_name: "Other Phones" }, { sub_id: "372", sub_name: "Mobile Operation", ns_id: "3650", ns_name: "Sim Card" } } </code></pre>
<p>Create an ArrayList and add your data.Before adding 2nd item every time check your ArrayList has same data or not using for loop with the help of arrayList size.</p> <p>Whatever I understood about your query I made this code....</p> <pre><code>import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList phones = new ArrayList&lt;&gt;(); ArrayList Mobile_Operation = new ArrayList&lt;&gt;(); String data = " category: {\n" + " cate: [\n" + " {\n" + " sub_id: \"568\",\n" + " sub_name: \"Phones\",\n" + " ns_id: \"17002\",\n" + " ns_name: \"Mobile Phone\"\n" + " },\n" + " {\n" + " sub_id: \"568\",\n" + " sub_name: \"Phones\",\n" + " ns_id: \"18787\",\n" + " ns_name: \"Other Phones\"\n" + " },\n" + " {\n" + " sub_id: \"372\",\n" + " sub_name: \"Mobile Operation\",\n" + " ns_id: \"3650\",\n" + " ns_name: \"Sim Card\"\n" + " }\n" + " ]\n" + " }"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { JSONObject jsonObject = new JSONObject(data); JSONObject categoryObject = jsonObject.getJSONObject("category"); JSONArray jsonArray = categoryObject.getJSONArray("cate"); for (int i = 0; i &lt; jsonArray.length(); i++) { String datal = ((JSONObject) jsonArray.get(i)).getString("sub_name"); if (datal.equalsIgnoreCase("Phones")) phones.add(jsonArray.get(i)); else if (datal.equalsIgnoreCase("Mobile Operation")) Mobile_Operation.add(jsonArray.get(i)); } Toast.makeText(this,((JSONObject)phones.get(1)).getString("ns_name"),Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } } </code></pre>
How to create Wordpress theme like <p>How to create WordPress theme like this websites one for govt jobs and another for show images slide </p> <p><a href="http://www.indiangovtjobs.in" rel="nofollow">www.indiangovtjobs.in</a></p> <p><a href="http://www.imgcluster.com" rel="nofollow">www.imgcluster.com</a></p>
<p>the job website have use this theme:</p> <pre><code>Theme Name: News Pro Theme Theme URI: http://my.studiopress.com/themes/news/ Description: A mobile responsive and HTML5 theme built for the Genesis Framework. Author: StudioPress Author URI: http://www.studiopress.com/ Version: 3.0.2 </code></pre> <p>But this are not start, you can by on envato. Honestly i prefer use _S. It's a empty starter theme you can do what you want with this theme. </p>
Android Wearable - Data Items: Unable to receive data on mobile device <p>I am trying to transfer heart rate sensors data from watch to mobile device. On the watch(wearable) side, I am getting message stating that the data has been transferred. I have set the priority of the message(PutDataMapRequest) as urgent on the watch. However, I am unable to receive the data on the mobile device. Following is my code for AndroidManifest.xml: </p> <pre><code>&lt;%service android:name=".WearableListenerService1"&gt;
 &lt;%intent-filter&gt;
 &lt;%action android:name="com.google.android.gms.wearable.DATA_CHANGED" /&gt;
 &lt;%data android:host="*" android:scheme="wear" android:pathPrefix= "/healthcare" /&gt;
 &lt;/intent-filter&gt; &lt;/service&gt; </code></pre> <p>My WearableListenerService1 class is:</p> <pre><code> public class WearableListenerService1 extends WearableListenerService { @Override public void onMessageReceived(MessageEvent messageEvent) { super.onMessageReceived(messageEvent); String event = messageEvent.getPath(); Log.d("Event ", event); String [] message = event.split("--"); Intent i = new Intent(this, MainActivity.class); startActivity(i); } @Override public void onDataChanged(DataEventBuffer dataEventBuffer) { // super.onDataChanged(dataEventBuffer); Log.d("Event ", "event data changed"); Intent i = new Intent(this, MainActivity.class); startActivity(i); } } </code></pre> <p>I am using following libraries:</p> <pre><code>compile 'com.google.android.support:wearable:2.0.0-alpha2' compile 'com.google.android.gms:play-services-wearable:9.4.0' </code></pre> <p>Can somebody help?</p> <p>Thanks, Savani</p>
<p>Acording to this <a href="http://www.androprogrammer.com/2015/05/android-wear-how-to-send-data-from.html" rel="nofollow">tutorial</a>, make sure that the <code>applicationId</code> in the main app and wearable app are matched (build.gradle files) in order for the <code>WearableListenerService</code> to fire the <code>onDataChanged</code> event. Because when you send some data through mobile app or wear app, it will check for the same package to pass that data. So if you give different name, you won't be able to send or receive data.</p> <p>You can also check this <a href="https://developer.android.com/training/wearables/data-layer/events.html#Listen" rel="nofollow">documentation</a> and related SO threads:</p> <ul> <li><a href="http://stackoverflow.com/questions/24595170/sending-messages-from-android-wear-to-host-device">Sending messages from Android Wear to host device</a></li> <li><a href="http://stackoverflow.com/questions/28034315/android-wear-sending-data-to-android-phone-but-phone-appears-to-never-receive-i">Android Wear sending data to Android phone, but phone appears to never receive it</a></li> </ul>
Jquery/JavaScript not working in a node-red simple custom node <p>I am developing a custom node for Node-Red. Below is the simple html, I am trying to select an element using Jquery. Jquery get/post/ajax is actually working, but selectors are not.</p> <pre><code>&lt;script type="text/javascript"&gt; RED.nodes.registerType('air-conditioner',{ category: 'function', color: '#a6bbcf', defaults: { name: {value:""}, aclist:{value:""} }, inputs:1, outputs:1, icon: "file.png", label: function() { return this.name||"air-conditioner"; } }); $( document ).ready(function() { alert("Name: "+$("#node-input-name").html()); var root = 'http://172.20.0.107:8080/sitewhere/api/sites/bb105f8d-3150-41f5-b9d1-db04965668d4/assignments?includeDevice=false&amp;includeAsset=true&amp;includeSite=false'; $.ajax({ headers: { 'Authorization':'Basic YWRtaW46cGFzc3dvcmQ=', 'X-Sitewhere-Tenant':'atif12345' }, url: root, method: 'GET' }).then(function(data) { debugger; $("#node-input-aclist").append('&lt;option&gt;hello&lt;/option&gt;'); }); }); </code></pre> <p></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;script type="text/x-red" data-template-name="air-conditioner"&gt; &lt;div class="form-row"&gt; &lt;label for="node-input-name"&gt;&lt;i class="icon-tag"&gt;&lt;/i&gt; Give this A.C a name&lt;/label&gt; &lt;input type="text" id="node-input-name" placeholder="Name"&gt; &lt;/div&gt; &lt;div class="form-row"&gt; &lt;label for="node-input-name"&gt;&lt;i class="icon-tag"&gt;&lt;/i&gt; Select A.C&lt;/label&gt; &lt;select id="node-input-aslist"&gt; &lt;option&gt;hello 1&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/script&gt;</code></pre> </div> </div> </p>
<p>You should not be putting any code in <code> $( document ).ready()</code> - a node's edit form only gets created when a node is being edited.</p> <p>You should add any code you need for the edit form into the node's <code>oneditprepare</code> function. That gets called each time the edit form is being built for a node.</p> <p>See <a href="http://nodered.org/docs/creating-nodes/properties#custom-edit-behaviour" rel="nofollow">http://nodered.org/docs/creating-nodes/properties#custom-edit-behaviour</a> for more information.</p>
Picasso: adding multiple images dynamically in flipper for Android. <p>I'm new to picasso.using it i want to dynamically fetch images and be able to update the images whenever some new link has been updated. currently i'm only able to do this for a single Image. the code that i'm using is :</p> <pre><code>picasso.with(this).load(url).into(image1) </code></pre> <p>where url is the url to the image and image1 is an imageview. i want to diaplay 5 images into 5 different imageviews, iteratively. how can i do that ? also i wan to delete the cached images of picasso, so that i can update it with newer images. any help would be appreciated.</p>
<p>In your xml just add only this,</p> <pre><code>&lt;ViewFlipper android:id="@+id/flipper" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;/ViewFlipper&gt; </code></pre> <p>lets Say your URL Images Array like this.</p> <pre><code>String ImgAry[] = {"url1","url2","url3","url4","url5"} </code></pre> <p>In your onCreate()</p> <pre><code> viewFlipper = (ViewFlipper) findViewById(R.id.flipper); for(int i=0;i&lt;ImgAry.length;i++) { // create dynamic image view and add them to ViewFlipper setImageInFlipr(ImgAry[i]); } </code></pre> <p>method in Your Activity file</p> <pre><code>private void setImageInFlipr(String imgUrl) { ImageView image = new ImageView(getApplicationContext()); picasso.with(this).load(imgUrl).into(image); viewFlipper.addView(image); } </code></pre>
How to adjust label height and width in custom tableView Cell <p>I have a expandable tableView, in which when i expand a section, than there are three cell. On firth Cell there is only name and in second cell. It have a big content. Now I want to auto adjust this label height and width according to content.</p> <pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tblView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell let dataArrayTblView = dataArrayForTableView let titleName = dataArrayTblView.valueForKey("name") let dueDate = dataArrayTblView.valueForKey("deadlinedate") let description = dataArrayTblView.valueForKey("description") cell.titleLabel.text = titleName[indexPath.row] as AnyObject! as! String! cell.dueDateLabel.text = dueDate[indexPath.row] as? String cell.descriptionLabel.text = description[indexPath.row] as? String cell.descriptionLabel.sizeToFit() cell.textLabel?.backgroundColor = UIColor.clearColor() cell.selectionStyle = .None return cell } </code></pre> <p><strong>But not getting complete content</strong></p> <p><a href="http://i.stack.imgur.com/AgMxJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/AgMxJ.png" alt="enter image description here"></a></p>
<p>Try to set this. It will automatically adjust the height of the row for you. If it is not working, then you have something wrong with your constraints inside your storyboard.</p> <pre><code>override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -&gt; CGFloat { return 40 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat { return UITableViewAutomaticDimension } </code></pre>
ES6 map feature <p>I am trying out es6 map datastructure, but I when I tried to iterate the map it is giving the following error </p> <pre><code>The error occurs on line 6: for (let [key, val] of m.entries()) SyntaxError: Unexpected token [ at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:413:25) at Object.Module._extensions..js (module.js:452:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.Module.runMain (module.js:475:10) at startup (node.js:117:18) at node.js:951:3 </code></pre> <p>Here is my code : </p> <pre><code>"use strict" let m = new Map() m.set("hello", 42) m.set(1, 34); console.log(m); for (let [key, val] of m.entries()) console.log(key + " = " + val) </code></pre>
<p>I found one solution, here is code snippet that iterates over es6 map: </p> <pre><code>"use strict" let m = new Map() m.set("hello", 42) m.set(1, 34); for (let entry of m.entries()) console.log(entry[0]+" "+entry[1]); </code></pre>
Most up to date CSS compliance table for email clients <p>I've found this CSS compliance table for <strong>email clients</strong>:</p> <p><a href="https://www.campaignmonitor.com/css/" rel="nofollow">https://www.campaignmonitor.com/css/</a></p> <p><strong>Are there any improvements?</strong> (last update there is dated 2013)</p> <p><strong>Can somebody point to to most up to date table of CSS compliance for email clients?</strong></p>
<p>As pointed by Pete in the comment, Mailchimp has it's own compliancy table, that can be found here:</p> <p><a href="http://templates.mailchimp.com/resources/email-client-css-support/" rel="nofollow">http://templates.mailchimp.com/resources/email-client-css-support/</a></p>
Daylight saving causing issue with scheduled job timing <p>I have a materialized view <code>MVIEW_MY_AU</code> which is getting refreshed from a stored procedure named <code>REFRESH_MVIEWS_VIA_PRC</code>. This SP contains following statement : </p> <pre><code>dbms_mview.refresh('MVIEW_MY_AU'); </code></pre> <p>A job <code>REFRESH_MVIEWS_VIA_SCH</code> is created in all_scheduler_jobs table to execute this stored procedure.</p> <p>Query : </p> <pre><code>select job_name, last_start_date,next_run_date,job_action from all_scheduler_jobs where job_name = 'REFRESH_MVIEWS_VIA_SCH' </code></pre> <p>Output : </p> <p><a href="http://i.stack.imgur.com/VQpRm.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/VQpRm.jpg" alt="enter image description here"></a></p> <p>As per the scheduled job I am expecting this materialized view to get refresh at 3:30 AM Australia time. But when its getting refreshed at 4:30 AM Australia time as per the following query : </p> <p>Query : </p> <pre><code>SELECT LAST_REFRESH ,TO_CHAR(last_refresh, 'MM/DD/YYYY HH24:MI:SS A.M.') as LAST_REFRESH_TIME FROM user_mview_refresh_times where name like 'MVIEW_MY_AU' </code></pre> <p>Output :</p> <p><a href="http://i.stack.imgur.com/Vx2NX.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Vx2NX.jpg" alt="enter image description here"></a></p> <p>I started facing this issue after Daylight saving time for Australia started on 2nd Oct 2016. Is there any way to schedule the job which will take into consideration the day light saving time?</p>
<p>The are several ways that Oracle will consider daylight saving times.</p> <p>Enter <code>TIMESTAMP WITH TIME ZONE</code> value for parameter <code>start_time</code>, e.g. <code>SYSTIMESTAMP</code> or <code>CURRENT_TIMESTAMP</code></p> <p>From <a href="http://docs.oracle.com/database/121/ARPLS/d_sched.htm#ARPLS72266" rel="nofollow">DBMS_SCHEDULER Documentation</a>:</p> <blockquote> <p>When start_date is NULL, the Scheduler determines the time zone for the repeat interval as follows:</p> <ol> <li>It checks whether or not the session time zone is a region name. The session time zone can be set by either: <ul> <li>Issuing an ALTER SESSION statement, for example: SQL> <code>ALTER SESSION SET time_zone = 'Asia/Shanghai';</code></li> <li>Setting the <code>ORA_SDTZ</code> environment variable.</li> </ul></li> <li>If the session time zone is an absolute offset instead of a region name, the Scheduler uses the value of the <code>DEFAULT_TIMEZONE</code> Scheduler attribute.</li> <li>If the <code>DEFAULT_TIMEZONE</code> attribute is NULL, the Scheduler uses the time zone of systimestamp when the job or window is enabled.</li> </ol> </blockquote> <p>Most important: Time zone must be provided as region, e.g. <code>Australia/Sydney</code>, not as UTC offset like <code>+08:00</code></p> <p>Regarding your query:</p> <p>Column LAST_REFRESH of view <code>user_mview_refresh_times</code> is <code>DATE</code> data type, so by definition it does not contain any time zone information. Most likely column <code>LAST_REFRESH</code> is provided at your DB operating system server time zone (i.e. time zone value of <code>SYSDATE</code>). What is the time zone of your DB operating system server? You can determine this on OS directly or by </p> <pre><code>SELECT TO_CHAR(SYSTIMESTAMP, 'tzr') FROM dual; </code></pre>
How to let user create Annotations on MSChart? <p>How do you create an Annotation on-the-run and how do you enable end-user placement with <code>Annotation.BeginPlacement()</code>? I've tried to do this in multiple ways, but cannot get it working. It should render itself in real-time after the BeginPlacement() has been called.</p> <p>Documentations on this subject is little to none - and mostly none - so I'm not able to find any help for this problem.</p> <p>What I've tried so far, is to create an annotation and place it with AnchorX/Y, set all Allow- flags to true and called BeginPlacement() while mouse is moving, but cannot see the annotation while placing it nor will it go in it's place accordingly. For example, LineAnnotation starts in right position, but doesn't end where I left it. When I move it so it starts from my ChartAreas {0,0}, it will hit the end-point.</p> <p>What I want to know, is when and how to use these tools available? What I am trying to do, is to let the user draw annotations on a chart and use as tools when analyzing the charts.</p>
<p>You need to calculate the right positions. Remember that the MouseMove will not give you positions (percentages) or values(data) but pixels. You can transform them using the various axis functions. Officially they only work in a xxxPaint event, but during mouse events they also work fine.</p> <p><strong>Update</strong>: There two ways to do the anchoring: </p> <ul> <li>Either by using the '<strong>Positions</strong>', i.e. the percentages or the 'Values', i.e. the data values.</li> </ul> <p>Here is an example of the 1st kind:</p> <p><a href="http://i.stack.imgur.com/WwsKJ.gif" rel="nofollow"><img src="http://i.stack.imgur.com/WwsKJ.gif" alt="enter image description here"></a></p> <pre><code> LineAnnotation laNew = null; private void chart1_MouseDown(object sender, MouseEventArgs e) { if (cbx_drawAnnotation.Checked) { Axis ax = chart1.ChartAreas[0].AxisX; Axis ay = chart1.ChartAreas[0].AxisY; laNew = new LineAnnotation(); chart1.Annotations.Add(laNew); double vx = ax.ValueToPosition(ax.PixelPositionToValue(e.X)); double vy = ay.ValueToPosition(ay.PixelPositionToValue(e.Y)); laNew.X = vx; laNew.Y = vy; } } private void chart1_MouseMove(object sender, MouseEventArgs e) { if (e.Button.HasFlag(MouseButtons.Left) &amp;&amp; cbx_drawAnnotation.Checked) { Axis ax = chart1.ChartAreas[0].AxisX; Axis ay = chart1.ChartAreas[0].AxisY; double vx = ax.ValueToPosition(ax.PixelPositionToValue(e.X))- laNew.X; double vy = ay.ValueToPosition(ay.PixelPositionToValue(e.Y)) - laNew.Y; laNew.Width = Math.Min(100, vx); laNew.Height = Math.Min(100, vy); laNew.LineColor = rb_green.Checked ? Color.Green : Color.Red; laNew.AllowMoving = true; // optional } } </code></pre> <p>This works fine unles you need to rescale the axis in some way, like chaning the axis minimum and/or maximum values.</p> <ul> <li>In the case you need to <strong>anchor to data values</strong>.</li> </ul> <p>First we need to relate the <code>Annotation</code> to the <code>Axes</code> and also set <code>IsSizeAlwaysRelative</code> to <code>false</code>. Then we can calculate the anchor and size values:</p> <pre><code>private void chart1_MouseDown(object sender, MouseEventArgs e) { if (cbx_drawAnnotation.Checked) { Axis ax = chart1.ChartAreas[0].AxisX; Axis ay = chart1.ChartAreas[0].AxisY; laNew = new LineAnnotation(); chart1.Annotations.Add(laNew); laNew.IsSizeAlwaysRelative = false; laNew.AxisX = ax; laNew.AxisY = ay; laNew.AnchorX = ax.PixelPositionToValue(e.X); laNew.AnchorY = ay.PixelPositionToValue(e.Y); laNew.LineColor = rb_green.Checked ? Color.Green : Color.Red; laNew.AllowMoving = true; } } private void chart1_MouseMove(object sender, MouseEventArgs e) { if (e.Button.HasFlag(MouseButtons.Left) &amp;&amp; cbx_drawAnnotation.Checked) { Axis ax = chart1.ChartAreas[0].AxisX; Axis ay = chart1.ChartAreas[0].AxisY; laNew.Width = ax.PixelPositionToValue(e.X) - laNew.AnchorX; // values laNew.Height = ay.PixelPositionToValue(e.Y) - laNew.AnchorY; } } </code></pre> <p>Note how I now can scale the maximum and also still resize the the chart and the annotations stay with the data points..:</p> <p><a href="http://i.stack.imgur.com/oAQ1G.gif" rel="nofollow"><img src="http://i.stack.imgur.com/oAQ1G.gif" alt="enter image description here"></a></p>
Django Custom Permission for Authorization <p>I am working on a Django Project, where one model (lets say Document) has the following field:</p> <pre><code>#In models.py class Document (models.Model): choice = (('Yes','Yes'), ('No','No')) authorized = models.CharField (max_length=3, choices=choice, default='No') </code></pre> <p>Now, as a normal user creates a Document object, the authorized field is no. However, the superior needs to authorize the same before it is actually approved. Now, is there a permission system in django where one user can create an object but not authorize, whereas some other user - who has the permission - can authorize? If not, is the only way to do it is to create a custom field in user model and check it every time? </p>
<p>Django has awesome auth system. I couldn't understand you scenario. But you could try something like this below By default every Model object comes with three Permission object like (add_document, change_document and delete_document in your case). If you want some custom permission you can add it in model Meta class like this:</p> <p>You can add these permission to User object or Group object.</p> <p>models.py</p> <pre><code>class Document (models.Model): ###### class Meta: permissions = (("Can see document dashbaord", "see_document" ),) </code></pre> <p>and run <code>python manage.py migrate</code> to create new Permission object with codename as <code>"see_document"</code>. </p> <p>You can implement permissions in request handled by view like this:</p> <p>view.py</p> <pre><code>from django.contrib.auth.mixins import PermissionRequiredMixin, permission_required # For function based view @pemission_required('document.see_document') def someview(request): ###### pass # For class based views class SomeView(PermissionRequiredMixin, BaseView): permission_required = 'document.see_document' </code></pre> <p>This could redirect any user with out the permssion to permission denied page. For more go through this <a href="https://docs.djangoproject.com/en/1.10/topics/auth/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/auth/</a></p>
Pharo Smalltalk: Reading from TextMorph <p>In Smalltalk using Pharo, I'm creating an application that reads the user input and does X.</p> <p>So far I've managed to make a TextMorph that a user could enter a value into, but I'm unsure of how to read from TextMorphs and then do something with the value.</p> <p>Any ideas?</p> <p>Thanks</p>
<p>Well, you can simply send <code>text</code> to your morph and get it's contents. So you could have a button and when button is pressed you do something with contents:</p> <pre><code>input := TextMorph new. button := SimpleButtonMorph new target: self actionSelector: #processTextMorph:; arguments: {input}; yourself. processTextMorph: aTextMorph | contents | contents := aTextMorph text. "do something with contents" </code></pre> <p>However maybe you want to use a dialog? Because you can do:</p> <pre><code>response := UIManager default request: 'What do you want to do?'. response ifNotNil: [ "do something with the response" ] </code></pre> <p>And then the execution of <code>UIManager default request: '…'</code> will open a dialog with a text input</p>
Django models: foriegn key or multiple data in a field <p>Actually, this question has puzzled me for a long time.</p> <p>Say, I have two models, <code>Course</code> and <code>CourseDate</code>, as follows:</p> <pre><code>class Course(models.Model): name = model.CharField() class CourseDate(models.Model): course = modelds.ForienKey(Course) date = models.DateField() </code></pre> <p>where <code>CourseDate</code> is the dates that a certain course will take place.</p> <p>I could also define <code>Course</code> as follows and discard <code>CourseDate</code>:</p> <pre><code>class Course(models.Model): name = models.CharField() dates = models.CharField() </code></pre> <p>where the <code>dates</code> field contains dates represented by strings. For example: </p> <pre><code>dates = '2016-10-1,2016-10-12,2016-10-30' </code></pre> <p>I don't know if the second solution is kind of "cheating". So, which one is better?</p>
<p>I don't know about cheating, but it certainly goes against good database design. More to the point, it prevents you from doing almost all kinds of useful queries on that field. What if you wanted to know all courses that had dates within two days of a specific date? Almost impossible to do that with solution 2, but simple with solution 1.</p>
How to use set rowcount in select query <p>I have a select query statement which will result 600k rows. When I blindly extract the result using select statement it will impact db performance. Is there an option to use Set rowcount for fetching the data? I tried the below code but it keep on resulting top 50000 rows and ended up in infinite loop.</p> <pre><code>#!/bin/ksh -x trap "" 1 updrowcount=50000 while [ $updrowcount -eq 50000 ] do QUERY="set rowcount 50000 select subject into tempdb..extract from tablename where fldr_id=8" runisql &lt;&lt;EOF &gt; db_restenter code here $QUERY goenter code here quit EOF updrowcount=`grep "rows affected" db_rest |cut -c2- | cut -f1 -d ' '` done exit </code></pre>
<p>If your <code>subject</code> is unique, you could try something like this:</p> <pre><code>set rowcount 50000 declare @subject varchar(...) select @subject = max( subject ) from tempdb..extract insert into tempdb..extract ( subject ) select subject from tablename where fldr_id=8 and (subject &gt; @subject OR @subject is null) order by subject </code></pre> <p>Otherwise, use a unique column, e.g.</p> <pre><code>set rowcount 50000 declare @maxId int select @maxId = max( id ) from tempdb..extract insert into tempdb..extract (id, subject ) select id, subject into tempdb..extract from tablename where fldr_id=8 and (id &gt; @maxId OR @maxId is null) order by id </code></pre> <p>(Obviously, you'll want to use an indexed column.)</p>
How to make side by side tags bottom align with each other <p>I have encountered a problem when I am using html to develop a website. Basically, I have two div tags align side by side. However, when the content of the first div tag is too long, the content may take more than one line to be displayed. Since the content in the second div is quite short, it only need one line to be displayed. </p> <pre><code>&lt;div style="float:left;width:80%;"&gt;XXX ... XXX&lt;/div&gt; &lt;div align="right" style="float:right;width:20%;"&gt;YYY&lt;/div&gt; </code></pre> <p>In this case, the end of the content does not align with each other. When I add one more (the third) div tag, the content will go after the first tag rather than start a new line. I have attached two images to show the problem and what I want from the solution.</p> <p><a href="http://i.stack.imgur.com/SKTGk.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/SKTGk.jpg" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/Lticf.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Lticf.jpg" alt="enter image description here"></a></p>
<p>Use <code>style="clear:both"</code> on the third div.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="float:left; width: 80%"&gt;text 1&lt;br&gt;text 1&lt;/div&gt; &lt;div style="float:right; width: 20%"&gt;text 2&lt;/div&gt; &lt;div style="clear:both"&gt;text 3&lt;/div&gt;</code></pre> </div> </div> </p>
Browser.clearHistory(getContentResolver()); method is not work in Android 5.0 and new version,so how to clear the history of chrome in Android 5.0 <p>In my Android application i want to clear the history of Google Chrome on any button click. </p> <p><code>Browser.clearHistory(getContentResolver());</code> is working properly in Android 4.2 but not work in Android 5.0 and later version, so how can I clear the history of Google Chrome?.</p>
<p>Android has removed Permission to read and write bookmark after API>=23. Pls refer this link <a href="https://developer.android.com/intl/ko/about/versions/marshmallow/android-6.0-changes.html#behavior-bookmark-browser" rel="nofollow">https://developer.android.com/intl/ko/about/versions/marshmallow/android-6.0-changes.html#behavior-bookmark-browser</a></p> <p>You have to use workaround in implementing your own browser app and then save bookmarks locally in your own sqllite database. </p>
WPF Grid Expander Listview vertical scrollbar missing <p>I have the following UI element tree:</p> <pre><code>&lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;/Grid&gt; &lt;Expander&gt; &lt;ListView/&gt; &lt;/Expander&gt; &lt;Expander&gt; &lt;ListView/&gt; &lt;/Expander&gt; &lt;/Grid&gt; </code></pre> <p>I have set ScrollViewer.CanContentScroll="True", ScrollViewer.HorizontalScrollBarVisibility="Auto", ScrollViewer.VerticalScrollBarVisibility="Auto". However, the content of the ListView extends beyond the widow size without showing any vertical scroll bar at all. Any advice and insight is appreciated.</p>
<p><code>Auto</code> will fit to the content (that's why it stretches). So you need to change <code>Height</code> to <code>*</code> to be able to take any available space. </p> <pre><code>&lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; </code></pre>
Vector does not accept new element properly <p>I see some odd behaviour in the code below. My console is printing </p> <blockquote> <p>0lo1lo</p> </blockquote> <p>when in reality I am expecting </p> <blockquote> <p>0Hel1lo</p> </blockquote> <p>Node.cpp</p> <pre><code>std::vector&lt;Node&gt; Node::getChildren() { return children; } void Node::setChildren(std::vector&lt;Node&gt; childrenNodes) { children = childrenNodes; } void Node::addChild(Node child) { children.push_back(child); std::cout &lt;&lt; child.getTitle(); } std::string Node::getTitle() { return title; } </code></pre> <p>From Main function</p> <pre><code>Node root = Node("root"); root.addChild(Node("Hel")); root.addChild(Node("lo")); std::cout &lt;&lt; "\n"; std::vector&lt;Node&gt; children = root.getChildren(); for (int i = 0; i &lt; children.size(); i++) { Node menuItem = children[i]; std::cout &lt;&lt; i; std::cout &lt;&lt; menuItem.getTitle(); } std::cout &lt;&lt; "\n"; </code></pre> <p>Does anybody have an idea why getChildren() appears to be getting a vector that is not accurately listing the first element I inserted?</p>
<p>You're using global variables to store instance data:</p> <pre><code>std::string title; </code></pre> <p>That means there's only one <code>title</code> in your program and if you ever change it, it changes for every class, function, etc. that accesses it.</p> <p>Make it a non-static member variable of <code>Node</code> and your problem will go away.</p>
string convert to json in android <pre><code> client.post("http://10.0.2.2/project/process/selectalluser.php", new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { Integer contacts = controller.getContactsCount(); Log.d("Reading contacts: ", contacts+""); System.out.println("onSuccess"); JSONArray jsonArray = new JSONArray(response); Log.d("Reading response: ", response.length()+""); System.out.println(response); Toast.makeText(getApplicationContext(), "MySQL DB has been informed about Sync activity", Toast.LENGTH_LONG).show(); } @Override public void onFailure(int statusCode, Throwable error, String content) { System.out.println("onFailure"); System.out.println(statusCode); System.out.println(error); System.out.println(content); Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_LONG).show(); } }); </code></pre> <p>Then my php :</p> <pre><code>$stmt = $dbh-&gt;prepare("SELECT * FROM `admin_tbl`"); if ($stmt-&gt;execute()) { $basicinfo = array(); if ($stmt-&gt;rowCount() &gt; 0) { while ($selected_row = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) { $basicinfo[] = array( 'email' =&gt; $selected_row['email'], 'username' =&gt; $selected_row['username'], 'password' =&gt; $selected_row['password'], 'fname' =&gt; $selected_row['fname'], 'mname' =&gt; $selected_row['mname'], 'lname' =&gt; $selected_row['lname'], 'suffix' =&gt; $selected_row['suffix'], 'status' =&gt; $selected_row['status']); } echo json_encode($basicinfo, JSON_UNESCAPED_UNICODE); //return $basicinfo; } else { echo json_encode(array( 'error' =&gt; false, 'message' =&gt; "No record found!" )); exit; } } </code></pre> <p>This is my code i want to convert the response which is of type string to JSON so i can count how many records are there. But I get error of <code>Unhandled Exception: org.json.JSONException</code> in line <code>JSONObject json = new JSONObject(response);</code></p> <p>The line <code>System.out.println(response);</code> will result below:</p> <blockquote> <p>I/System.out: [{"email":"admin@gmail.com","username":"admin","password":"admin","fname":"Bradley","mname":"Buenafe","lname":"Dalina","suffix":"","status":"1"}]</p> </blockquote> <p>How to correctly convert this format of String to JSON</p>
<p>Your response isn't a <code>JSONObject</code> but a <code>JSONArray</code>, the <code>[]</code> indicate an array. A normal object wouldn't have those. You can use</p> <pre><code>JSONArray jsonArray = new JSONArray(response); </code></pre>
X-Axis label in mpandroidchart <p>Earlier, we could set label for X-Axis using the constructor of LineData.</p> <pre><code> LineData lineData = new LineData(labels,dataSet); </code></pre> <p>But after 3.0, it's not working. Has this been removed or am i missing something?</p>
<p>You can use value formatters . xAxis.setValueFormatter(new AxisFormatter)</p>
SQL need assistance <p>Hi all so im stuck on this sql query question: write an sql statement that displays details of session (id and date) that shows crime movies. You must use join to obtain the answer.</p> <p>I have a table for session with an id column and a date column and i have a movie table that has an moviegenre column with 'crime' under it. I was wondering how i could construct this. I found an example of one:</p> <pre><code>Select orders.orderid, customers.customername, orders.orderdate from orders inner join customers on orders.customerid = customers.customerid; </code></pre> <p>from <a href="http://www.w3schools.com/sql/sql_join.asp" rel="nofollow">this site</a>, but am unsure on how to use this so help answer my question. Also is there a way of doing is problem with using a sub query instead</p> <p>thank you! </p>
<pre><code>Select s.id, s.date, from Session s inner join Movie m on m.commoncol = s.commomcol where m.MovieGenre like 'crime'; </code></pre> <p>commomcol represents the mutual column between the tables. Name of the commoncol can be different in both tables.</p> <p>Hope it helps!!</p>
RSpec - equality match, two different instances <p>I created a parser, which reads from CSV file and creates objects from every row. It works fine, but now I created Rspec tests. I have:</p> <pre><code> let(:sample_row) { Call.new(date: '01.09.2016 08:49', service: 'International', phone_number: '48627843111', raw_duration: '0:29', unit: '', cost: '0.00') } it 'tests parser' do expect([sample_row]).to eql(parse('/file_test.csv')) end </code></pre> <p>Test outputs - <code>expected</code> and <code>got</code> - were the same, except of instance id - they were obiously different, because those are two different objects, even if they have exactly the same attributes. So I placed <code>inspect</code> method in my class to control the way Object is presented. Now RSpec shows me two exactly the same <code>expected</code> and <code>got</code> but still test fails. How should I somehow omit the fact two instanes aren't exactly the same if it comes to instance number? I've also tried to use <code>eq</code>.</p>
<p>With all the given informations <code>eq</code> can't work out of the box. You have multiple options: </p> <ul> <li>compare every attribute like <code>expect(sample_row.service).to eq(parse('/file_test.csv').first.service)</code></li> <li>implement <code>Comparable</code> </li> <li>use a third party gem like <code>equalizer</code> to define equality</li> <li>add a method to <code>Call</code> that converts all attributes to a hash and compare those Hashes</li> <li>create your own Matcher</li> <li>...</li> </ul>
Multiple backgrounds with CSS animations <p>I'm using multiple backgrounds in CSS (one being a kind of corporate background, and the other is a member of staff).</p> <p>This is my code :</p> <pre><code>background: url("../../images/andy.png"),url("../../images/background.png") no-repeat top; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; </code></pre> <p>This works fine, but I want to animate and do other CSS options specifically to the first background parameter (<code>url("../../images/andy.png")</code>).</p> <p>Is there any possible way to reference that? It's not it's own element so how could it be possible?</p> <p>Here is my HTML</p> <pre><code>&lt;section id="intro" class="main style1 dark fullscreen"&gt; &lt;div class="content container 100% 12u(mobile)"&gt; &lt;header&gt; &lt;div style="width:40%;margin-right:auto;margin-left:auto;"&gt;&lt;h2 style="font-size:50px;"&gt;a title&lt;/h2&gt;&lt;/div&gt; &lt;/header&gt; &lt;div style="width:40%;margin-right:auto;margin-left:auto;"&gt; &lt;p style="width:100%; margin-right:0; margin-left:0;"&gt;&lt;i&gt;“sometext”.&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;footer&gt; &lt;a href="#work" class="button style2 down"&gt;More&lt;/a&gt; &lt;/footer&gt; &lt;/div&gt; &lt;/section&gt; </code></pre>
<p><strong>Firstly:</strong></p> <p>Your JSFiddle was a little over-complicated and animations were on wrong elements etc.</p> <p>I'd removed unnecessary elements in the HTML for clarity.</p> <p>Here is an updated JSFiddle that shows your desired effect <a href="https://jsfiddle.net/6nstfftn/4/" rel="nofollow">https://jsfiddle.net/6nstfftn/4/</a></p> <p><strong>Read up on CSS Animations!:</strong></p> <p>I would highly recommend looking into CSS animations. There's a guy I follow on YouTube and he's super-awesome. He has some great tutorials - well worth a watch.</p> <p>Find him at : <a href="https://www.youtube.com/devtipsfordesigners" rel="nofollow">https://www.youtube.com/devtipsfordesigners</a></p> <p>He's done a series very recently with some videos on CSS transition/animation/effects etc. Check it out.</p> <hr> <p><strong>Steps to take:</strong></p> <ol> <li>Make your <code>#index</code> element's <code>position: relative;</code></li> <li>Add pseudo-elements for <code>:before</code> and <code>:after</code>, setting their <code>position: absolute;</code> and their <code>top</code>, <code>bottom</code>, <code>left</code> and <code>right</code> to <code>0</code> (basically making them fill the width and height of their "parent" element). <em>Make sure to set the <code>content: ''</code>, otherwise they will have no size!</em></li> <li>Then, for the pseudo-elements, set the <code>background-image</code>, and set the <code>z-index</code> to layer them properly - you can have them in whatever order you like</li> <li>Set the "default" style for each "background" - so, if you want it to start at <code>0</code> opacity (to fade in), do that; likewise if you want it to move, move it to the "start" position: <em>TL;DR - you may end up seeing the elements appear and flash before the animation has started if you set them to the "end" position - also, if the attribute is not defined in the CSS, the animation might not know what it was to begin with</em></li> <li>Create the animations using <code>@keyframes animationName</code>, using <code>from</code> and <code>to</code> to set the starting and ending properties of the animation</li> <li>Apply the <code>transition</code> attribute to each of the "backgrounds" to allow smoothness</li> <li>Apply the <code>animation</code> attribute to each of the backgrounds, setting the name of each <code>@keyframes</code> to use. Set a duration, and use <code>forwards</code> to keep the end-state of the animation</li> <li>Sit back and enjoy a rewarding hot beverage</li> </ol> <hr> <p><strong>Here's a snippet of the CSS:</strong></p> <pre><code>#intro { position: relative; } #intro:after { content: ''; position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: url("http://i65.tinypic.com/2woc2o5.png") no-repeat top; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; z-index: -2; transition: all 0.5s ease-in-out; animation: background 0.5s forwards; opacity: 0; } #intro:before { content: ''; position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: url("http://i65.tinypic.com/2mn0w8j.png") no-repeat top; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; z-index: -1; transition: all 0.5s ease-in-out; animation: andy 1s forwards; transform: translateX(-100%); } @keyframes andy{ from { transform: translateX(-100%); } to { transform: translateX(0%); } } @keyframes background { from { opacity: 0; } to { opacity: 1; } } </code></pre> <p>In my example I've not included the vendor-specific extensions for <code>transition</code>, <code>animation</code>, <code>transform</code> etc. Obviously, you can add these under your own steam for compatibility.</p> <hr> <p>I would highly recommend looking into CSS Animations to get the desired effect.</p> <p>There are literally hundreds (if not thousands) of them out there.</p> <p>Any questions, just ask!</p> <p>Hope this helps :)</p>
Using EF as an ORM after the EDMX is no longer supported <p>Currently I am using a database first approach where I reverse engineer the database using the EF designer from database to produce an EDMX file with pluralization. I then use the designer to produce C# compliant names and I then produce the corresponding POCOs. Updating a table was a little painful but it was possible while maintaining the ORM mappings already made in the EDMX.</p> <p>I understand that future releases of EF will no longer support EDMX files.</p> <p>How can I continue my database first approach using EF to convert database fields into C# complient objects eg PascalCasing for table names and camel casing for table properties?</p>
<p>You can still reverse engineer an existing database even without the designer support. In fact, we've had this capability for a while with various tools (EF Power Tools (from MS), the the EF6 version of the EF Designer (from MS), ReversePoco (reversepoco.com). These all create a set of domain classes that look just like the db table schema and a dbcontext that wrap those classes.</p> <p>WIth EF Core there's currently a migrations command called "Scaffold" that allows you to do the same...specify a database along with parameters to customize the operation... and generate domain classes and dbcontext.</p> <p>Besides no visual designer for this, the other big difference is that it's a one shot deal. You can't udpate the model if the db changes. You'd either do that manually or be using the opposite: update the db if the model changes via migrations.</p> <p>There are also other options such as DevArt's Entity Developer for working with a visual model for efcore and LLBLGen will have one soon as well.</p> <p>HTH!</p>
android - changing the file played in mediaplayer dynamically <p>I'm trying to play sounds dynamically. I have a resource diractory that I have created under res folder that is called "raw". this diractory contains mp3 files. what I want to do is to make an Array with all the files names, and when a button is clicked the next mp3 int the next index will be loaded to the mediaplayer and will be playable.</p> <p>I have found this code for using mediaplayer</p> <pre><code>public class MainActivity extends ActionBarActivity { Context context = this; MediaPlayer mp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); mp = MediaPlayer.create(context, R.raw.sound); final Button b = (Button) findViewById(R.id.Button); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { if (mp.isPlaying()) { mp.stop(); mp.release(); mp = MediaPlayer.create(context, R.raw.sound); } mp.start(); } catch(Exception e) { e.printStackTrace(); } } }); } } </code></pre> <p>but I can't seem to find the way to set track switching by Array with using the song name on the i index.</p> <p>Thanks for any help</p>
<p>1.Basing on this source: </p> <p><a href="http://stackoverflow.com/questions/12274891/dynamically-getting-all-image-resource-id-in-an-array" title="dynamically getting all image resource id in an array">dynamically getting all image resource id in an array</a></p> <p>you can try to write this kind of code:</p> <pre><code>Field[] fields= R.raw.class.getFields(); int[] resArray = new int[fields.length]; for(int i = 0; i &lt; fields.length; i++) { try { resArray[i] = fields[i].getInt(null); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } </code></pre> <p>and <code>resArray[]</code> will contain all the ids that you have in your <code>raw</code> folder.</p> <p>2.If you want to use file names you can use <a href="https://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String,%20java.lang.String,%20java.lang.String)" rel="nofollow">int getIdentifier (String name, String defType, String defPackage)</a> method from <code>Resources</code> class.</p> <p>3.If you want to use files from external storage you can easily create <code>Media Player</code> instance using file path (remember about permissions) </p>
exponential of real(16) in fortran <p>The largest number that is not an infinity in the model of the type of <code>real(16)</code> is 10^4932. I have the <code>exp(10000)</code> in Fortran 90 code that is 8.806818225×10^4342 calculated by simple calculator. I use this simple code:</p> <pre><code>real(16) :: a ... a = exp(10000) ... </code></pre> <p>But it returns infinity. What can I do?</p>
<p>First, who knows what is <code>real(16)</code>, the kind numbers are not portable and may mean anything.</p> <p>But let's say you want to use real of kind 16 whatever it actually is. Then you have to put real of kind 16 into the exp function</p> <pre><code> a = exp(10000._16) </code></pre> <p>In Fortran expressions never care about their surroundings. <code>exp(10000)</code> is evaluated independently and in the same way in all contexts. You put a default integer there and you got the answer in default real. The answer is too big for default real.</p> <p>I <strong>strongly</strong> suggest using some proper way to defind your kinds than just 16. </p> <pre><code>use iso_fortran_env integer, parameter :: rp = real128 real(rp) :: a a = exp(10000._rp) </code></pre> <p>is one of the possible ways.</p>
Updating cells in table using jEditable, jQuery and DataTables <p>I am very new to using DataTables as well as jQuery. </p> <p>I am trying to display a table and let the user edit the cells and update the values in the MySQL database. </p> <p>I don't really understand what the sValue is used for/represents either. </p> <p>This is my code so far, keeping in mind that I have linked the jeditable.js file.</p> <pre><code>$(document).ready(function() { /* Init DataTables */ var oTable = $('#parentEditTable').dataTable({ "columns": [ { "data": "ParentId" }, { "data": "Name" }], "order": [[0, 'asc']], "processing": true, "serverSide": true, "responsive": true, "ajax": { url: 'processEditParent.php', type: 'POST' } }); oTable.$('#parentEditTable').editable('processEditParent.php', { "callback": function( sValue, y ) { var aPos = oTable.GetPosition( this ); oTable.upload( sValue, aPos[0], aPos[1] ); }, "submitdata": function ( value, settings ) { return { "row_id": this.parentNode.getAttribute('ParentId'), "column": oTable.fnGetPosition(this )[2] }; }, "height": "14px", "width": "100%" } ); } ); </code></pre> <p>Any help at all would be appreciated. </p>
<p>I managed to make it work using examples from <a href="http://kingkode.com/free-datatables-editor-alternative/" rel="nofollow">http://kingkode.com/free-datatables-editor-alternative/</a> and some of my own code, feel free to comment or ask any questions if you need any help.</p> <p>Instead of creating a dataSet with static variables, I did a DB query and returned the results as an array and set that array as the dataSet in the dataTable function. </p>
GMSAutocompleteViewController iOS, how to change the text color in the searchBar <p>I'm using a GMSAutocompleteViewController and want to change the textColor in the searchBar but can't find a way to do it, I managed to change the some colors but not the searchBar text.</p> <p><a href="http://i.stack.imgur.com/TJP6A.png" rel="nofollow"><img src="http://i.stack.imgur.com/TJP6A.png" alt="enter image description here"></a></p> <p>I've tried following code but the color won't change:</p> <pre><code> acController.searchBarController?.searchBar.tintColor = UIColor.whiteColor() acController.searchBarController?.searchBar.textColor = UIColor.whiteColor() acController.searchBarController?.searchBar.textField.textColor = UIColor.whiteColor() acController.searchBarController?.searchBar.textField.tintColor = UIColor.whiteColor() acController.searchBarController?.searchBar.textField.backgroundColor = UIColor.whiteColor() acController.searchDisplayController?.searchBar.setTextColor(UIColor.whiteColor()) acController.searchDisplayController?.searchBar.tintColor = UIColor.whiteColor() // changes the color of the sugested places acController.primaryTextColor = UIColor.whiteColor() acController.secondaryTextColor = UIColor.whiteColor() </code></pre>
<p>Try this code </p> <pre><code>let searchBarTextAttributes: [String : AnyObject] = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize())] UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes </code></pre>
Convert.ToDecimal throws System.FormatExcept <p>Im trying to parse from a xml file a value of say 2.25 to be a decimal separated by ",". </p> <pre><code>decimal hrsElapsed = Convert.ToDecimal(caseNode["hrsElapsed"].InnerText, new NumberFormatInfo() {NumberDecimalSeparator = ","}) </code></pre> <p>However, I get a <code>System.FormatException</code> . The same line of code applyed to other fields does not throw it. For example here:</p> <pre><code>decimal hrsOrigEst = Convert.ToDecimal(caseNode["hrsOrigEst"].InnerText, new NumberFormatInfo() {NumberDecimalSeparator = ","}); </code></pre> <p>I checked to see what the actual value of <code>caseNode[""].InnerText</code> which is "2.25" so I see no reason why I would get a Format Exception. Any ideas?</p>
<p>A decimal has no implicit decimal separator, a string could have if you convert the decimal to one. So you need a <code>NumberFormatInfo</code>/<code>CultureInfo</code> that uses a dot as decimal separator to parse the string to <code>decimal</code>,f.e. <code>CultureInfo.InvariantCulture</code>:</p> <pre><code>decimal hrsElapsed = decimal.Parse(caseNode["hrsElapsed"].InnerText, CultureInfo.InvariantCulture); </code></pre> <p>Now you need a <code>NumberFormatInfo</code>/<code>CultureInfo</code> that uses comma as decimal separator for <code>decimal.ToString</code>:</p> <pre><code>string hrsElapsedWithComma = hrsElapsed.ToString(new CultureInfo("de-DE")); // or another one that uses comma as decimal separator </code></pre>