input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Moving a response into table <p>I have a response given below, I need to move program details into an array and show them in table. But I am getting undefined message since, programdetails is again an array.my programdetails is stored in <code>newprogramdetails[]</code>
if I give ng-repeat it gives duplicate error.</p>
<pre><code>HTML:
<tr ng-repeat="item in newProgramDetails">
<td>{{newProgramDetails.title}}</td>
<td>{{newProgramDetails.description}}</td>
<td>{{newProgramDetails.createddate}}</td>
<td>{{newProgramDetails.updateddate}}</td>
</select></td>
</tr>
</code></pre>
<p>JS:</p>
<pre><code>UserService.getProgram(json).then(function(response) {
$scope.newprograms = response.json.response.data;
for(var i=0;i<$scope.newprograms.length;i++){
newProgramDetails.push($scope.newprograms[i].programdetails);
}
});
</code></pre>
<p>JSON:</p>
<pre><code>{
"json": {
"response": {
"servicetype": "4",
"functiontype": "4004",
"statuscode": "0",
"statusmessage": "Success",
"data": [
{
"programdetails": {
"id": 256,
"createddate": "2016-10-07 10:20:48",
"defaultprogram": true,
"description": "This is default program .",
"ppin": "000256",
"apin": "000256",
"owner": true,
"allowscheduling": false,
"points": 0,
"title": "Cakey Bakes Customer default program",
"updateddate": "2016-10-07 10:20:48",
"programtype": "Customer"
}
},
{
"programdetails": {
"id": 257,
"createddate": "2016-10-07 10:20:48",
"defaultprogram": true,
"description": "This is default program .",
"ppin": "000257",
"apin": "000257",
"owner": true,
"allowscheduling": false,
"points": 0,
"title": "Cakey Bakes Vendor default program",
"updateddate": "2016-10-07 10:20:48",
"programtype": "Vendor"
},
"userlist": [
{
"businessuserid": 44,
"businessusername": "rk business New",
"businessusermobile": "00",
"businessusercountrycode": "91",
"admin": true,
"mobilevalidated": false,
"emailvalidated": false,
"email": "riteshnew@gmail.com",
"upin": "000044"
}
]
}
]
}
}
}
</code></pre>
| <p>You dont need for loop for this.</p>
<p>Correct approach to solve your issue is:</p>
<pre><code><tr ng-repeat="item in json.response.data">
<td>{{item.programdetails.title}}</td>
<td>{{item.programdetails.description}}</td>
<td>{{item.programdetails.createddate}}</td>
<td>{{item.programdetails.updateddate}}</td>
</select></td>
</tr>
</code></pre>
<p><a href="https://jsfiddle.net/6t3b9mzy/7/" rel="nofollow"><strong>DEMO</strong></a></p>
|
Style first word of paragraph <p>I am trying to style the first word of a paragraph, but it is not working. Can anyone help. I can style the first letter, but not the first word. I have reasons to not use <code><span></code> to do this. <strong><a href="https://jsfiddle.net/pjthqaz8/" rel="nofollow">JSFiDDLE HERE</a></strong></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-css lang-css prettyprint-override"><code>.product-title {
width: 100vw;
text-align: right;
font-size: 4.5vw;
letter-spacing: -0.05em;
color: #ffffff;
"
}
#first-letter-here p::first-letter {
font-family: arial;
font-weight: 900;
font-size: 3em;
}
#first-word-here p::first-word {
font-family: arial;
font-weight: 900;
font-size: 3em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="first-letter-here">
<p>
Milk and cookies.
</p>
</div>
<div id="first-word-here">
<p>
Milk and cookies.
</p>
</div></code></pre>
</div>
</div>
</p>
| <p>there is no pseudo class for :first-word in css
they only have :first-line and :first-letter
if you need to style that you can do it by adding span tag and applying class to first word.</p>
<p><a href="http://www.w3schools.com/css/css_pseudo_elements.asp" rel="nofollow">http://www.w3schools.com/css/css_pseudo_elements.asp</a></p>
|
Get data with db with lambda expression and coalesce <p>I have a question about coalesce and lambda expression. I'm reading from a SQLite database some records but not always there are some of them. For example</p>
<pre><code>return db.GetItems<Appointment>().Where(l => l.AppointmentId == appointmentId).First();
</code></pre>
<p>If there are no appointment I receive an error</p>
<blockquote>
<p>Sequence contains no elements</p>
</blockquote>
<p>I agree. Then I tried to change the expression</p>
<pre><code>return db.GetItems<Appointment>()?.Where(l => l.AppointmentId == appointmentId)?.First();
</code></pre>
<p>I thought with first <code>?</code> if there are no appointment the function return <code>null</code>. I inserted the second <code>?</code> for the same reason if the <code>where</code> are no appointment.</p>
<p>Then my question is: what did I wrong? Is it possible to do that?
Thank you in advance</p>
| <p>Use <a href="https://msdn.microsoft.com/en-us/library/bb340482(v=vs.110).aspx" rel="nofollow"><code>FirstOrDefault</code></a> instead of <code>First</code>. It returns default value if the sequence contains <strong>no</strong> elements. And also you don't need the null conditional operator.</p>
<pre><code>return db.GetItems<Appointment>()
.Where(l => l.AppointmentId == appointmentId)
.FirstOrDefault();
</code></pre>
<p>See the following to read and know more about <code>First</code>, <code>FirstOrDefault</code>, <code>Last</code>, <code>LastOrDefault</code>, <code>Single</code>, and <code>SingleOrDefault</code>:</p>
<p><a class='doc-link' href="http://stackoverflow.com/documentation/c%23/68/linq-queries/329/first-firstordefault-last-lastordefault-single-and-singleordefault#t=201610141217068833514">First, FirstOrDefault, Last, LastOrDefault, Single, and SingleOrDefault</a></p>
|
Spring Scheduler synchronized method starvation <p>Assume I have a scheduler</p>
<pre><code>@Component
public class Scheduler{
private static int counter = 0;
private synchronized void countIt(){
counter++;
}
@Scheduled(fixedDelay = 3000)
public void job1(){
countIt();
}
@Scheduled(fixedDelay = 6000)
public void job2(){
countIt();
}
}
</code></pre>
<p>Different task trigger in different case will call countIt.</p>
<p>When two or more job call countIt simultaneous, it will cause starvation.</p>
<p>Could any one tell me if there is a way to avoid this situation?</p>
| <p>This should not deadlock.</p>
<p>A Deadlock is caused by one thread locking resource <code>A</code> and then attempting to lock resource <code>B</code> while another thread locks resource <code>B</code> and then tries to lock resource <code>A</code>. There are more complex ways a deadlock can occurr but deadlocks cannot happen with only one lock.</p>
<p>In your case there is only one lock so there is no deadlock.</p>
|
Shell Script : How to use Tee command with sed command <p>Before:</p>
<pre><code>main 2>&1 | tee -a $log_file;
</code></pre>
<p>This is working fine but it is throwing stderr in $log_file as shown below. I want to replace:</p>
<pre><code>"ERROR (version 5.3.0.0-213, build 1 from 2015-02-02_12-17-08 by buildguy) : (stderr)"
</code></pre>
<p>With:</p>
<pre><code>"NOTE (version 5.3.0.0-213, build 1 from 2015-02-02_12-17-08 by buildguy) : (stderr)"
</code></pre>
<p>I want the version and date to be in regex format.</p>
<p>After:</p>
<pre><code>main 2>&1 | tee -a | sed -i 's|ERROR (version 5.3.0.0-213, build 1 from 2015-02-02_12-17-08 by buildguy) : (stderr)|NOTE (version 5.3.0.0-213, build 1 from 2015-02-02_12-17-08 by buildguy) : (stderr)|g' $log_file;
</code></pre>
<p><a href="https://i.stack.imgur.com/Rtluz.png" rel="nofollow">Error which are coming at downloading time</a></p>
<p><a href="https://i.stack.imgur.com/h04wc.png" rel="nofollow">Few lines coming at the end(The lines are jumbled)</a></p>
| <p>You should precise your need, it's pretty hard to read your code by now.</p>
<p>There is two option here : </p>
<ul>
<li>You get the mainstream and alternate him before saving into your log file</li>
<li>You format your log file at the end</li>
</ul>
<p><strong>First option</strong></p>
<p>I can't test it, however, it should be like this : </p>
<pre><code>main 2>&1 | SED COMMAND | tee -a $log_file
</code></pre>
<p><strong>Second option</strong></p>
<p>Tested, it works.</p>
<pre><code>sed -i "s/ERROR (version 5.3.0.0-213, build 1 from 2015-02-02_12-17-08 by buildguy) : (stderr)/NOTE (version 5.3.0.0-213, build 1 from 2015-02-02_12-17-08 by buildguy) : (stderr)/g" $log_file
</code></pre>
<p>Sed will edit the file specified inline because of -i option.</p>
<p><strong>REGEX</strong></p>
<p>If you want to change all <em>ERROR</em> by <em>NOTE</em>, then, you should just use this sed command</p>
<pre><code>sed -i "s/ERROR/NOTE/g" $log_file;
</code></pre>
<p>And if you want to be more specific, take a look at this answer : <a href="http://stackoverflow.com/questions/9189120/using-sed-with-wildcard">using SED with wildcard</a> </p>
|
Angular2 Prevent queuing http requests when there is any pending request <p>Let's assume I want to pull data from backend each 15 seconds. My code now looks like this:</p>
<p><strong>TestComponent:</strong></p>
<pre><code>public ngOnInit(): void {
Observable.timer(0, 15000).subscribe(() => {
this.callService();
});
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
});
}
</code></pre>
<p><strong>TestService:</strong></p>
<pre><code>public callBackendSerivce(): Subscribable<Data> {
return this.http.get(this.serviceUrl)
.map(this.extractData)
.catch(this.handleError);
}
</code></pre>
<p>The problem is that when some error on backend occur and processing time will take more than 15 seconds this code will hit backend service once again, and again, no waiting for response. I want to prevent such behaviour and call service only when I received response from previous call. How to implement this?</p>
<p>I thought it should look like this:</p>
<p><strong>TestComponent:</strong></p>
<pre><code>public ngOnInit(): void {
this.callService();
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
this.subscribeToService();
});
}
private subscribeToService(): void {
this.timerSubscription= Observable.timer(15000).subscribe(() => {
this.callService();
this.timerSubscription.unsubscribe();
});
}
</code></pre>
<p>Two questions: </p>
<ol>
<li>Is there any better solution to do this?</li>
<li><p>If no - does Observable.timer has method to get first result and automatically unsubscribe? It'll prevent adding this code:</p>
<p><em>this.timerSubscription.unsubscribe();</em></p></li>
</ol>
| <p>According to second point, you have two possibilities:</p>
<pre><code>Observable.first().subscribe(...)
</code></pre>
<p>or</p>
<pre><code>Observable.take(1).subscribe(...)
</code></pre>
<p><code>first()</code> means that <strong>Observable</strong> will emit only 1 item from the source. <code>take()</code> allows you to set how much times you want to subscribe (as argument).</p>
|
convert signed to unsigned value in C <p>I have got a negative value somehow which I need the equivalent positive value. I though adding MAX + 1 to that value, where MAX is the maximum value that can be represented with that many number of bits, we can resolve this issue. But it did not help. For example please look at the following code:</p>
<pre><code>#include <stdio.h>
int main()
{
long long int i;
unsigned long long u;
u = 0xffffffff38034080;
u = 0xffffffffffffffff + u + 1;
printf("0x%llx", u);
}
</code></pre>
<p>But this program returns the same negative number.</p>
<p>The output of the program is: <code>0xffffffff38034080</code>. I would like it to be <code>0x0000000038034080</code></p>
| <p>I think what you are looking for is the 2's complement:</p>
<pre><code>{
unsigned long long u;
u = 0xffffffff38034080;
u = ~u + 1;
printf("0x%llx", u);
}
</code></pre>
|
Javascript to cut same second character on a text <p>For example I have text: </p>
<pre><code>var x="default_1305, default_1695, default_1805";
</code></pre>
<p>I want to cut before the second comma to get this text:"default_1305, default_1695". </p>
<p>How can I do this?</p>
| <p><code>var x="default_1305, default_1695, default_1805";</code></p>
<p>string can be split by , like below:</p>
<p><code>var res = x.split(",", 2);</code></p>
<p>Note 2 here in the second param.</p>
<p>And if needed as string, then</p>
<p><code>var res_string = res.join(",");</code></p>
<hr>
<p><strong>Edit</strong>: </p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" rel="nofollow">.split() on MDN</a></p>
<p>Syntax</p>
<blockquote>
<p>str.split([separator[, limit]])
Parameters</p>
</blockquote>
<p><strong>separator</strong></p>
<blockquote>
<p>Optional. Specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.</p>
</blockquote>
<p><strong>limit</strong></p>
<blockquote>
<p>Optional. Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, until the number of split items match the limit or the string falls short of separator.</p>
</blockquote>
|
Filter with elasticsearch <p>I want to fetch a range of date with a specific id, but my result is including other id's in it. I need help checking the query.</p>
<p>This is what am trying to do</p>
<p>Fectch all documents where <strong>uniqueid</strong> == 1 and
<strong>start</strong> range from 2016-10-11T12:00:30.000Z
to "2016-10-12T12:00:30.000Z"</p>
<p>My query and results is shown below.</p>
<p><strong>Query</strong></p>
<pre><code>GET _search
{
"query": {
"constant_score": {
"filter": {
"bool": {
"must": [
{
"term": {
"uniqueid": 1
}
}
],
"should": [
{
"range": {
"start": {
"from": "2016-10-11T12:00:30.000Z",
"to": "2016-10-12T12:00:30.000Z"
}
}
}
]
}
}
}
}
}
</code></pre>
<p><strong>Result</strong> </p>
<pre><code> {
"took": 15,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 6,
"max_score": 1,
"hits": [
{
"_index": "cdr",
"_type": "face",
"_id": "AVfDCsC-vh94Tg1hrkix",
"_score": 1,
"_source": {
"start": "2016-10-12T12:00:30.000Z",
"answer": "2016-10-12T12:00:25.000Z",
"end": "2016-10-12T12:00:35.000Z",
"duration": 50,
"billsec": 55,
"uniqueid": 1,
"is_successful": true,
"is_clicked": true
}
},
{
"_index": "cdr",
"_type": "face",
"_id": "AVfDCucPvh94Tg1hrkiy",
"_score": 1,
"_source": {
"start": "2016-10-12T12:00:30.000Z",
"answer": "2016-10-12T12:00:25.000Z",
"end": "2016-10-12T12:00:35.000Z",
"duration": 50,
"billsec": 55,
"uniqueid": 2,
"is_successful": true,
"is_clicked": true
}
},
{
"_index": "cdr",
"_type": "face",
"_id": "AVfDC1G2vh94Tg1hrkiz",
"_score": 1,
"_source": {
"start": "2016-10-13T12:00:30.000Z",
"answer": "2016-10-13T12:00:25.000Z",
"end": "2016-10-13T12:00:35.000Z",
"duration": 50,
"billsec": 55,
"uniqueid": 2,
"is_successful": true,
"is_clicked": true
}
},
{
"_index": "cdr",
"_type": "face",
"_id": "AVfDC2IGvh94Tg1hrki0",
"_score": 1,
"_source": {
"start": "2016-10-13T12:00:30.000Z",
"answer": "2016-10-13T12:00:25.000Z",
"end": "2016-10-13T12:00:35.000Z",
"duration": 50,
"billsec": 55,
"uniqueid": 1,
"is_successful": true,
"is_clicked": true
}
},
{
"_index": "cdr",
"_type": "face",
"_id": "AVfDCCOOvh94Tg1hrkiv",
"_score": 1,
"_source": {
"start": "2016-10-10T12:00:15.000Z",
"answer": "2016-10-10T12:00:25.000Z",
"end": "2016-10-10T12:00:35.000Z",
"duration": 25,
"billsec": 25,
"uniqueid": 1,
"is_successful": true,
"is_clicked": true
}
},
{
"_index": "cdr",
"_type": "face",
"_id": "AVfDCR2Uvh94Tg1hrkiw",
"_score": 1,
"_source": {
"start": "2016-10-11T12:00:15.000Z",
"answer": "2016-10-11T12:00:25.000Z",
"end": "2016-10-11T12:00:35.000Z",
"duration": 25,
"billsec": 25,
"uniqueid": 1,
"is_successful": true,
"is_clicked": true
}
}
]
}
}
</code></pre>
| <p>You need to remove the empty line below the URL path</p>
<pre><code>GET _search
<--- remove this line
{
"query": {
</code></pre>
<p>Like this:</p>
<pre><code>GET _search
{
"query": {
</code></pre>
|
concrete5 no name no description no styling of theme <p>I have installed my theme in C:\xampp\htdocs\projects\c5\surreymarketingpr_gmk\packages\dotawesome_warm\themes\dotawesome
its working fine on localhost but not on live site. Also its an older version of concrete5 because this theme is not compatible with the latest versions of concrete5.</p>
| <p>You aren't really giving enough information here. Not working is not very helpful. What do your error logs contain? What's the website URL?</p>
<p>There are several things that can impact uploading to an online host, such as PHP version, MySQL version, .htaccess settings, file permissions, etc.</p>
<p>Another very possible problem is that you didn't have this in your <strong>my.ini</strong> under XAMPP when you installed concret5:</p>
<pre><code>lower_case_table_names=1
</code></pre>
<p>If you'd like help with this you can contact me jasteele12 at <a href="http://www.concrete5.org/r/-/13433" rel="nofollow">concrete5.org</a></p>
|
Combine jquery on form submit with plugins for inputs <p>Im using jquery and a few input plugins like sliders checkboxes etc.
However in that form I have on form change submit (GET filtering).
Here the action will not be triggered if plugin changes the input value field.. only if the user did it.</p>
<pre><code>$(document).on('change', '.form-onchange-submit', function (e) {
$(this).submit();
});
</code></pre>
<p>And for example I use this code for selecting all </p>
<pre><code> $(document).on('click', ".select_all", function (e) {
e.preventDefault();
var fields = $(this).data('fields');
$("input[name='" + fields + "']").prop('checked', true);
$("input[name='" + fields + "']").each(function () {
var input_id = $(this).attr('id');
$('label[for="' + input_id + '"]').removeClass('selectable-deselected').addClass('selectable-selected');
});
});
</code></pre>
<p>How do I make the form auto submit when a select_all is clicked ?</p>
| <p>It seems that you would like to combine two events. you can combine multiple events with multiple selectors.</p>
<ul>
<li>Check event type <code>e.type</code></li>
<li>Check element id <code>e.target.id</code></li>
</ul>
<p><strong>Example</strong></p>
<pre><code>$(".select_all, #form-onchange-submit").on("click change", function(e){
if(e.type === "change"){
//DO STUFF UNIQUE TO CHANGE
}
else if(e.type === "click") {
//DO STUFF UNIQUE TO CLICK
}
//DO STUFF THAT IS THE SAME
});
</code></pre>
<p>And if you would like to trigger the event manually you can use <code>.trigger()</code> as well.</p>
<pre><code>$('#element').trigger('click');
</code></pre>
|
Configure mobilefist operational analytics with *websphre application server (network depoyment) cluster* on a separate machine(server) <p>Currently I have configured mobilefirst server 7.1 on websphere application server <strong>cluster</strong> with two nodes (two machine). </p>
<p>My reference :
<a href="https://www.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.installconfig.doc/admin/t_setting_up_WL_WAS_ND_8_cluster_env.html" rel="nofollow">https://www.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.installconfig.doc/admin/t_setting_up_WL_WAS_ND_8_cluster_env.html</a></p>
<p><em>Now I want to setup analytics server for this setup. For analytics I have a separate server.</em></p>
<p>For that I found these two links :</p>
<p><a href="http://www.ibm.com/support/knowledgecenter/SSHSCD_7.1.0/com.ibm.worklight.installconfig.doc/monitor/t_installing_op_analytics_websphere.html" rel="nofollow">http://www.ibm.com/support/knowledgecenter/SSHSCD_7.1.0/com.ibm.worklight.installconfig.doc/monitor/t_installing_op_analytics_websphere.html</a>
As per above link, We can enable WAS to accept analytics by deploying analytics war on WAS. </p>
<p><a href="http://www.ibm.com/support/knowledgecenter/en/SSHSCD_7.1.0/com.ibm.worklight.installconfig.doc/monitor/t_configuring_op_analytics.html" rel="nofollow">http://www.ibm.com/support/knowledgecenter/en/SSHSCD_7.1.0/com.ibm.worklight.installconfig.doc/monitor/t_configuring_op_analytics.html</a>
As per this link, While creating mobilefirst server war, we have to congiure analytics detail in worklight properties.</p>
<p>Here my question is where will be thae configuration of ip/domain, port, database etc. of analytics? Does it require mobilefirst server on this seprate for analytics? </p>
| <p>Analytics is not a relational database. Analytics uses Elasticsearch as it's method of storing information. </p>
<p>Elasticsearch is a search engine based on Lucene. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents.</p>
<p>Elasticsearch stores it's data on the filesystem of the machine you install on unless you tell it otherwise through environment entries.</p>
<p>IP/domain - host of the machine you installed on</p>
<p>port - I believe you set this when you are installing the WAR on WAS.</p>
<p>No, Analytics does not require MobileFirst Platform runtime server to be installed on the same machine. Operational Analytics is a separate server that gets it's data forwarded to it by the runtime server. </p>
<p>Does that answer all of your questions? </p>
|
Why do XMPP messages sometimes get lost on mobile devices <p><a href="http://stackoverflow.com/questions/9690020/lost-messages-over-xmpp-on-device-disconnected">This question</a> asks what to do about loosing XMPP messages on mobile devices when they don't have a stable connection, but I don't really see why the packages get lost in the first place.</p>
<p>I remember having read that the stream between the server and the client stays open when the connection is suddenly lost and will only be destroyed once the connection times out. This means that the server sends arriving messages over the stream, even though the disconnected client can't receive those messages anymore.</p>
<p>I was happy with that explanation for some time, but started wondering why core XMPP would be lacking such an important feature. Eventually I noticed that ensuring correct transmission in the XMPP protocol would be redundant, as the underlying TCP should already ensure the proper transmission of the message, but as the various problems that arise from the lost message it seems that this isn't true.</p>
<p>Why isn't TCP enough to ensure that the message is either correctly sent or fails properly so the server knows it has to send the message later?</p>
| <blockquote>
<blockquote>
<p>Why isn't TCP enough to ensure a proper transmission (or proper error handling, so the server knows the message has to be sent again) in this scenario?</p>
</blockquote>
</blockquote>
<p>Application gives the data that needs to be sent across to its TCP. TCP segments the data as needed and sends them out on established connection. Application passes over the burden of ensuring the packet reaches the other end to TCP. ( This does not mean,application should not have re-transmissions. Application level protocol can define re-send of messages if right response didn't come)</p>
<p>TCP has the mechanism of the Re-transmissions. Every packet sent to peer needs to be acknowledged. Until the acknowledgements come in TCP shall have the packets in its sendQ. Once the acknowledgement for the packets sent is received, they are removed. </p>
<p>If there is packet loss, acknowledgements don't arrive. TCP does the re-transmissions. Eventually gives up.Notifies application which needs to take action. Packet loss can happen beyond TCPs control. Thus TCP provides best-effort reliable service. </p>
|
Redirecting to page based on today's date isn't working <p>I'm not very familiar with scripts, etc... and I have a very precise question.
On one of my pages I want to redirect to a page, based on today's date.
Searching the web, I've come up with something like this at the moment :</p>
<pre><code><html>
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
window.onload = function() {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var newurl = '/Documenten/Kalender_Datum_' + [year, month, day].join('-') + '.html';
// document.location.href = redirect_datum;
alert(newurl); // simulated redirection for testing purposes only
}
</script>
</body>
</code></pre>
<p></p>
<p>But when I want to visit the page, it doesn't do much....
Can anyone explain me what's happening ? Are there any syntax-errors, or other ....
File can be found <a href="http://kbkb.be/matchen_vandaag.html" rel="nofollow">HERE</a>
THX a lot
Carl</p>
| <p>Remove the <code>date</code> argument passed to the <code>Date()</code> and wich is defined nowhere, and the script will work fine. This variable is not defined and cause an error, the script will not continue.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = function() {
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var newurl = '/Documenten/Kalender_Datum_' + [year, month, day].join('-') + '.html';
// document.location.href = redirect_datum;
alert(newurl); // simulated redirection for testing purposes only
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>test</title>
</head>
<body>
</body></code></pre>
</div>
</div>
</p>
|
How to upgrade VSIX to make it compatible with VS 15 Preview 5? <p>When I try to install my VSIX to <a href="https://blogs.msdn.microsoft.com/visualstudio/2016/10/05/announcing-visual-studio-15-preview-5" rel="nofollow">VS 15 Preview 5</a> I get the warning </p>
<blockquote>
<p>"This extension is not compatible with Visual Studio 15 and will not be supported in RC":</p>
</blockquote>
<p><a href="http://i.imgur.com/PoKHzzk.png" rel="nofollow"><img src="http://i.imgur.com/PoKHzzk.png" alt="VSIX installation warning"></a></p>
<p><a href="https://blogs.msdn.microsoft.com/visualstudio/2016/10/05/announcing-visual-studio-15-preview-5" rel="nofollow">Microsoft blog</a> does not provide any notes about this issue.</p>
<p>This should be related to a new VSIX manifest format, which is JSON instead of XML, but I can not find any info regarding upgrade process of the manifest.</p>
<p>How to upgrade my manifest to resolve this issue?</p>
| <p>You can download upgrade documentation to VSIXv3 from <a href="https://aka.ms/vs15preview5extensionsdk" rel="nofollow">this link</a>.</p>
<p>Mostly you should use VS "15" and add <code><GenerateVsixV3>true</GenerateVsixV3></code> to your project file. That will add <code>manifest.json</code> to your new vsix.</p>
|
How to remove duplicate values from array in foreach loop? <p>I want to remove duplicate values from array. I know to use <code>array_unique(array)</code> function but faced problem in <code>foreach</code> loop. This is not a duplicate question because I have read several questions regarding this and most of them force to use <code>array_unique(array)</code> function but I have no idea to use it in <code>foreach</code> loop. Here is my php function.</p>
<pre><code>$images = scandir($dir);
$listImages=array();
foreach($images as $image){
$listImages=$image;
echo substr($listImages, 0, -25) ."<br>"; //remove last 25 chracters
}
</code></pre>
<p>How to do this? </p>
| <p>It is very complicated to remove duplicate values from array within foreach loop. Simply you can push all elements to one array and then remove the duplicates and then get values as you need. Try with following code.</p>
<pre><code> $listImages=array();
$images = scandir($dir);
foreach($images as $image){
$editedImage = substr($image, 0, -25);
array_push($listImages, $editedImage);
}
$filteredList = array_unique($listImages);
foreach($filteredList as $oneitem){
echo $oneitem;
}
</code></pre>
|
Java regex pattern group capture <p>I'm trying to split the string below into 3 groups, but with it doesn't seem to be working as expected with the pattern that I'm using. Namely, when I invoke <code>matcher.group(3)</code>, I'm getting a null value instead of <code>*;+g.3gpp.cs-voice;require</code>. What's wrong with the pattern?</p>
<p>String: <code>"*;+g.oma.sip-im;explicit,*;+g.3gpp.cs-voice;require"</code></p>
<p>Pattern: <code>(\\*;.*)?(\\*;.*?\\+g.oma.sip-im.*?)(,\\*;.*)?</code></p>
<p>Expected:</p>
<p>Group 1: <code>null</code>,
Group 2: <code>*;+g.oma.sip-im;explicit</code>,
Group 3: <code>,*;+g.3gpp.cs-voice;require</code></p>
<p>Actual:</p>
<p>Group 1: <code>null</code>,
Group 2: <code>*;+g.oma.sip-im</code>,
Group 3: <code>null</code></p>
| <p>The result you get does actually match your pattern in a non-greedy way. Group2 is expanded to the shortest possible result </p>
<pre><code>*;+g.oma.sip-im
</code></pre>
<p>and then the last group is left out because of the question mark at the very end. It appears to me that you are building a far too complicated regex for your purpose. </p>
|
Cannot pass size_t *arg[] to function requiring array of void pointers <p>My function <code>f(void *data[])</code> is supposed to receive an array of generic pointers as an argument, as far as I understand.
Nonetheless, I get a compilation error when I try to do</p>
<pre><code>size_t *cnt[8];
... // initialize pointers in cnt
f(cnt);
</code></pre>
<p>In particular g++ automatically converts the prototype of <code>f</code> into <code>f(void**)</code>, then it converts <code>cnt</code> to <code>size_t**</code>, and than it says that it cannot convert <code>size_t**</code> to <code>void**</code>.</p>
| <blockquote>
<p>g++ automatically converts the prototype of <code>f</code> into <code>f(void**)</code></p>
</blockquote>
<p>I find that using exact terminology helps understand programming languages better. It may be confusing to think that <code>f</code> is <em>converted</em> into <code>f(void**)</code>. That's not pedantically speaking the case.<code>f(void *data[])</code> is simply another way to write <code>f(void** data)</code>. This, alternative syntax, is a case of <em>syntactic sugar</em>.</p>
<p>Conversion typically means change of one type into another. There is no conversion involved in the declaration of your function.</p>
<p>Also, this syntactic sugar is not specific to the compiler g++. This behaviour is specified in the C++ standard.</p>
<blockquote>
<pre><code>f(cnt);
</code></pre>
<p>then it converts <code>cnt</code> to <code>size_t**</code></p>
</blockquote>
<p>This <em>is</em> a conversion indeed. It is a special type of conversion called <em>decaying</em>. This implicit conversion is also a case syntactic sugar. It is semantically same as writing:</p>
<pre><code>f(&cnt[0]);
</code></pre>
<hr>
<blockquote>
<p>Cannot pass size_t *arg[] to function requiring array of void pointers</p>
</blockquote>
<p>This is correct.</p>
<p>Indeed, your function expects a <code>void**</code> but you passed the function a <code>size_t**</code>. A <code>size_t**</code> is not implicitly convertible to <code>void**</code>, so your program is ill-formed.</p>
<p>Ways to fix the problem:</p>
<p>1) Use <code>f(size_t**)</code> instead.</p>
<p>2) Use an array of <code>void*</code> in the first place</p>
<p>3) Copy <code>size_t *cnt[8]</code> into another array <code>void *temp[8]</code>, and pass that to the function.</p>
<p>4) (not recommended) Cast <code>cnt</code> to <code>void**</code> and hope that it does what your function expects.</p>
|
Issue in php with "header" <p>I am developing an android app that download songs(so type of data is blob) from db.</p>
<p>I have the following download image code example:</p>
<pre><code><?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select * from images where id = '$id'";
require_once('dbConnect.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
header('content-type: image/jpeg');
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
</code></pre>
<p>How do I change "header" and "echo"(under header) to download an mp3 audio file ?</p>
| <p>You'll want to send the following header for a .mp3 file:</p>
<pre><code>Content-Type: audio/mpeg3
</code></pre>
<p>Refer to <a href="https://www.sitepoint.com/web-foundations/mime-types-complete-list/" rel="nofollow">https://www.sitepoint.com/web-foundations/mime-types-complete-list/</a> for a good list of MIME types.</p>
|
Twitter bootstrap typeahea - get value and id <p>i try to get a value and the id from this data-set. </p>
<p>Gettin one think is easy, but i dont know how i can get the second information?</p>
<p>Importang to know is, that in my site can be a dynamicly number of input fields wich all have to use this function.</p>
<p>This is the JS Code</p>
<pre><code>// Datas
var datas = new Bloodhound({
datumTokenizer: function(d) { return d.tokens; },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'autocomplete.php?s=1&li=5&query=%QUERY',
wildcard: '%QUERY' }
});
$('#orga_id').typeahead(null,
{
name: 'orga_id_autosuggest',
displayKey: 'desc',
input: 'value',
highlight: true,
hint: false,
limit: 5,
minLength: 2,
wildcard: '%QUERY',
source: datas.ttAdapter(),
templates: {
suggestion: Handlebars.compile([
'<div class=\"media\">',
'<div class=\"pull-left\">',
'<div class=\"media-object\">',
'<img src=\"{{img}}\" width=\"50\" height=\"50\"/>',
'</div>',
'</div>',
'<div class=\"media-body\">',
'<h4 class=\"media-heading\">{{value}}</h4>',
'<p>{{desc}}</p>',
'</div>',
'</div>',
].join(''))
}
});
</code></pre>
<p>And in the html form something linke this</p>
<pre><code><input type="text" name="3_orga_name[]" class="form-control autosugbtn" value="" />
<input type="hidden" name="3_orga_id[]" value="">
</code></pre>
<p>Thats the Feedback of the PHP File</p>
<pre><code>$results[] = array(
"value" => $res['DS'],
"desc" => $res['ORG_NAME'],
"img" => "http://lorempixel.com/50/50/?" . (rand(1, 10000) . rand(1, 10000)),
"tokens" => array($query, $query . rand(1, 10))
);
</code></pre>
| <p>To get more than one values from your dataset, you have to transform your result set and return a key-value pair. So in the example below, the <code>response</code> is a JSON string that I receive, and then I get all the values I need.</p>
<blockquote>
<p>A friendly reminder to everyone who are still using Twitter-Typeahead
is to move away from this repository as it is no longer maintained.
Instead redirect yourself to <a href="https://github.com/corejavascript/typeahead.js" rel="nofollow">corejavascript/typeahead.js</a> which is
a fork of the original repository, and the same author (@JakeHarding)
maintains this repository.</p>
</blockquote>
<p><strong>I am using v0.11.</strong></p>
<p><strong>HTML</strong></p>
<pre><code><div id="prefetch">
<input class="typeahead" type="text" placeholder="Countries">
</div>
</code></pre>
<p><strong>JS</strong></p>
<pre><code> var tags = new Bloodhound({
datumTokenizer: function(datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'http://www.yourwebsite.com/js/data.json',
cache: false,
transform: function(response) {
return $.map(response, function (tag) {
return {
name: tag.tagName,
id: tag.tagId
}
});
}
}
});
$('#prefetch .typeahead').typeahead({
minLength: 3,
highlight: true
}, {
name: 'tags-dataset',
source: tags,
display: 'name',
templates: {
suggestion: function (data) {
return '<p><strong>' + data.id + '</strong> - ' + data.name + '</p>';
}
}
})
.bind('typeahead:select', function (ev, suggestion) {
console.log(ev);
console.log(suggestion);
$('#your-id').attr('value', ev.id);
});
</code></pre>
<p>Here is a working <a href="https://jsfiddle.net/xzrh7fde/" rel="nofollow">JSFIDDLE</a> example to get you started.</p>
|
Linux IF & Else using awk or grep <p>I have an output in one column. I need to compare if any value is greater then 3 then print "value is greater than 3"</p>
<pre><code>Column
2
4
5
6
7
</code></pre>
| <p>try this;</p>
<pre><code>awk '$1 > 3' yourFile
</code></pre>
<p>Eg;</p>
<pre><code>user@host $ awk '$1 > 3' test
Column
4
5
6
7
</code></pre>
|
How to configure nginx for django with gunicorn? <p>I have successfully run gunicorn and confirmed that my web runs on localhost:8000. But I can't get nginx right. My config file goes like this:</p>
<pre><code> server {
listen 80;
server_name 104.224.149.42;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
</code></pre>
<p>104.224.149.42 is the ip for outside world.</p>
| <p>Do this</p>
<ul>
<li>Remove <code>default</code> from <code>/etc/nginx/sites-enabled/default</code></li>
</ul>
<p>Create <code>/etc/nginx/sites-available/my.conf</code> with following</p>
<pre><code>server {
listen 80;
server_name 104.224.149.42;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
</code></pre>
<p>Then <code>sudo ln -s /etc/nginx/sites-available/my.conf /etc/nginx/sites-enabled/my.conf</code></p>
<ul>
<li>restart <code>nginx</code></li>
</ul>
<p>You have to configure <code>static</code> files and <code>media</code> files serving.</p>
|
asp.net query c# error <p>I was working with ASP.NET and I try to change a label text and get the value from data base.
here is what i do.</p>
<p>First I add database then I create a linq and then I use query to load it but it won't work.</p>
<p>this is query code</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
DataClasses1DataContext db = new DataClasses1DataContext();
var q = from dc in db.topboxes
where dc.id == (1)
select dc;
Lmain11.Text = q.ToString();
}
</code></pre>
<p><img src="https://i.stack.imgur.com/paRSb.png" alt="this is image"></p>
<p>and this is what I get as label text</p>
<blockquote>
<p>SELECT [t0].[id], [t0].[title], [t0].[dc], [t0].[adminid] FROM [dbo].[topbox] AS [t0] WHERE [t0].[id] = @p0</p>
</blockquote>
<p><img src="https://i.stack.imgur.com/gevpd.png" alt="this image"></p>
<p>Can someone please tell me what should I do? It is not the value that I indented to print</p>
<p>and also when I want to get dc from database topbox <code>where id = 1</code> I also try code without () in where line.</p>
<p>also my data is not null
<a href="https://i.stack.imgur.com/7SqyS.png" rel="nofollow"><img src="https://i.stack.imgur.com/7SqyS.png" alt="enter image description here"></a></p>
| <p>Linq queries return an <code>IEnumerable<T></code> and you want to access a specific item in the collection, to a specific property. Use <code>FirstOrDefault()</code>. <em>(Read <a class='doc-link' href="http://stackoverflow.com/documentation/c%23/68/linq-queries/329/first-firstordefault-last-lastordefault-single-and-singleordefault#t=201610141305491513383">here</a> for more about <code>FirstOrDefault</code>/<code>First</code>)</em></p>
<pre><code>DataClasses1DataContext db = new DataClasses1DataContext();
var q = (from dc in db.topboxes
where dc.id == 1
select dc).FirstOrDefault();
Lmain11.Text = q?.SomeProperty;
</code></pre>
<p><code>FirstOrDefault</code> might return <code>default(T)</code> if such was not found in query. In your case the default is <code>null</code>. Use C# 6 <code>?.</code> operator to safely access the desired property</p>
<p><em>Using on a linq-2-sql query <code>.ToString()</code> will give you the sql that is being generated - Great when you want to see under the hood :)</em></p>
|
C# Winforms SQLAuthentication fails when running exe from share, works running locally <p>I have a Windows Form app that a connects to a SQL Server database using a connection string in the following format:</p>
<pre><code>ConnectionString='Data Source=ServerName;Initial Catalog=DbName;User ID=UserName;Password
</code></pre>
<p>When the user double clicks on the exe in a folder on his desktop, he is able to successfully connect to the database. When we copy the binary folder to a share drive and he double clicks on it, the program throws and error message when it attempts to connect to the database (on the SqlConnection.Open() command).</p>
<p>This used to work for him, but recently he was remove from a global group that provided write access to the share. I captured the SQL Authentication CONNECTION STRING in each case, when it worked and when it failed. It is identical. Since I know that it is failing exactly on the OpenConnection statement (as opposed to, say, attempting to write to a log file), I don't see why not having write access to the share would matter.</p>
<p>One question. Is the word "Data Source=" in the connection string below identical to "Server="?</p>
<pre><code>ConnectionString='Data Source=ServerName;Initial Catalog=DbName;User ID=UserName;Password
</code></pre>
<p>Or does this the "DataSource" usage expect a ODBC/OLE DSN to be created in the Control Panel? I would assume that it is synonymous with Server since I would expect the user NOT to have the DSN on his machine (where the app ran successfully) and I would expect that when running from the share location that the presence of a DSN on the share server would NOT even be accessible (I'm grasping at straws here.)</p>
<pre><code>************** Exception Text **************
System.Data.SqlClient.SqlException (0x80131904): The client was unable to establish a connection because of an error during connection initialization process before login. Possible causes include the following: the client tried to connect to an unsupported version of SQL Server; the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum allowed connections) on the server. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.) ---> System.ComponentModel.Win32Exception (0x80004005): No process is on the other end of the pipe
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParserStateObject.SNIWritePacket(SNIHandle handle, SNIPacket packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock)
at System.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
at System.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
at System.Data.SqlClient.TdsParser.SendPreLoginHandshake(Byte[] instanceName, Boolean encrypt)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
</code></pre>
<p><strong>Update</strong></p>
<p>I changed the connection string to use an IP address</p>
<pre><code> ConnectionString='Server=IPADDRESS;Initial Catalog=DbName;User ID=UserName;Password
</code></pre>
<p>based on what I read here:</p>
<p><a href="http://stackoverflow.com/questions/15795432/name-resolution-in-connection-string-fails-from-network-share">Name resolution in connection string fails from network share</a></p>
<p>Same result.</p>
| <p>I think you are publishing the project you have to add file where your connection string is stored. According to your connection string you have to use provider name in it. When publishing or making exe select include file in your project.</p>
|
Finding a minimum length substring in string S which contains all charachters from string T using Hash Table in O(n) <p>I know that this question has already been asked more than once.My doubt is not finding the solution of this problem, but the correct complexity.
I read an answer here:</p>
<p><a href="http://stackoverflow.com/questions/3592079/minimum-window-width-in-string-x-that-contains-all-characters-in-string-y][1]">Minimum window width in string x that contains all characters in string y</a><br>
In this solution,the complexity proposed is O(n) using hash table.Now till mapping the characters of string T in hash table is fine,but when it comes to finding the minimum and maximum element from the hash table,in almost every answer,I read a linked list is used and they write that the complexity in updating a linked list is O(1).This is where the doubt is.</p>
<p>Please consider the following example:</p>
<p><strong>S:abcbae</strong></p>
<p><strong>T:abc</strong></p>
<p>Initially t["a"],t["b"] and t["c"] will be -1,after 3 passes the values will be 0,1,2 respectively(in hash table) and the double linked list will be containing the elements <strong>[(a,0)-(b,1)-(c,2)]</strong>.</p>
<p>Now the fourth character in string S is <strong>b</strong>,so before appending new value of index for <strong>b</strong> in DLL,I need to remove it's previous instance for which I will have to traverse the DLL.</p>
<p>My question is then how come is the solution for updating DLL is O(1),isn't it O(n),which would lead to a total complexity of O(n^2)?</p>
<p>[O(n) for traversing string S,then O(n) for updating DLL] </p>
<p>Please correct me if I am wrong. </p>
| <p>The data structure described is a doubly-linked list, visualised as follows, using the example in the <a href="http://stackoverflow.com/a/3592224/149530">answer</a>:</p>
<pre><code>HEAD <=> ('c', 0) <=> ('b', 3) <=> ('a', 5) <=> TAIL
</code></pre>
<p>coupled with an array, which is visualised as follows:</p>
<pre><code> 'a' | 'b' | 'c'
{5, &list[2]} | {3, &list[1]} | {0, &list[0]}
</code></pre>
<p>(notice the duplication of information)</p>
<p>At any point during the described algorithm, the following operations are necessary:</p>
<ol>
<li>insertion of an element in the array</li>
<li>insertion of an element in the list</li>
<li>finding the index value for a given character</li>
<li>removal of a node from the list</li>
</ol>
<p>The time-complexity of #1 is O(1) (trivial), and of #2 also O(1) because of our choice of doubly-linked list.</p>
<p>The time-complexity of #3 is also O(1), because of our choice of array. It would still be O(1) for a hash-table-backed map.</p>
<p>The time-complexity of #4 is O(1) because our array holds a pointer to each node in the list, and each character only ever has one node in the list, therefore removal is also trivial.</p>
<p>It's important to note (and understand) here that at any iteration of the proposed algorithm, the minimum window cannot be made larger than what it already was in the last step (why? prove it), and therefore we only need <em>at most one</em> node per character in the string Y (or T in your question).</p>
<p>Hope this helps.</p>
|
d3 plot missing the first item in an array <p>I'm really struggling with this. I'm creating a dot-plot in javascript using the d3 library. I would like to filter the dots actually being plotted so that later I can add text fields to some of them specified in a column in the dataset called 'highlight. Just as a test I'm only plotting the circles that are marked 'yes' but will eventually plot all circles. I've only included the actual plotting code as I'm pretty sure the data structure is OK. The following code plots the circles as I expect it to.</p>
<pre><code>var category = plot.selectAll("."+media+"category")
.data(plotData)
.enter()
.append("g")
.attr("transform", function (d) {return "translate(0," + yScale(d.key) + ")"; })
.attr("class", media+"category")
.call(function(parent){
parent.append('text')
.attr("class", media+"Subtitle")
.attr("x",margin.left)
.attr("y",0)
.text(function(d){return d.key})
parent.selectAll('circles')
.data(function(d){
//console.log("object= ",d)
let filtered=d.values.filter(function(d){
return d.highlight=="yes"
})
//console.log("circles filtered ", filtered)
return filtered
})
.enter()
.append('circle')
.attr("class",function(d,i){
if(d.highlight=="yes"){
return media+"highlight"
}
else {return media+"fill"}
})
.attr("id",function(d){return d.name +" "+d.value+ " "+d.size})
.attr("cx",function(d){return xScale(d.value)})
.attr("cy",yScale.rangeBand()*.4)
.attr("r", function(d) {
if (size) {return d.size*(yScale.rangeBand()*.003 )}
else {return yOffset/2}
})
.attr("transform", function (d) {return "translate("+(margin.left)+","+(0)+")"})
.style("fill",colours[0])
</code></pre>
<p>The plot looks like this:</p>
<p><a href="https://i.stack.imgur.com/BKu7r.png" rel="nofollow"><img src="https://i.stack.imgur.com/BKu7r.png" alt="enter image description here"></a></p>
<p>The problem comes when I try to add the text. I'm using exactly the same filter to filter the data which creates an array for the .data aregument to use. However for some reason, although the first object IS in the array it is not plotted. My revised code looks like this:</p>
<pre><code>var category = plot.selectAll("."+media+"category")
.data(plotData)
.enter()
.append("g")
.attr("transform", function (d) {return "translate(0," + yScale(d.key) + ")"; })
.attr("class", media+"category")
.call(function(parent){
parent.append('text')
.attr("class", media+"Subtitle")
.attr("x",margin.left)
.attr("y",0)
.text(function(d){return d.key})
parent.selectAll('circles')
.data(function(d){
//console.log("object= ",d)
let filtered=d.values.filter(function(d){
return d.highlight=="yes"
})
//console.log("circles filtered ", filtered)
return filtered
})
.enter()
.append('circle')
.attr("class",function(d,i){
if(d.highlight=="yes"){
return media+"highlight"
}
else {return media+"fill"}
})
.attr("id",function(d){return d.name +" "+d.value+ " "+d.size})
.attr("cx",function(d){return xScale(d.value)})
.attr("cy",yScale.rangeBand()*.4)
.attr("r", function(d) {
if (size) {return d.size*(yScale.rangeBand()*.003 )}
else {return yOffset/2}
})
.attr("transform", function (d) {return "translate("+(margin.left)+","+(0)+")"})
.style("fill",colours[0])
parent.selectAll('text')
.data(function(d){
console.log("object= ",d)
let filtered=d.values.filter(function(d){
return d.highlight=="yes"
})
console.log("text filtered ", filtered)
return filtered
})
.enter()
.append('text')
.attr("x",function(d){
return xScale(d.value)+(margin.left);
})
.attr("y",function(d){
return yScale.rangeBand()*.4;
})
.text(function(d){
return d.name+' '+d.size
})
.attr("class",media+"subtitle")
</code></pre>
<p>but the plot looks like this:</p>
<p><a href="https://i.stack.imgur.com/prBuF.png" rel="nofollow"><img src="https://i.stack.imgur.com/prBuF.png" alt="enter image description here"></a></p>
<p>No matter how many circles I define in the dataset as 'yes' so that they are plotted, the first circle is always missing its label. I'm guessing the data is getting mutated somewhere but can't figure out where. I've also tried plotting the text first before the circles just to see but the result is always the same.</p>
<p>This is the output from the console showing that the .data araay has the first items in it</p>
<pre><code>[Object, Object, Object, Object]
dot-plot.js:104 object= Object {key: "Endland", values: Array[22]}
dot-plot.js:108 text filtered [Object, Object]0: Objectgroup: "Endland"highlight: "yes"name: "Manchester City"size: "95.65695168"value: "55097"__proto__: Object1: Objectgroup: "Endland"highlight: "yes"name: "Stoke"size: "9.13121722"value: "27743"__proto__: Objectlength: 2__proto__: Array[0]
dot-plot.js:104 object= Object {key: "Spain", values: Array[44]}
dot-plot.js:108 text filtered [Object, Object, Object]0: Objectgroup: "Spain"highlight: "yes"name: "Barcelona"size: "47.32724506"value: "100000"__proto__: Object1: Objectgroup: "Spain"highlight: "yes"name: "Deportivo de La Coru_a"size: "59.93202583"value: "34600"__proto__: Object2: Objectlength: 3__proto__: Array[0]
dot-plot.js:104 object= Object {key: "Italy", values: Array[22]}
dot-plot.js:108 text filtered [Object]
dot-plot.js:104 object= Object {key: "Germany", values: Array[20]}
dot-plot.js:108 text filtered [Object, Object]
</code></pre>
<p>I'd appreciate any insight that anyone may have. Really sorry for being so verbose but I've never used js.fiddle or I'd put an example up</p>
<p>Thanks</p>
| <p>When you do this:</p>
<pre><code>parent.append('text')
.attr("class", media+"Subtitle")
.attr("x",margin.left)
.attr("y",0)
.text(function(d){return d.key});
</code></pre>
<p>You are creating a <code>text</code> element in the SVG (in your case, the subtitle). So, when you do this later:</p>
<pre><code>parent.selectAll('text')//here you select ALL text elements
.data(function(d){
console.log("object= ",d)
let filtered=d.values.filter(function(d){
return d.highlight=="yes"
})
console.log("text filtered ", filtered)
return filtered
})
.enter()
.append('text');
</code></pre>
<p>You are selecting that previous text (the subtitle). Thus, your enter selection has one element less (have a look here: <a class='doc-link' href="http://stackoverflow.com/documentation/d3.js/2135/selections/16948/the-role-of-placeholders-in-enter-selections#t=201610141302194749446">The role of placeholders in "enter" selections</a>).</p>
<p>Solution: select something else:</p>
<pre><code>parent.selectAll('.somethingElse')//here you don't select existing elements
.data(function(d){
console.log("object= ",d)
let filtered=d.values.filter(function(d){
return d.highlight=="yes"
})
console.log("text filtered ", filtered)
return filtered
})
.enter()
.append('text')
</code></pre>
|
Dictionaries and Map <p>I've just started my adventure with programming. I really like the subject, but sometimes I come across something that I do not completly understand.<br>
Like this, for instance:</p>
<pre><code>//Complete this code or write your own from scratch
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh){
Scanner in = new Scanner(System.in);
Map<String, Integer> phonebook = new HashMap<String, Integer>();
int n = in.nextInt();
for(int i = 0; i < n; i++){
String name = in.next();
int phone = in.nextInt();
phonebook.put(name, phone);
}
// Write code here
while(in.hasNext()){
String s = in.next();
int phonenumber = phonebook.get(s);
if(phonebook.equals("null") == true){
System.out.println("Not found");
}
else if(phonebook.equals("null") == false){
System.out.println(s + "=" + phonebook.get(s));
}
}
in.close();
}
}
</code></pre>
<p>I should have obtained such an output but I get something like this:</p>
<p>Your Output (stdout)</p>
<pre><code>sam=99912222
</code></pre>
<p>Expected Output</p>
<pre><code>sam=99912222
Not found
harry=12299933
</code></pre>
| <p><code>phonebook</code> is a Hashmap. It cannot equal a String of <code>"null"</code></p>
<pre><code>if(phonebook.equals("null") == true)
</code></pre>
<p>I believe you are confused about how to appropriately check for <code>null</code> values.</p>
<p>When a key in a Hashmap does not exist, it returns <code>null</code>, not <code>"null"</code>. Also, you need to check the value, not the Hashmap itself. </p>
<p>Therefore </p>
<pre><code>Integer phonenumber = phonebook.get(s);
if(phonenumber == null){
System.out.println("Not found");
}
else {
System.out.println(s + "=" + phonenumber);
}
</code></pre>
<p>Then, unrelated issue <code>if (val == true)</code> is just <code>if (val)</code>. And no need for an <code>else if</code> if you only invert the condition </p>
|
Generating Report from User Inputs in Access Form <p>Goal: To create an access form that takes user inputs combines those with a bound value in an access query calculates a final number and then generates a report.</p>
<p>The only issue I am having here in referencing the user inputs on the form to the actual report. </p>
<p>Any suggestions? </p>
| <p>In the report it would be:</p>
<pre><code>=Forms!YourUserInputFormName!txtUserInputBox
</code></pre>
<p>The form must be left open.</p>
|
Plotting and sorting of multi-channel sequence objects <p>I would like to make a sequence index plots of a multi-channel sequence object for first descriptive purposes. However, I am still not sure how to do that properly. The usual way of sorting one sequence object does not work well as there is no nested sorting function which sorts across multiple channels. The best way seems to me, to do a MDS after calculating multi-channel sequence distances using seqdistmc and sort all channels accordingly. This approach necessitates multiple decisions regarding the distance measure and so on, thus it almost goes beyond my intention of a first description.</p>
<ol>
<li>Would it somehow be possible to create a nested sort function
for multi-channel sequence objects? Maybe by sorting first one
channel from the beginning of sequences and then sorting the âtiesâ,
equal sequences, by sorting the second channel and so on?<br>
<strong>Update</strong>: I found an answer to this part of the question using <code>seqHMM</code>, see below.</li>
<li>What do you think, what would be the best way to plot and sort a
multi-channel sequence object for description?</li>
</ol>
<p>Here is some R syntax which may help to understand my problem</p>
<pre><code>library(TraMineR)
library(TraMineRextras)
# Building sequence objects
data(biofam)
## Building one channel per type of event left, children or married
bf <- as.matrix(biofam[, 10:25])
children <- bf==4 | bf==5 | bf==6
married <- bf == 2 | bf== 3 | bf==6
left <- bf==1 | bf==3 | bf==5 | bf==6
child.seq <- seqdef(children)
marr.seq <- seqdef(married)
left.seq <- seqdef(left)
# Create unsorted Sequence Index Plots
layout(matrix(c(1,2,3,4,4,4), 2, 3, byrow=TRUE), heights=c(3,1.5))
seqIplot(child.seq, title="Children", withlegend=FALSE)
seqIplot(marr.seq, title="Married", withlegend=FALSE)
seqIplot(left.seq, title="Left parents", withlegend=FALSE)
seqlegend(child.seq, horiz=TRUE, position="top", xpd=TRUE)
# Create sequence Index Plots sorted by alignment of first channel from beginning
mcsort.ch1 <- sortv(child.seq, start="beg")
layout(matrix(c(1,2,3,4,4,4), 2, 3, byrow=TRUE), heights=c(3,1.5))
seqIplot(child.seq, title="Children", sortv=mcsort.ch1, withlegend=FALSE)
seqIplot(marr.seq, title="Married", sortv=mcsort.ch1, withlegend=FALSE)
seqIplot(left.seq, title="Left parents", sortv=mcsort.ch1, withlegend=FALSE)
seqlegend(child.seq, horiz=TRUE, position="top", xpd=TRUE)
# Sequence Index Plots sorted by MDS scores of multi-channel distances
## Calculate multi-channel distances and MDS scores
mcdist <- seqdistmc(channels=list(child.seq, marr.seq, left.seq),
method="OM", sm =list("TRATE", "TRATE", "TRATE"))
mcsort.mds <- cmdscale(mcdist, k=2, eig=TRUE)
## Create sequence Index Plots sorted by MDS scores of multi-channel distances
layout(matrix(c(1,2,3,4,4,4), 2, 3, byrow=TRUE), heights=c(3,1.5))
seqIplot(child.seq, title="Children", sortv=mcsort.mds$points[,1], withlegend=FALSE)
seqIplot(marr.seq, title="Married", sortv=mcsort.mds$points[,1], withlegend=FALSE)
seqIplot(left.seq, title="Left parents", sortv=mcsort.mds$points[,1], withlegend=FALSE)
seqlegend(child.seq, horiz=TRUE, position="top", xpd=TRUE)
</code></pre>
| <p>I just stumbled upon the package <code>seqHMM</code> whose name suggests other purposes but which is able to sort multi-channel sequence objects. Thus, <code>seqHMM</code> is an answer to my first question.
Here is an example code using <code>seqHMM</code>:</p>
<pre><code>library(TraMineR)
library(seqHMM)
# Building sequence objects
data(biofam)
## Building one channel per type of event left, children or married
bf <- as.matrix(biofam[, 10:25])
children <- bf==4 | bf==5 | bf==6
married <- bf == 2 | bf== 3 | bf==6
left <- bf==1 | bf==3 | bf==5 | bf==6
child.seq <- seqdef(children)
marr.seq <- seqdef(married)
left.seq <- seqdef(left)
mcplot <- ssp(list(child.seq, marr.seq, left.seq),
type = "I",title = "Sequence index plots",
sortv = "from.start", sort.channel = 1,
withlegend = FALSE, ylab.pos = c(1, 1.5, 1),
ylab = c("Parenthood", "Marriage", "Residence"))
plot(mcplot)
</code></pre>
<p>You can find more about the abilities of the package in the following paper:<br>
Helske, Satu; Helske, Jouni (2016): Mixture Hidden Markov Models for Sequence Data: the seqHMM Package in R. Jyväskylä. Available online at <a href="https://cran.r-project.org/web/packages/seqHMM/vignettes/seqHMM.pdf" rel="nofollow">https://cran.r-project.org/web/packages/seqHMM/vignettes/seqHMM.pdf</a>.</p>
|
How to get the selected options of a multiselect in Elm? <p>I've seen <a href="http://stackoverflow.com/questions/32426042">what is required for a getting the selected index of a single select</a> but I'm interested in getting all of the selected options from a multi select. I haven't been able to work out how to do this.</p>
<p>I've attempted the following but I suspect the Json decoder is failing. I'm not 100% sure of that though, because the decoding happens in the virtual dom code and any errors there are thrown away.</p>
<pre><code>type Msg
= SetMultipleInts (List Int)
-- I'm not seeing the SetMultipleInts message when I click on the multiselect
view model =
div []
[ select (onSelect SetMultipleInts) (List.map myOption [1..4]) ]
myOption : Int -> Html Msg
myOption id =
option [ value (toString id) ] [ text <| "Option " ++ (toString id) ]
-- I'm not seeing anything happen in the onchange
onMultiSelect : (List Int -> msg) -> List (Html.Attribute msg)
onMultiSelect msg =
[ on "change" (Json.map msg targetSelectedOptions), multiple True ]
targetSelectedOptions : Json.Decoder (List Int)
targetSelectedOptions =
Json.at [ "target", "selectedOptions" ] (Json.list (Json.at [ "value" ] Json.int))
</code></pre>
<p>Can I do this without having to use ports?</p>
| <p>The decoder fails because <code>event.target.selectedOptions</code> is not a
javascript array. When you cannot use <code>Json.Decode.list</code>, you
can use <code>Json.Decode.keyValuePairs</code>.</p>
<p>Here is the example how you can use it.
You may want to change <code>extractValues</code> below depending
on how you want to react to empty selection and such.</p>
<pre class="lang-elm prettyprint-override"><code>targetSelectedOptions : Json.Decoder (List String)
targetSelectedOptions =
let
maybeValues =
Json.at [ "target", "selectedOptions" ]
<| Json.keyValuePairs
<| Json.maybe ("value" := Json.string)
extractValues mv =
Ok (List.filterMap snd mv)
in Json.customDecoder maybeValues extractValues
</code></pre>
|
How do i pass the value from the first form to the second form messageBox ? It will show 0 <p>This is the first form( it contains an OK button and a textbox)</p>
<pre><code>namespace Testt
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int dimx;
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
this.Hide();
f2.ShowDialog();
this.Show();
dimx = int.Parse(textBox1.Text);
MessageBox.Show(dimx.ToString());
}
}
}
</code></pre>
<p>This is the second form (it contains an OK button + a messageBox when OK is pressed)</p>
<pre><code>namespace Testt
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f=new Form1();
MessageBox.Show(f.dimx.ToString());
}
}
}
</code></pre>
<p>I want to write the value of 6 in the textbox press OK, then form2 pops up and when i press OK on the second form it should display 6 not 0..what am i doing wrong?</p>
| <p>You could make it so that your form takes dimx as a variable, so it would look like this</p>
<pre><code>public partial class Form2 : Form
{
private int dimX;
public Form2(int dimx)
{
InitializeComponent();
dimX = dimx;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(dimX.ToString());
}
}
</code></pre>
<p>alternatively you could pass the form itself, changing</p>
<pre><code>public Form2(int dimx)
</code></pre>
<p>into</p>
<pre><code>public Form2(Form1 f1)
</code></pre>
<p>You would then also have to replace</p>
<pre><code>private int dimX;
//and
dimX = dimx;
//and
MessageBox.Show(dimX.ToString());
</code></pre>
<p>with </p>
<pre><code>private Form1 f;
//and
f = f1;
//and
MessageBox.Show(f.dimx.ToString());
</code></pre>
|
How to Fill a group of Fabric.Path like any shape or a single path <p>While filling a single Fabric.Path object , it fills completely and works fine! </p>
<p>Example,<br>
<a href="https://i.stack.imgur.com/jxKzL.png" rel="nofollow"><strong>Single Path Fill Example Image</strong></a> </p>
<p>But , when I fill a group Paths , they obviously act according to their Individual shape . </p>
<p>Example,<br>
<a href="https://i.stack.imgur.com/Sgdwp.png" rel="nofollow"><strong>Group of Paths Fill Example Image</strong> </a> </p>
<p>I'm using simple fill function of fabricjs.
Secondly , I have to avoid any change in their state. they must stay as a group of paths.</p>
<p>Is there something i did wrong?<br>
Thanks!</p>
| <p>Fabric does not support what you are trying to do.</p>
|
Get value of option of the dropdown menu and filter table <p>I would like to click in the dropdown menu and I get the value of the selected option. After that I would like to filter a field of the bootstrap-table and it show only the records with this field.</p>
<p><a href="https://i.stack.imgur.com/l2LBt.png" rel="nofollow"><img src="https://i.stack.imgur.com/l2LBt.png" alt="enter image description here"></a></p>
<p>At moment my code of the jquery is this:</p>
<pre><code>$('#edicion').click(function(v){
console.log(v.target.value);
});
</code></pre>
<p>HTML:</p>
<pre><code><div class="dropdown pull-left btn-group" style="padding-right: 10px;">
<button class="btn dropdown-toggle" type="button" data-toggle="dropdown">EDICIÃ<span class="caret"></span></button>
<ul class="dropdown-menu text-center" id="edicion">
<?php
$result = dbQuery($conn, "SELECT * FROM produccion.ma_edicion");
while ($row = pg_fetch_row($result)){ ?>
<li><a href=#><?php echo $row[1] .' '. $row[2]; ?></a></li>
<?php
}
?>
</ul>
</div>
</code></pre>
<p><code>#edicion</code> is the id of the Dropdown Menu and at moment only it shows in the console the message 'undefined'.</p>
<p><a href="https://i.stack.imgur.com/HCB0U.png" rel="nofollow"><img src="https://i.stack.imgur.com/HCB0U.png" alt="enter image description here"></a></p>
<p>I do not know how to get the value of the option nor how to filter the table applying this value at field.</p>
<p>To filtering:</p>
<p><a href="https://i.stack.imgur.com/SK1xn.png" rel="nofollow"><img src="https://i.stack.imgur.com/SK1xn.png" alt="enter image description here"></a></p>
<p>After choose option:</p>
<p><a href="https://i.stack.imgur.com/2gAjz.png" rel="nofollow"><img src="https://i.stack.imgur.com/2gAjz.png" alt="enter image description here"></a></p>
<p>The head of the table disappear :(</p>
| <p>Add this code</p>
<pre><code><select id="edicion">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
$(document).on("change", '#edicion', function(){
console.log($(this).val());
});
</code></pre>
<p>Demo here: <a href="https://jsfiddle.net/2fkb95ur/1/" rel="nofollow">https://jsfiddle.net/2fkb95ur/1/</a> </p>
<pre><code>$('#edicion li').click(function(){
console.log($(this).text());
});
</code></pre>
<p>Demo here: <a href="https://jsfiddle.net/2fkb95ur/2/" rel="nofollow">https://jsfiddle.net/2fkb95ur/2/</a> </p>
|
How to get camera instance from cwac- cam2 for face detection? <p>I would like to know how to get camera instance from CWAC- CAM2 library in android so that I can attach face detector to camera for face detection. Need know how to do this in android ?</p>
| <p>That is not supported by the library. Use the camera APIs directly, skipping the library.</p>
|
How to restrict errors coming from iframe - htaccess <p>I have a php site .Im using iframe to load some contents from other site.A bulk list of errors showing in my console.Is it possible to restrict this errors in htaccess or using jquery?</p>
| <p>You cannot suppress errors in frames from other sites. It is for security reasons.</p>
<p>What you can do is catch the errors - and then do some action if an error occurs. Or I would recommend to contact the site which you are including as a frame. They are the ones who can fix the errors. </p>
|
How do I call an Excel VBA script using xlwings v0.10 <p>I used to use the info in this question to run a VBA script that does some basic formatting after I run my python code.</p>
<p><a href="http://stackoverflow.com/questions/30308455/how-do-i-call-an-excel-macro-from-python-using-xlwings">How do I call an Excel macro from Python using xlwings?</a></p>
<p>Specifically I used the first update.</p>
<pre><code>from xlwings import Workbook, Application
wb = Workbook(...)
Application(wb).xl_app.Run("your_macro")
</code></pre>
<p>Now I'm using v0.10.0 of xlwings and this code no longer works.</p>
<p>When I try the suggested new code for v0.10.0:</p>
<pre><code>wb.app.macro('your_macro')
</code></pre>
<p>Python returns an object: </p>
<pre><code><xlwings.main.Macro at 0x92d3198>
</code></pre>
<p>and my macro isn't run in Excel.</p>
<p>The documentation (<a href="http://docs.xlwings.org/en/stable/api.html#xlwings.App.macro" rel="nofollow">http://docs.xlwings.org/en/stable/api.html#xlwings.App.macro</a>) has an example that is a custom function but I have a script that does several things in Excel (formats the data I output from python, adds some formulas in the sheet, etc.) that I want to run.</p>
<p>I'm sure I'm missing something basic here.</p>
<p><strong>Update</strong>
Based on Felix Zumstein's suggestion, I tried:</p>
<pre><code>import xlwings as xw
xlfile = 'model.xlsm'
wb = xw.Book(xlfile)
wb.macro('your_macro')
</code></pre>
<p>This returns the same thing as wb.app.macro('your_macro'):</p>
<pre><code><xlwings.main.Macro at 0x92d05888>
</code></pre>
<p>and no VBA script run inside Excel.</p>
| <p>You need to use <code>Book.macro</code>. As your link to the docs says, <code>App.macro</code> is only for macros that are not part of a workbook (i.e. addins). So use:</p>
<pre><code>wb.macro('your_macro')
</code></pre>
|
How to display images in web page using angularjs? <p>I already know how to save images in mongodb using angularjs and java to save it in my mongodb, </p>
<p>I need to get the saved image from mongodb and display it in an html page using AngularJS.</p>
<p>This is my controller for getting image</p>
<pre><code>@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getById(@PathParam("id") String id) throws IOException
{
Response response = null;
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB mongoDB = mongoClient.getDB("sampleDB");
DBCollection collection = mongoDB.getCollection("filestore");
BasicDBObject query = new BasicDBObject();
ObjectId oid = new ObjectId(id);
query.put("_id", oid);
GridFS fileStore = new GridFS(mongoDB, "filestore");
GridFSDBFile gridFile = fileStore.findOne(query);
InputStream in = gridFile.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data = in.read();
while (data >= 0)
{
out.write((char) data);
data = in.read();
}
out.flush();
ResponseBuilder builder = Response.ok(out.toByteArray());
builder.header("Content-Disposition", "attachment; filename=");
response = builder.build();
return response;
}
</code></pre>
<p>This is my angularjs for getting image</p>
<pre><code>var userImagePromise = $http.get("../api/s3/" + $scope.user.profileImage[0].id);
userImagePromise.success(function(data, status, headers, config) {
$scope.imageData = data;
});
userImagePromise.error(function(data, status, headers, config) {
});
</code></pre>
<p>This is my html for displaying image</p>
<pre><code><img id="userProfileImg" height="150px" width="150px" ng-src="data:image/png;base64,{{imageData}}">
</code></pre>
<p>if I simply put the link to browser i got this output in octect-stream</p>
<p>�PNG .....</p>
<p>How to display image in html?Any error in my code wise?</p>
<p><a href="https://i.stack.imgur.com/KFvd9.png" rel="nofollow">Image for getting output</a></p>
| <p>i think your base64 code is not converting images properly, so check my code it may help you.</p>
<pre><code>import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
BufferedImage buffimage = ImageIO.read(new File(imagePath));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffimage, "png", baos);
String img = Base64.encode(baos.toByteArray());
</code></pre>
<p>send this img variable to your angularjs code.</p>
|
Search each row, paste each match - Excel VBA <p>So I can search but I'm having problems with the loop, here is an example for some context:</p>
<pre><code>Sub Find_First()
Dim FindString As String
Dim Rng As Range
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
With Sheets("DCCUEQ").Range("1:20") 'searches all of rows 1 to 20
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
Application.Goto Rng, True 'value found
MsgBox ("Value Found" & Rng)
Else
MsgBox "Nothing found" 'value not found
End If
End With
End If
End Sub
</code></pre>
<p>There are a few things I need to do with this </p>
<p>If FindString is on a row, Copy and paste that row (From A:F) to Sheet3 starting from row 5<br>
Skip the rest of that row and search the next row on DCCUEQ<br>
check and paste under the previously pasted row (on Sheet3) if the requirements are met<br>
Loop this until no information is found on a row </p>
<p>It is part of a large program so if I can get some slight aid in filling this part of the code I can do the rest quite easily by following the logic </p>
<p>Any help or direction to the information to aid me on an answer would be appreciated please.</p>
| <p>I think using 2 For loops (one for the columns and one for the rows) would work perfectly in your context. </p>
<p>You set a cell with your two variables for the address and compare it to your string. If it is the same, then you copy/paste and exit the loop of columns so it skips the rest of the row.</p>
<pre><code>Sub Find_First()
Dim FindString As String
Dim Rng As Range
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
With Sheets("DCCUEQ")
Dim s3r As Integer, i As Integer, j As Integer
s3r = 4 'this would determine the row in Sheet3
For i = 1 To 20
For j = 1 To 10 'Let's say the last column is J
Set Rng = .Cells(i, j)
If Rng = FindString Then
s3r = s3r + 1
.Range(.Cells(Rng.Row, 1), .Cells(Rng.Row, 6)).Copy Destination:=Worksheets("Sheet3").Range(Worksheets("Sheet3").Cells(s3r, 1), Worksheets("Sheet3").Cells(s3r, 6))
Exit For 'it will go to the next row
End If
Next j
Next i
If s3r = 4 Then MsgBox "Nothing found"
End With
End If
End Sub
</code></pre>
<p>Let me know if this way suits you.</p>
|
Runtime defined global const variable in C++ <p>I want to declare a global const variable that is defined at runtime. That is, I want to prompt the user for a value and assign it to a const global variable that I don't want to be modified during the execution of the program. </p>
<p>If I wanted a const variable in the <code>main</code> I could do </p>
<pre><code>int tmp;
cin >> tmp;
const int var = tmp;
</code></pre>
<p>But if I want to use a global variable I can't because I have to declare it outside the <code>main</code>. For context, this is for high performance scientific computing. I want to define a set of physical constants that shouldn't change and that I need to access from anywhere. Is there any way I can do this?</p>
| <p>Write an init function for it:</p>
<pre><code>int init() {
int tmp;
cin >> tmp;
return tmp;
}
const int var = init();
</code></pre>
|
how to read endpoint address value from app.config <p>I have <code>asp.net web application</code> and have the following in my <code>app.config</code> file. </p>
<pre><code><system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Test" />
<binding name="Test1">
<security mode="Test" />
</binding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://test:90001"
binding="basicHttpBinding" bindingConfiguration="Test"
contract="Test" name="HTTP_Port" />
</client>
</system.serviceModel>
</code></pre>
<p>How i can <code>get/read endpoint address</code> value?</p>
<p>I have come accross the this <a href="http://stackoverflow.com/questions/3214385/how-to-get-this-config-value-from-app-config">solution</a> but it is not working for me asking for exe file path. Not sure which exe path file?</p>
| <pre><code> var serviceModel = ServiceModelSectionGroup.GetSectionGroup(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
var endpoints = serviceModel.Client.Endpoints;
foreach (ChannelEndpointElement e in endpoints)
{
if (e.Name == "HTTP_Port")
Console.WriteLine(e.Address);
}
Console.ReadLine();
</code></pre>
<p>To read endpoints from appconfig you need to add reference of System.ServiceModel.Configuration and use GetSectionGroup method which return the serviceModel group and you can access all the endpoints in that section,if you just need the one you can access specific with the endpoint name.</p>
<p>Also in the appconfig you provided the port is invalid, I got and error while reading the url with that port I assume you just added that as an example.</p>
|
select specific column from panads MultiIndex dataframe <p>I have a MultiIndex dataframe with 200 columns, I would like to select an specific column from that. Suppose, df is some part of my dataframe:</p>
<pre><code>df=
a b
l h l h l h l
cold hot hot cold cold hot hot
2009-01-01 01:00:00 0.1 0.9 0.4 0.29 0.15 0.6 0.3
2009-01-01 02:00:00 0.1 0.8 0.35 0.2 0.15 0.6 0.4
2009-01-01 03:00:00 0.12 0.7 0.3 0.23 0.23 0.8 0.3
2009-01-01 04:00:00 0.1 0.9 0.33 0.24 0.15 0.6 0.4
2009-01-01 05:00:00 0.17 0.9 0.41 0.23 0.18 0.75 0.4
</code></pre>
<p>I would like to select the values for this column[h,hot]. </p>
<p>My output should be:</p>
<pre><code>df['h','hot']=
a b
2009-01-01 01:00:00 0.9 0.6
2009-01-01 02:00:00 0.8 0.6
2009-01-01 03:00:00 0.7 0.8
2009-01-01 04:00:00 0.9 0.6
2009-01-01 05:00:00 0.9 0.75
</code></pre>
<p>I do appreciate that if someone guide me how can I select that. </p>
<p>Thank you in advance.</p>
| <p>For multi-index slicing as you desire the columns needs to be sorted first using <code>sort_index(axis=1)</code>, you can then select the cols of interest without error:</p>
<pre><code>In [12]:
df = df.sort_index(axis=1)
df['a','h','hot']
Out[12]:
0
2009-01-01 01:00:00 0.9
2009-01-01 02:00:00 0.8
2009-01-01 03:00:00 0.7
2009-01-01 04:00:00 0.9
2009-01-01 05:00:00 0.9
Name: (a, h, hot), dtype: float64
</code></pre>
|
Pass devise current_user to a method in a lib file <p>I am trying to pass the devise @current_user from my application_controller to a class method in a library file. This is to use the Twitter API. I can get it working by writing the various twitter methods in the application_controller file, but I was wondering how I would do it using a separate lib. file and class instead? The code is as follows:</p>
<p><strong>lib/twitter_api.rb</strong></p>
<pre><code>class TwitterApi
def self.our_public_tweets
client.user_timeline('BBCNews', count: 1, exclude_replies: true, include_rts: false)
end
def self.followers
client.followers.take(5)
end
def self.client
@client ||= Twitter::REST::Client.new do |config|
config.consumer_key = Rails.application.secrets.twitter_api_key
config.consumer_secret = Rails.application.secrets.twitter_api_secret
config.access_token = current_user.token
config.access_token_secret = current_user.secret
end
end
end
</code></pre>
<p><strong>application_controller.rb</strong></p>
<pre><code>class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
</code></pre>
<p><strong>view file: index.html.erb</strong></p>
<pre><code> <%= TwitterApi.our_public_tweets.each do |tweet| %>
<%= tweet.text %>
<% end %>
<%= TwitterApi.followers.each do |follower| %>
<%= follower.name %>
<% end %>
</code></pre>
| <p>I woudl make an instance of the class rather than using class methods.</p>
<pre><code>class UserTwitter
def initialize(user)
@user = user
end
def our_public_tweets
client.user_timeline('BBCNews', count: 1, exclude_replies: true, include_rts: false)
end
def followers
client.followers.take(5)
end
private
attr_reader :user
def client
@client ||= Twitter::REST::Client.new do |config|
config.consumer_key = Rails.application.secrets.twitter_api_key
config.consumer_secret = Rails.application.secrets.twitter_api_secret
config.access_token = user.token
config.access_token_secret = user.secret
end
end
end
</code></pre>
<p>Then in your controller</p>
<pre><code>def index
@user_twitter = UserTwitter.new(current_user)
end
</code></pre>
<p>Which then means in your view</p>
<pre><code><% @user_twitter.our_public_tweets.each do |tweet| %>
<%= tweet.text %>
<% end %>
<% @user_twitter.followers.each do |follower| %>
<%= follower.name %>
<% end %>
</code></pre>
|
datatables adding/removing data to text area <p>I'm trying to add the clicked row of datatables to a textarea and if the same row is clicked again, the data is searched in the textarea and if found removed.
(select/deselect)</p>
<p>If I select one row and the deselect it, it works great. But when I select more than one row and then return to deselect them, only the last selected row is being searched for and removed but not the others.</p>
<p>Any help?</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>$('#myTable tbody').on('click', 'tr', function() {
var str = $("#selectedref").text();
var ref = table.cell(this, 2).data();
if (str.indexOf(ref) != -1) {
var rmvref = ref + "\r\n";
$("#selectedref").html($("#selectedref").html().replace(rmvref, ""));
} else {
var addref = ref + "\r\n";
var str1 = addref.concat(str);
$("#selectedref").text(str1);
}
});</code></pre>
</div>
</div>
</p>
| <p>EDITED: Since you're using textarea:</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>$('#myTable tbody').on('click', 'tr', function() {
var str = $("#selectedref").val();
var ref = table.cell(this, 2).data();
if (str.indexOf(ref) != -1) {
var rmvref = ref + "\r\n";
$("#selectedref").val($("#selectedref").val().replace(rmvref, ""));
} else {
var addref = ref + "\r\n";
var str1 = addref.concat(str);
$("#selectedref").val(str1);
}
});</code></pre>
</div>
</div>
</p>
<hr>
<p>Try using < br> to do your linebreaks in your html instead of \r\n. </p>
<p>Your snippet works in this case: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var row1 = "test row 1\r\n";
var row2 = "test row 2\r\n";
var row3 = "test row 3\r\n";
str = row3.concat(row2.concat(row1));
str = str.replace(row2, "");</code></pre>
</div>
</div>
</p>
<p>But as soon as you replace str with an element.innerHTML it doesn't work because it doesn't treat newlines the same way.</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>$('#myTable tbody').on('click', 'tr', function() {
var str = $("#selectedref").text();
var ref = table.cell(this, 2).data();
var strref = ref + "<br>";
if (str.indexOf(ref) != -1) {
$("#selectedref").html($("#selectedref").html().replace(strref, ""));
} else {
var str1 = strref.concat(str);
$("#selectedref").text(strref);
}
});</code></pre>
</div>
</div>
</p>
<p>Edited with working code</p>
|
ServiceM8 api email - how to relate to job diary <p>I can send an email from a ServiceM8 account through the ServiceM8 API 'message services' (<a href="http://developer.servicem8.com/docs/platform-services/message-services/" rel="nofollow">http://developer.servicem8.com/docs/platform-services/message-services/</a>), and read the resulting ServiceM8 message-id. </p>
<p>But I would like to relate that message to a specific job within ServiceM8, so that it will appear as an email item in that job's diary in the ServiceM8 web application. (Emails sent from within the ServiceM8 web application are related to the diary and appear there - my question is about how to do this from the API).</p>
<p>Worst case, I could create a new 'Note' containing the email text and add that to the job in the hope that it would show up in the diary in the web application as a note. </p>
<p>But I want to check there isn't an easier way since sending the email results in there already being a relatable message-id available within ServiceM8.</p>
<p>Thanks</p>
| <p>Using the messaging services API, can't be done. Using the web API, you can do just that.</p>
<p>There's an authorisation code required, which is specific to your account and to this function, you only need to retrieve it once, and then you can integrate that specific URL into your code. It's contained within the ClientSidePlatform_PerSessionSetup URL.</p>
<p>Here is a script that will grab the E-mail URL specific to your login:</p>
<p><strong>Syntax:</strong> <code>./getsm8emailurl.sh "email@address.com" "password"</code></p>
<pre><code>#!/usr/bin/env bash
#getsm8emailurl.sh
#Create Basic auth
user="$1"
pass="$2"
pass="$(echo -n "${pass}" | md5sum | cut -f1 -d' ')"
auth="$(echo -n "${user}:${pass}" | base64)"
#Get Account specific e-mail url
email_url="https://go.servicem8.com/$(curl --compressed -s -L "https://go.servicem8.com/$(curl --compressed -s -L "https://go.servicem8.com/" -H "Authorization: Basic $auth" | grep -o 'ClientSidePlatform_PerSessionSetup.[^"]*' | grep -v "s_boolFailover")" -H "Authorization: Basic $auth" | grep -o "PluginEmailClient_SendEmail.[^']*")"
#Output base e-mail URL
echo "$email_url"
</code></pre>
<p>Once you have the email url, (will start with <code>https://go.servicem8.com/PluginEmailClient_SendEmail</code> and will end with the s_auth code), you can use it like any other rest endpoint.</p>
<p><strong>Required Header Values:</strong> </p>
<ul>
<li>Authorization (same as regular API)</li>
</ul>
<p><strong>Required Post Params:</strong></p>
<ul>
<li><strong>s_form_values</strong>=<code>"guid-to-cc-subject-msg-job_id-attachedFiles-attachedContacts-strRegardingObjectUUID-strRegardingObject-boolAllowDirectReply"</code>
(these have to stay just as they are)</li>
<li><p><strong>s_auth</strong>="your_account_s_auth_code"</p></li>
<li><p><strong>to</strong>="recipient@domain.com"</p></li>
</ul>
<p><strong>Optional Post Params:</strong></p>
<ul>
<li><p><strong>subject</strong>="subject"</p></li>
<li><p><strong>msg</strong>="html message body"</p></li>
<li><p><strong>boolAllowDirectReply</strong>="true|false" (Can recipient reply directly to job diary)</p></li>
<li><p><strong>strRegardingObject</strong>="job|company"</p></li>
<li><p><strong>strRegardingObjectUUID</strong>="job|company uuid"</p></li>
</ul>
<hr>
<h2>DEMO</h2>
<pre><code>#!/usr/bin/env bash
#sendemail.sh
#demo here using random auth codes and uuids
curl --compressed -s "https://go.servicem8.com/PluginEmailClient_SendEmail" \
-H "Authorization: Basic dGVzdHVzZXJAdGVzdGRvbWFpbi5jb206dGVzdHBhc3M=" \
-d s_form_values=guid-to-cc-subject-msg-job_id-attachedFiles-attachedContacts-strRegardingObjectUUID-strRegardingObject-boolAllowDirectReply \
-d s_auth="6akj209db12bikbs01hbobi3r0fws7j2" \
-d boolAllowDirectReply=true \
-d strRegardingObject=job \
-d strRegardingObjectUUID="512b3b2a-007e-431b-be23-4bd812f2aeaf" \
-d to="test@testdomain.com" \
-d subject="Job Diary E-mail" \
-d msg="hello"
</code></pre>
<hr>
<p><em>Edit/Update/Disclaimer:
This information is for convenience and efficiency - memos, quick tasks, notifications, updates, etc. This isn't to be relied upon for critical business operations as it is undocumented, and since it does not process JS like a browser would, it could stop working if the inner workings of the service changed.</em></p>
|
Python How to sort list in a list <p>I'm trying to sort a list within a list. This is what I have. I would like to sort the inner namelist based on alphabetical order. Have tried using loops but to no avail. The smaller 'lists' inside happens to be strings so I can't sort() them as list. Error: 'str' object has no attribute 'sort'</p>
<pre><code>Names = [
[['John'] ['Andrea', 'Regina', 'Candice'], ['Charlotte', 'Melanie'],
['Claudia', 'Lace', 'Karen'] ['Ronald', 'Freddy'],
['James', 'Luke', 'Ben', 'Nick']]
]
</code></pre>
<p>I would like it to be sorted into: </p>
<pre><code>[
[['John'] ['Andrea', 'Candice', 'Regina'], ['Charlotte', 'Melanie'],
['Claudia', 'Karen', 'Lace'] ['Freddy', 'Ronald'],
['Ben', 'James', 'Luke', 'Nick']]
]
</code></pre>
<p>Thank you.
Edit: Sorry i made a mistake in the previous codes. Ive since edited it.</p>
| <pre><code>Names = [sorted(sublist) for sublist in Names]
</code></pre>
<p>This is a list comprehension that takes each sublist of <code>Names</code>, sorts it, and then builds a new list out of those sorted lists. It then makes <code>Names</code> that list</p>
|
Matlab function perfcurve falsely asserts ROC AUC = 1 <p>The perfcurve function in Matlab falsely, asserts AUC=1 when two records are clearly misclassified for reasonable cutoff values.
If I run the same data through a confusion matrix with cutoff 0.5, the accuracy is rightfully below 1.
The MWE contains data from one of my folds. I noticed the problem because I saw perfect auc with less than perfect accuracy in my results.</p>
<p>I use Matlab 2016a and Ubuntu 16.4 64bit.</p>
<pre><code>% These are the true classes in one of my test-set folds
classes = transpose([ones(1,9) 2*ones(1,7)])
% These are predictions from my classifier
% Class 1 is very well predicted
% Class 2 has two records predicted as class 1 with threshold 0.5
confidence = transpose([1.0 1.0 1.0 1.0 0.9999 1.0 1.0...
1.0 1.0 0.0 0.7694 0.0 0.9917 0.0 0.0269 0.002])
positiveClass = 1
% Nevertheless, the AUC yields a perfect 1
% I understand why X, Y, T have less values than classes and confidence
% Identical records are dealt with by one point on the ROC curve
[X,Y,T,AUC] = perfcurve(classes, confidence, positiveClass)
% The confusion matrix for comparison
threshold = 0.5
confus = confusionmat(classes,(confidence<threshold)+1)
accuracy = trace(confus)/sum(sum(confus))
</code></pre>
| <p>This simply means that there is <em>another cutoff</em> where the separation is perfect.</p>
<p>Try:</p>
<pre><code>threshold = 0.995
confus = confusionmat(classes,(confidence<threshold)+1)
accuracy = trace(confus)/sum(sum(confus))
</code></pre>
|
For Loop not giving correct results in R <p>I am trying to rename my Dataframe columns from 5th column to the total number of columns in my dataframe. Below, is the R loop which i have coded to rename.</p>
<pre><code>for(i in 5:NCOL(raw_data_ui)){
colnames(raw_data_ui[i]) <- paste(substr(colnames(raw_data_ui[i]),7,9), substr(colnames(raw_data_ui[i]),11,14), sep = "-")
}
</code></pre>
<p>But, My code didn't change the column name. For example my 5th column name is "Count.Feb.2015". After running the above code the name didn't change. </p>
<p>Could anyone tell me as what went wrong in my code.</p>
<p>Thanks,</p>
<p>Mohan</p>
| <p>You want to change the i'th colname, that is why the brackets need to stand after after the closing parenthesis as in </p>
<pre><code>colnames(raw_data_ui)[i]
</code></pre>
<p>To give a clearer view, some sore simpler example:</p>
<pre><code>d <- data.frame(a=1, b=2, c=3)
</code></pre>
<p>Your version of </p>
<pre><code>colnames(d[2])<-"Y"
</code></pre>
<p>will create a new instance/entity, which is the second row of d. A copy will be created once you change anything, like the name, and the link to <code>d</code> is lost.</p>
<pre><code>colnames(d)[2]<-"Y"
</code></pre>
<p>will change the second name and the reference to d is intact.</p>
|
horizontal scroll bar on resizing browser and right white space on smaller screens <p>i'm getting horizontal scroll bar when resizing the browser to 796px or less i'v tried to delete the sections one by one to find which one gives that issue but it didn't resolve it then i tried to delete some code starting from section products-4 to the end of the code and it's solved then i started to delete the sections one by one from products-4 to the end but that didn't help i don't know what's the link between them to make that scroll appear and when try to test using google chrome device toolbar it gives white space on the right side with mobile screen resolution so i'v tried to delete any css code has any relationship with size for products-4 or for any other section below it but nothing happened so i hope you guys can help me to find where the problem is </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-css lang-css prettyprint-override"><code>/* Products-4 */
#products-4{
background-color: #000;
margin-top:20px;
color:darkred;
}
#products-4 img{
border:1px solid white;
border-radius:10px;
padding:5px;
}
.col-centered{
float: none;
margin: 0 auto;
}
#products-4 h2 {
text-align:center;
}
#products-4 p{
text-align:center;
}
/* Team */
#team h2{
text-align:center;
}
#team{
text-align:center;
}
#team img{
border:1px solid black;
}
/* Contact */
#contact{
background-color: #000;
}
#contact .container{
height:500px;
}
.tab-content{
padding:50px;
border:1px solid white;
}
.tab-content .tab-content-inside{
padding:50px 0;
}
.tab-content .tab-content-inside a{
color:white;
text-decoration: none;
}
.tab-content .tab-content-inside .btn{
margin-top:30px;
}
.tab-content .tab-content-inside .btn-info{
margin-left:50px;
}
.tab-content .tab-content-inside .btn-info a{
padding-right:10px;
padding-left:10px;
}
.nav-tabs li a{
background-color: transparent !important;
color:red;
}
.nav-tabs .active a{
color:white !important;
}
.nav-tabs .active a:hover{
color:cornflowerblue !important;
}
.nav-tabs li a:hover{
background-color:white !important ;
color:cornflowerblue;
transition : all 1s;
-webkit-transition : all 1s;
-moz-transition : all 1s;
-o-transition : all 1s;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!-- Strart of products-4 -->
<section id="products-4">
<div class="container">
<div class="row">
<h1 class="text-center">More Products</h1>
<div class="row">
<div class="col-md-3">
<img class="img-responsive center-block" src="img/polo-pro2.png">
<h2>Polo Shirts</h2>
<p>And Of Course Paragraph here</p>
</div>
<div class="col-md-3">
<img class="img-responsive center-block" src="img/polo-pro2.png">
<h2>Polo Shirts</h2>
<p>And Of Course Paragraph here</p>
</div>
<div class="col-md-3">
<img class="img-responsive center-block" src="img/polo-pro2.png">
<h2>Polo Shirts</h2>
<p>And Of Course Paragraph here</p>
</div>
<div class="col-md-3">
<img class="img-responsive center-block" src="img/polo-pro2.png">
<h2>Polo Shirts</h2>
<p>And Of Course Paragraph here</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3 col-centered">
<img class="img-responsive center-block" src="img/polo-pro2.png">
<h2>Polo Shirts</h2>
<p>And Of Course Paragraph here</p>
</div>
</div>
</div>
</section>
<!-- End of Products-4-->
<!--Start of Team -->
<section id="team">
<div class="container">
<div class="row">
<h1>Our Team</h1>
<div class="col-md-4 col-md-offset-2">
<img src="img/face.png" class="img-circle" alt="">
<h2>The Manager</h2>
<p>Any pragraph here</p>
</div>
<div class="col-md-4">
<img src="img/face.png" class="img-circle" alt="">
<h2>The Sales Man</h2>
<p>Any pragraph here</p>
</div>
</div>
</div>
</section>
<!-- End Of Team -->
<!-- Start of contact -->
<section id="contact">
<div class="container">
<div class="row">
<h1>Contact Us</h1>
<div class="row">
<ul class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" href="#e-mails">E-mails</a>
</li>
<li>
<a data-toggle="tab" href="#phones">Phones</a>
</li>
<li>
<a data-toggle="tab" href="#address">Address</a>
</li>
<li>
<a data-toggle="tab" href="#social">Social Networks</a>
</li>
</ul>
<div class="tab-content">
<div id="e-mails" class="tab-pane fade in active">
<div class="tab-content-inside text-center">
<h1>Feel Free To Text Us Any Time Using This E-Mails</h1>
<div class="tab-content-content">
<button type="button" class="btn btn-primary">
<span class="fa fa-envelope-o fa-2x">
<a href="mailto:m.shawky@rt-wm.com">Manager</a>
</span>
</button>
<button type="button" class="btn btn-info">
<span class="fa fa-envelope-o fa-2x">
<a href="mailto:m.shawky@rt-wm.com">Sales</a>
</span>
</button>
</div>
</div>
</div>
<div id="phones" class="tab-pane fade">
All Phones Goes here
</div>
<div id="address" class="tab-pane fade">
Address Comes here
</div>
<div id="social" class="tab-pane fade">
Social Addresses goes here
</div>
</div>
</div>
</div>
</div>
</section>
<!--end of contact--></code></pre>
</div>
</div>
</p>
| <p>I can not replicate the side scroll however the white space is because you have a "Margin: 8px;" on your "body" if you add "body {margin:0;}" into your css that should fix your issue.</p>
<p>Let me know if that helped!</p>
|
How to check for partial string match in getelementById while scraping <p>I need to get value of this id: "price-including-tax-9926"</p>
<pre><code> <span class="price-including-tax">
<span class="label">Incl. Tax:</span>
<span class="price" id="price-including-tax-9926">
£70.21 </span>
</span>
</code></pre>
<p>This is the <a href="http://www.tradingdepot.co.uk/catalogsearch/result/?q=S362467" rel="nofollow">site</a> </p>
<p>This is what I've tried so far:</p>
<pre><code>Sub GetPriceData()
Dim IE As New InternetExplorer
Dim doc As HTMLDocument
Dim wk As Worksheet, frow As Long, urL As String, i As Long
Set wk = Sheet1
frow = wk.Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To frow
urL = Trim(wk.Range("B" & i))
With IE
.Navigate urL
.Visible = True
Do While IE.Busy
DoEvents
Loop
Set doc = .document
</code></pre>
<blockquote>
<pre><code> amt = doc.getElementById("price-inlcuding-tax-9926").innerText 'Run time error '91 Object variable with or with block not set
</code></pre>
</blockquote>
<pre><code> wk.Range("C" & i) = amt
End With
Next i
IE.Quit
Set IE = Nothing
End Sub
</code></pre>
<blockquote>
<p>I want to do this for several urls which will have the part of the id as constant i.e. : <code>"price-including-tax-"</code> and <code>"9926"</code> as variable is there a way I can search id using partial match or using <code>Like</code> </p>
</blockquote>
| <p>Your question re: can you partially match an ID, have a look at this <a href="http://stackoverflow.com/questions/4275071/javascript-getelementbyid-wildcard">post</a>. Hopefully it helps</p>
|
Custom Magento 2 container/banner <p>I'm trying to create my own magento 2 theme.
I want to add a header image to all pages on top. </p>
<pre><code>-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="header.panel">
<block class="Magento\Framework\View\Element\Html\Links" name="header.links">
<arguments>
<argument name="css_class" xsi:type="string">header links</argument>
</arguments>
</block>
</referenceContainer>
<referenceBlock name="logo">
<arguments>
<argument name="logo_img_width" xsi:type="number">250</argument>
<argument name="logo_img_height" xsi:type="number">100</argument>
</arguments>
</referenceBlock>
<referenceContainer name="footer">
<block class="Magento\Store\Block\Switcher" name="store_switcher" as="store_switcher" after="footer_links" template="switch/stores.phtml"/>
</referenceContainer>
<referenceBlock name="report.bugs" remove="true"/>
<move element="copyright" destination="before.body.end"/>
</body>
</page>
</code></pre>
<p>This is my default.xml file.</p>
<p>i thought i could add a reference block inside my default.xml like this:</p>
<pre><code> <referenceContainer name="header.panel">
<block class="Magento\Framework\View\Element\Html\Links" name="header.links">
<arguments>
<argument name="css_class" xsi:type="string">header links</argument>
</arguments>
</block>
</referenceContainer>
</code></pre>
<p>But instead of that my banner. How do i do this?</p>
| <pre><code> <referenceContainer name="header.panel">
<block class="Magento\Framework\View\Element\Html\Links" name="header.links">
<arguments>
<argument name="css_class" xsi:type="string">header links</argument>
</arguments>
</block>
</referenceContainer>
</code></pre>
<p>Note.. This is how you add a block right. </p>
<pre><code><block class="Magento\Store\Block\Switcher" name="store_switcher" as="store_switcher" after="footer_links" template="switch/stores.phtml"/>
</code></pre>
<p>Create a block </p>
<pre><code><block class="Magento\Framework\View\Element\Template" name="banner" template="banner.phtml"/>
</code></pre>
<p>and put it inside of </p>
<pre><code><referenceContainer name="header.panel">
<block class="Magento\Framework\View\Element\Html\Links" name="header.links">
<arguments>
<argument name="css_class" xsi:type="string">header links</argument>
</arguments>
</block>
<block class="Magento\Framework\View\Element\Template" name="banner" template="banner.phtml"/>
</referenceContainer>
</code></pre>
<p>You will have to create within the following folders.
app/code/YouTheme/Banners/view/frontend/templates/banner.phtml </p>
<p>Where banner.phtml is where html code will be.</p>
<p>I hope it gave you an idea on how to solve it.</p>
|
Multiple language sitemap gives validation error "No matching global element declaration available" <p>I have been trying to follow <a href="https://support.google.com/webmasters/answer/2620865?hl=en" rel="nofollow">Google's recommendation for multi-lingual sitemaps</a>. However when I try this on my site I get the error:</p>
<blockquote>
<p>Error 1845: Element '<code>{http://www.w3.org/1999/xhtml}link</code>': No matching global element declaration available, but demanded by the strict wildcard.</p>
</blockquote>
<p>Even when I paste Google's example into the sitemap validator I get the same error. Is there something I am missing here?</p>
<p>Here is Google's example I've been pasting into the validator:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url>
<loc>http://www.example.com/english/</loc>
<xhtml:link
rel="alternate"
hreflang="de"
href="http://www.example.com/deutsch/"
/>
<xhtml:link
rel="alternate"
hreflang="de-ch"
href="http://www.example.com/schweiz-deutsch/"
/>
<xhtml:link
rel="alternate"
hreflang="en"
href="http://www.example.com/english/"
/>
</url>
<url>
<loc>http://www.example.com/deutsch/</loc>
<xhtml:link
rel="alternate"
hreflang="en"
href="http://www.example.com/english/"
/>
<xhtml:link
rel="alternate"
hreflang="de-ch"
href="http://www.example.com/schweiz-deutsch/"
/>
<xhtml:link
rel="alternate"
hreflang="de"
href="http://www.example.com/deutsch/"
/>
</url>
<url>
<loc>http://www.example.com/schweiz-deutsch/</loc>
<xhtml:link
rel="alternate"
hreflang="de"
href="http://www.example.com/deutsch/"
/>
<xhtml:link
rel="alternate"
hreflang="en"
href="http://www.example.com/english/"
/>
<xhtml:link
rel="alternate"
hreflang="de-ch"
href="http://www.example.com/schweiz-deutsch/"
/>
</url>
</urlset>
</code></pre>
| <p>It seems the validator you use, <a href="http://tools.seochat.com/tools/site-validator/" rel="nofollow">http://tools.seochat.com/tools/site-validator/</a>, doesnât support <a href="http://www.sitemaps.org/protocol.html#extending" rel="nofollow">additional namespaces</a> (like <code>xhtml</code> in your example).</p>
|
Responsive CSS: viewport and 100% doesnt fit so much <p>I putted this tag in my code:</p>
<pre><code><meta name="viewport" content="width=device-width; initial-scale=1.0;">
</code></pre>
<p>And then, after a media query i asked</p>
<pre><code>header {
width: 100% !important;
}
main {
width: 100% !important;
}
</code></pre>
<p>But I have a serious difference when i go to the site in my iPhone. </p>
<p>Safari zoom in the text (main) and the header is much bigger in width. </p>
<p>If I take off the meta tag its too small.</p>
<p>Thanks for your help.</p>
| <p>You use <strong>semicolon</strong> to separate content attribute's values, where you should use <strong>comma</strong> instead, like:</p>
<pre><code> <meta name="viewport" content="width=device-width, initial-scale=1">
</code></pre>
|
Message is received two times in xmpp smack library <p>I am creating an android chat application using xmpp smack library.I have create a background service to listen to incoming chats and use an application class to initialize the xmpp connection object.
The problem is the chatCreated function of chat listener is called twice therefore duplicate message is shown..
This is my application class where i have created connection</p>
<p>Authenticate.java</p>
<pre><code>public class Authenticate extends Application {
private static final String DOMAIN = StaticVariables.chatServer;
private static final String HOST = StaticVariables.chatServer;
private static final int PORT = 5222;
static AbstractXMPPConnection connection ;
String username,password;
private boolean connected;
@Override
public void onCreate() {
super.onCreate();
}
public AbstractXMPPConnection initializeXMPPTCPConnection(String username,String password) {
Log.e("APPLICATION", "username: "+username);
Log.e("APPLICATION", "password: "+password);
Log.i("APPLCATION", "initializeXMPPTCPConnection calle:");
this.username=username;
this.password=password;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(username, password);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection=connectConnection();
Log.e("APPLICATION", "initializeXMPPTCPConnection: "+connection.isConnected());
return connection;
}
public AbstractXMPPConnection getConnection(){
return connection;
}
public AbstractXMPPConnection connectConnection()
{
AsyncTask<Void, Void, AbstractXMPPConnection> connectionThread = new AsyncTask<Void, Void, AbstractXMPPConnection>() {
@Override
protected AbstractXMPPConnection doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect().login();
Log.e("Application", "doInBackground: "+connection.isConnected());
//login();
connected = true;
//sendMsg();
} catch (IOException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return connection;
}
@Override
protected void onPostExecute(AbstractXMPPConnection connection2) {
super.onPostExecute(connection2);
// sendMsg(message.getText().toString());
Log.e("APPLICATION", "onPostExecute: "+connection2.isConnected());
connection=connection2;
}
};
try {
connection=connectionThread.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.e("Application", "connectConnection: "+connection.isConnected());
return connection;
}
public void login() {
try {
connection.login(username, password);
Log.e("APPLICATIPN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
}
</code></pre>
<p>This is the code through which i am calling connection instance</p>
<pre><code>connection=((Authenticate)getApplication()).getConnection();
</code></pre>
<p>Listener function</p>
<pre><code>public void listenChat(String name){
ChatManager manager = ChatManager.getInstanceFor(connection);
manager.addChatListener(new ChatManagerListener() {
@Override
public void chatCreated(final Chat chat, boolean createdLocally) {
System.out.println("Created chat");
chat.addMessageListener(new ChatMessageListener() {
@Override
public void processMessage(final Chat chat, final org.jivesoftware.smack.packet.Message message) {
//This is called twice
}
}
});
}
});
}
</code></pre>
<p>I am a beginner in android and as well in xmpp.Please tell me where i am wrong how can i resolve it</p>
| <p>You have to fix createdLocally usage in chatCreated method. </p>
<p>Just add the listener if is not createdLocally like this:</p>
<pre><code>public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally)
{
chat.addMessageListener(new ChatMessageListener()...);
}
}
</code></pre>
|
"require is not defined" error <p>I just started a <a href="http://ionicframework.com/docs/v2/getting-started/tutorial/" rel="nofollow">new project</a> with ionic v2 and added <a href="https://github.com/danmactough/node-feedparser" rel="nofollow">feedparser</a> to my project.</p>
<p>By using</p>
<pre><code>ionic serve
</code></pre>
<p>I get a blank screen and the error</p>
<blockquote>
<p>Uncaught ReferenceError: require is not defined
This is the code that is used to load the dependencies:</p>
</blockquote>
<pre><code>declare var require: any;
var Feedparser = require('feedparser');
var request = require('request');
</code></pre>
<p>The first point is this part:</p>
<pre><code>declare var require: any;
</code></pre>
<p>It has been mentioned in another thread, so I just put it there.</p>
<p>So I did some research and checked whether I have requirejs and stuff like that, but it didn't solved my problem.</p>
<p>After some time, I create another ionic project with an older version and it was no problem to include the feedparser examples - even with <code>declare var require:any;</code> thing.
So probably something has been changed with the release of ionic v2 and I really would like to modules like in the RC-Version.</p>
<p>Thank you.</p>
<p>EDIT:
Imports like </p>
<pre><code>import * as Feedparser from 'feedparser';
</code></pre>
<p>are also not working.</p>
| <p>I guess you need to install these node dependencies in your machine. </p>
<p>Use the below commands to have them installed in your project, </p>
<p>For RequireJS,</p>
<pre><code>npm install --save requirejs
</code></pre>
<p>For FeedParser,</p>
<pre><code>npm install --save feedparser
</code></pre>
<p>If you want them to install the above packages globally use <code>-g</code> instead of <code>--save</code> switch.</p>
<p>Hope this helps!</p>
|
Cassandra consistency Issue <p>We have our Cassandra cluster running on AWS EC2 with 4 nodes in the ring. We have face data inconsistency issue. We changed consistency level two while using "cqlsh" shell, the data inconsistency issue has been solved. </p>
<p>But we dont know "How to set consistency level on Cassandra cluster?"</p>
| <p>Consistency level can be set at per session or per statement basis. You will need to check the consistency level of writes and reads, to get a strong consistency your R + W ( read consistency + write consistency ) should be greater than your replication factor. </p>
|
React Jest to match snapshot, crash when testing component with child components <p>I have some components with child components from third parties addons/libraries. I use Jest for my unit test and <code>toMatchSnapshot()</code> method. I tried to exclude the child components with <code>jest.unmock('ChildComponet.js')</code> and i get this error:</p>
<p><em>jest.unmock('ChildComponet.js') was called but automocking is disabled. Remove the unnecessary call to <code>jest.unmock</code> or enable automocking for this test via <code>jest.enableAutomock();</code>. This warning is likely a result of a default configuration change in Jest 15.</em></p>
<p>I enabled <code>jest.enableAutomock();</code> and now i have tis error:</p>
<p><em>TypeError: Cannot read property 'DEFINE_MANY' of undefined</em></p>
<p>I put this on my package.json but nothing happens:</p>
<p><em>"unmockedModulePathPatterns": ["rootDir/node_modules/react"]</em></p>
<p>Any ideas?</p>
<p>is the correct way to make unit test of components in React?</p>
| <p>The easiest way to mock out react components I found so far is to use:</p>
<pre><code>jest.mock('component', ()=> 'ComponentName')
</code></pre>
<p>before you the import statement of the module you want to test.</p>
<p>The first parameter is either the name of global npm module or the path to your local component (note that the path in relative to your test file). The second parameter is just a function that returns a string (I always return the same name I use in jsx). This will result in a dump component that does nothing but have the same name as your original component. So in your snapshot you will see no difference, beside the mocked component will not render any childs.</p>
<p>Now to the error messages you got.</p>
<blockquote>
<p>jest.unmock('ChildComponet.js') was called but automocking is disabled...</p>
</blockquote>
<p>The problem is that you use <code>jest.unmock</code> instead of <code>jest.mock</code>. Jest has the feature to automatically mock all the dependencies of your modules. With auto mock enabled you could use <code>jest.unmock</code> to get the real implantation for some essential libs like lodash or moment. As the auto mock feature was confusing for a lot of people, they decide to make it optional. Tldr you tried to un mock something that was not mocked in the first place as you don't enabled auto mocking.</p>
<blockquote>
<p>TypeError: Cannot read property 'DEFINE_MANY' of undefined</p>
</blockquote>
<p>When you enable auto mocking every imported module is replaced with <code>undefined</code>. I cant say much about the <code>unmockedModulePathPatterns</code> setting but I believe you have to use the same pattern you use to import the module, so if it is a global you don't have to put the path to the <code>node_modules</code> folder in it.</p>
|
Concatenate dictionary values in Swift <p>I created a dictionary in Swift like:</p>
<pre><code>var dict:[String : Int] = ["A": 1, "B": 2, "C": 3, "D": 4]
print(dict["A"]!)
</code></pre>
<p>The computer prints number 1, but how do I concatenate these values such that the output is 1234 instead of a single integer?</p>
| <p>The key-value pairs in a <code>Dictionary</code> are unordered. If you want to access them in a certain order, you must sort the keys yourself:</p>
<pre><code>let dict = ["A": 1, "B": 2,"C": 3,"D": 4]
let str = dict.keys
.sorted(by: <)
.map { dict[$0]! }
.reduce ("") { $0 + String($1) }
</code></pre>
<p>Or alternatively:</p>
<pre><code>let str = dict.keys
.sorted(by: <)
.map { String(dict[$0]!) }
.joined()
</code></pre>
<p>No idea about the relative performance of the two as I haven't benchmarked them. But unless your dictionary is huge, the difference will be minimal.</p>
|
send checkbox values to php through ajax results in null <p>I am trying to send the values of 7 jquery checkboxes to php via ajax. I am attempting to put the values in an array and serialize the array in ajax. Ultimately, I would like to use the values of the checkboxes as conditions in a MySQL WHERE clause. My ajax completes successfully but the value of the array is always null no matter what method I try using. </p>
<p>CODE: <strong><em>note: I've updated the code on here to reflect the suggested edits provided in the answers.</em></strong></p>
<p>My HTML code:</p>
<pre><code><label for="prestage_select">Prestage</label>
<input type="checkbox" name="revenue_checkboxes[]" id="prestage_select" class="revenuechbxs" value="Prestage">
<label for="validation_select">Validation</label>
<input type="checkbox" name="revenue_checkboxes[]" id="validation_select" class="revenuechbxs" value="Validation">
<label for="scheduling_select">Scheduling</label>
<input type="checkbox" name="revenue_checkboxes[]" id="scheduling_select" class="revenuechbxs" value="Scheduling">
<label for="production_select">Production</label>
<input type="checkbox" name="revenue_checkboxes[]" id="production_select" class="revenuechbxs" value="Production">
<label for="needsBOL_select">Needs BOL</label>
<input type="checkbox" name="revenue_checkboxes[]" id="needsBOL_select" class="revenuechbxs" value="Needs BOL">
<label for="shpAcct2Close_select">Shipped: Account to Close</label>
<input type="checkbox" name="revenue_checkboxes[]" id="shpAcct2Close_select" class="revenuechbxs" value="Shipped: Acctg. To Close Out">
<label for="movedToComplete_select">Moved to Complete for Selected Period</label>
<input type="checkbox" name="revenue_checkboxes[]" id="movedToComplete_select" class="revenuechbxs" value="Complete">
</code></pre>
<p>My Ajax Code: </p>
<pre><code>j("#create_submit").click(function(){
//send Revenue Data values to php using ajax.
var revenuechbxarray = j('.revenuechbxs:checked').val();
var revenuefrom = j('#revenuefrom').val();
var revenueto = j('#revenueto').val();
j.ajax ({
method: 'POST',
url: "revenue_report.php",
data: { revenuefromtext: revenuefrom, revenuetotext: revenueto, revenuechbx: revenuechbxarray },
success: function( response ) {
j('#fieldset_ReportDiv').html(response);
}
});
console.log(revenuechbxarray);
</code></pre>
<p>My PHP Code:</p>
<pre><code><?php
include('inc.php');
//Get date range.
$revenuefromajax=$_POST['revenuefromtext'];
$revenuetoajax=$_POST['revenuetotext'];
$revenuefromstring = strtotime($revenuefromajax);
$revenuetostring = strtotime($revenuetoajax);
$revenuefrom=date("Y-m-d", $revenuefromstring);
$revenueto=date("Y-m-d", $revenuetostring);
//Get selected Status Values.
$revenue_check = $_POST['revenuechbx']; //
print_r($revenue_check); //displays result of one checkbox (the first selected on) but not more than one...
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
//echo 'MySQL Connected successfully.'."<BR>";
$conn->select_db("some database name"); /////Database name has been changed for security reasons/////////
if(! $conn->select_db("some database name") ) {
echo 'Could not select database. '."<BR>";
}
// echo 'Successfully selected database. '."<BR>";
//Select Data and Display it in a table.
$sql = "SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, FORMAT((lineitems.width * lineitems.height) /144, 2 ) AS sqft, lineitems.quantity AS qty, FORMAT((invoices.totalprice / ((lineitems.width * lineitems.height) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice) / lineitems.quantity), 2) AS avgunitrevenue
FROM clients
INNER JOIN invoices ON clients.id = invoices.clientid
INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
WHERE invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."'
ORDER BY invoices.id DESC";
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<tr>
<th>Customer</th>
<th>SG</th>
<th>Revenue</th>
<th>SQ FT</th>
<th>AVG Revenue Per SQ FT</th>
<th>Number of Units</th>
<th>AVG Revenue Per Unit</th>
</tr>";
if ($result = $conn->query($sql)) {
// fetch associative array
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sqft'] ."&nbsp;&nbsp;". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['qty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
}
echo "</table>";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Free the result variable.
$result->free();
}
//Close the Database connection.
$conn->close();
?>
</code></pre>
<p>I have tried several different suggestions for sending the values to php but the value is always null.</p>
<p>Note: I included the other ajax call for revenueto and revenuefrom date. This call is successful and my table displays correctly based off those dates. I just can't seem the get actual values for my selected checkboxes from the same page as the dates.</p>
| <p>You are using a class selector while your checkboxes does not have class attributes</p>
|
How to use git staging as temporary space? <p>I am trying to figure out the easiest way to switch back and forth between version of code to test while making changes. When I'm in the middle of something and want to test out something else I'll use git stash but that seems like overkill in this situation as it can't be done on individual files.</p>
<p>What I tried to do was <code>git add {file}</code> to temporarily store changes and then <code>git checkout {file}</code> to get back to the previous state. The intention being to have staging as a temporary holding area for a file and then pull the staged file back into my working directory. I was surprised though that after staging a file the checkout had no effect on the file in the working directory. Is there a series of command options that would allow this work flow to function as I want it to?</p>
<p>Update 1:</p>
<p>Based on docs it appears this would work if there was a way for step 2 to not overwrite the index</p>
<ol>
<li>git add {file}</li>
<li>git checkout HEAD {file}</li>
<li>git checkout {file}</li>
</ol>
<p>Update 2:</p>
<p>After being inspired by ElpieKay's post to look at writing output of a command to file I found <a href="http://stackoverflow.com/questions/7856416/view-a-file-in-a-different-git-branch-without-changing-branches">another answer</a> that overcomes the limitation of step 2 above. With <code>git show HEAD:{file} > {file}</code> I can now overwrite the working directory version of the file without overwriting index. Then calling checkout pulls the index version into the working directory. Combined with git checkout-index I get this...</p>
<ol>
<li>git add {file}</li>
<li>git show HEAD:{file} > {file}</li>
<li>git checkout-index -f</li>
</ol>
| <p>You could simply use <code>git commit</code> if <code>git stash</code> is not good enough.</p>
<p>First let's make a tag to track the tip of the current branch.</p>
<pre><code> git tag start
</code></pre>
<p>After making the changes to some files,</p>
<pre><code> git add .
git commit -m 'version 1'
git tag v1
#do the test
</code></pre>
<p>Make some other changes,</p>
<pre><code> git reset start --hard
git add .
git commit -m 'version 2'
git tag v2
</code></pre>
<p>Supposing you are interested in different versions of <code>file-a</code>, use <code>git checkout v1 -- file-a</code> or <code>git checkout v2 -- file-a</code> or <code>git checkout start -- file-a</code> to switch <code>file-a</code> in the work tree. In the end, <code>git tag -d start v1 v2</code> to remove the tags. And before that, run <code>git reset start --hard</code> if necessary. Branches can also work instead of tags.</p>
<p>To manipulate blobs directly is another approach.</p>
<pre><code> #make some changes to file-a
#modify, modify, modify
#create the blob of this file-a and make a tag for it.
git tag v1 $(git hash-object -w file-a)
#restore file-a to HEAD's version
git checkout -- file-a
#make some other changes to file-a
#oh, oh, ah, ah
#create the blob of this file-a and make another tag for it.
git tag v2 $(git hash-object -w file-a)
#now we want version1's file-a
git cat-file -p v1 > file-a
#now we want version2's file-a
git cat-file -p v2 > file-a
</code></pre>
<p>After all is done, run <code>git tag -d v1 v2</code>. As to the temp blobs, just leave them alone if you don't need them any more and they won't bother you. </p>
|
linux source command not working when building Dockerfile <p>I have a Dockerfile that defines a Ruby on Rails stack.</p>
<p>Here is the Dockerfile:</p>
<pre><code>FROM ubuntu:14.04
MAINTAINER Junayed Mizan <m.j.mizan@gmail.com>
# Update
RUN apt-get update
# Install Ruby and Rails dependencies
RUN apt-get install -y \
ruby \
ruby-dev \
build-essential \
libxml2-dev \
libxslt1-dev \
zlib1g-dev \
libsqlite3-dev \
nodejs \
curl
RUN gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
RUN curl -sSL https://get.rvm.io | bash -s stable --rails
RUN /bin/bash -c "source /usr/local/rvm/scripts/rvm"
# Install Rails
RUN gem install rails
# Create a new Rails app under /src/my-app
RUN mkdir -p /src/new-app
RUN rails new /src/new-app
WORKDIR /src/my-app
# Default command is to run a rails server on port 3000
CMD ["rails", "server", "--binding", "0.0.0.0", "--port" ,"3000"]
EXPOSE 3000
</code></pre>
<p>When I execute the command <code>docker build -t anotherapp/my-rails-app .</code> I get the following error:</p>
<blockquote>
<p>Removing intermediate container 3f8060cdc6f5<br>
Step 8 : RUN gem install rails<br>
---> Running in 8c1793414e63<br>
ERROR: Error installing rails:<br>
activesupport requires Ruby version >= 2.2.2.<br>
The command '/bin/sh -c gem install rails' returned a non-zero code: 1 </p>
</blockquote>
<p>It looks like the command <code>source /usr/local/rvm/scripts/rvm</code> isn't working during the build.</p>
<p>I'm not sure exactly why this is happening.</p>
| <p>From the <a href="https://docs.docker.com/engine/reference/builder" rel="nofollow">docker builder reference</a>, each RUN command is run independently. So doing <code>RUN source /usr/local/rvm/scripts/rvm</code> does not have any effect on the next RUN command. </p>
<p>Try changing the operations which require the given source file as follows</p>
<pre><code> RUN /bin/bash -c "source /usr/local/rvm/scripts/rvm ; gem install rails"
</code></pre>
|
WebSocket timeout in Firefox (and Chrome) <p>I use <a href="https://github.com/ghedipunk/PHP-Websockets" rel="nofollow">PHP WebSockets</a>.</p>
<p>I've set a long timeout on the server:</p>
<pre><code>protected function connected ($user) {
socket_set_option($user->socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>7200, 'usec'=>0));
socket_set_option($user->socket, SOL_SOCKET, SO_SNDTIMEO, array('sec'=>7200, 'usec'=>0));
}
</code></pre>
<p>Nevertheless Firefox disconnects after about 5 minutes. I strongly suspect that this is because a timeout in Firefox.</p>
<p>What is the exact value of the timeout? How my JaveScript can access it? Can I change it?</p>
<p>The same applies to Chrome.</p>
| <p>What you are setting with SO_RCVTIMEO & SO_SNDTIMEO is the timeout for socket <code>send</code> and <code>recv</code>. If within the set time, the <code>send</code> and <code>recv</code> do not perform their actions, error is returned.Its not related to the disconnect you are seeing</p>
<p>The disconnect that you see is probably due to inactivity on the TCP connection. Either the client or the server is setting up a idle line timeout of 5 minutes. May be you should setup application level keep-alive messages to keep the TCP connection intact. </p>
|
Retrieve GroupName in Listview Grouping in WPF <p>I've setup a ListView with grouping and I would like to retrieve the GroupName when I right click on the group in MVVM. I've placed a <code>ContextMenu</code> on my group style, and I was trying to use the EventToCommand from System.Windows.Interactivity to get the underlying item.</p>
<p>Here the relevant part:</p>
<pre><code><ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Expander IsExpanded="False" Template="{StaticResource CustomizedExpander}" Background="#FFEBEBEB" BorderThickness="0" ContextMenu="{StaticResource GroupContextMenu}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseRightButtonDown">
<i:InvokeCommandAction Command="{Binding Path=OnCategorySelected}" CommandParameter="{Binding Name}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Expander.Header>
<StackPanel Orientation="Horizontal">
<!--N.B. The "Name" property is part of the CollectionViewSource-->
<TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="#FF767676" VerticalAlignment="Bottom" />
<TextBlock Text="{Binding ItemCount}" Foreground="#FF454545" FontWeight="Bold" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
<TextBlock Text=" item(s)" Foreground="#FF767676" FontStyle="Italic" VerticalAlignment="Bottom" />
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
</code></pre>
<p>I don't know if it's the right way to do it but it seems the command is not triggered at all.</p>
<p>Any suggestion?</p>
<p>UPDATE:</p>
<p>The whole thing was much simpler than I thought. The interaction part was not required at all. Fixing the binding is enough to get the underlying category when the context menu is shown:</p>
<pre><code><ListView ItemsSource="{Binding Modifications}" SelectedItem="{Binding SelectedItem}">
<ListView.Resources>
<ContextMenu x:Key="ItemContextMenu">
<MenuItem Header="Execute" Command="{Binding Path=DataContext.OnExecuteScript, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" Background="WhiteSmoke" Visibility="{Binding CanExecute, Converter={StaticResource BooleanToVisibilityConverter}}" />
<MenuItem Header="Execute up to this" Command="{Binding Path=DataContext.OnExecuteScriptUpToThis, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" Background="WhiteSmoke" Visibility="{Binding CanOnlyBeExecutedSequentially, Converter={StaticResource BooleanToVisibilityConverter}}" />
<MenuItem Header="Drop" Command="{Binding Path=DataContext.OnExecuteDrop, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" Visibility="{Binding Drop, Converter={StaticResource BooleanToVisibilityConverter}}" Background="WhiteSmoke" />
<MenuItem Header="Dump" Command="{Binding Path=DataContext.OnExecuteDump, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" Visibility="{Binding CanDump, Converter={StaticResource BooleanToVisibilityConverter}}" Background="WhiteSmoke" />
</ContextMenu>
<ContextMenu x:Key="GroupContextMenu">
<MenuItem Header="Dump all" Command="{Binding Path=DataContext.OnExecuteDumpAll, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" CommandParameter="{Binding Name}" Background="WhiteSmoke" />
</ContextMenu>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn Header="Type" Width="120" DisplayMemberBinding="{Binding Type}" />
<GridViewColumn Header="Object Name" Width="Auto" DisplayMemberBinding="{Binding DisplayName}" />
<GridViewColumn Header="" Width="50">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Deploy}" IsHitTestVisible="False" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Object Name" Width="300" DisplayMemberBinding="{Binding ObjectName}" />
</GridView>
</ListView.View>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}" BasedOn="{StaticResource MetroListViewItem}" >
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Drop}" Value="True">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="ContextMenu" Value="{StaticResource GroupContextMenu}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Expander IsExpanded="False" Template="{StaticResource CustomizedExpander}" Background="#FFEBEBEB" BorderThickness="0">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<!--N.B. The "Name" property is part of the CollectionViewSource-->
<TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="#FF767676" VerticalAlignment="Bottom" />
<TextBlock Text="{Binding ItemCount}" Foreground="#FF454545" FontWeight="Bold" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
<TextBlock Text=" item(s)" Foreground="#FF767676" FontStyle="Italic" VerticalAlignment="Bottom" />
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
</code></pre>
| <p>First of all, i think i've figured out why your Command isnt firing.</p>
<p>Since you are in an Template, the DataContext has Changed. Therefore your CommandBinding should look like this:</p>
<pre><code><i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.OnCategorySelected}" CommandParameter="{Binding}"/>
</code></pre>
<p>Also, your CommandParameter should not be <code>Name</code> because you'll only get a string in the end instead the whole Object. </p>
<p>If you use my above code you will get the whole <code>CollectionViewGroup</code> instead. In said <code>CollectionViewGroup</code> you'll find all the Items in the group. If you are fine with getting just the Groupname you can proceed with you implementation of course.</p>
<p>I dont really understand why you are using a <code>ContextMenu</code> and what it does (Since you dont posted that code), but if you are interested in how you can display the grouped Items in such a ContextMenu, you can do it like this:</p>
<pre><code><Expander IsExpanded="False" Background="#FFEBEBEB" BorderThickness="0" >
<Expander.ContextMenu>
<ContextMenu ItemsSource="{Binding Items}"/>
</Expander.ContextMenu>
</Expander>
</code></pre>
<p>Since we now know, what we have to deal with (It's still an <code>CollectionViewGroup</code>) we can set the Items of it as ItemsSource of the ContextMenu.</p>
<p>Hope this helps!</p>
|
Sum arrays in php <p>I have the result from database.</p>
<pre><code>Array
(
[0] = stdClass Object
(
[name] = First
[sum] = 3,8,...
)
[1] = stdClass Object
(
[name] = Second
[sum] = -1,0,...
)
[2] = stdClass Object
(
[name] = Third
[sum] = 2,-1...
)
)
</code></pre>
<p>So now I need to sum all in colomn <strong>"sum"</strong>.</p>
<p>I need to get result like</p>
<pre><code>$final = (4, 7,...);
</code></pre>
<p>I have transformed <strong>sum</strong> to array throw <strong>explode()</strong> and then tried with foreach</p>
<p>for example` </p>
<pre><code>foreach ($result as $k=>$subArray) {
$arrayNumbers = explode(",",$subArray->sum);
foreach ($arrayNumbers as $key => $value) {
$sumArray[] = $value];
$stepToSum2[] = array_sum($sumArray);
}
unset($arrayNumb);
}
</code></pre>
<p>Not sure that my example working because I'm already stuck with commented code.</p>
<p>Anyway, I with some manipulations I can get or sum right for the first numbers (5) or the sum of my array (11).</p>
<p>The same result with this</p>
<pre><code>$sum = array_sum(array_map(function($var) {
return $var['sum'];
}, $myResultArray));
</code></pre>
<p>I have searched for the answer but most of the answers only for two arrays, but in same tables, I have more than 5 arrays, so I can't figure out how to implement this.</p>
<p>Thanks.</p>
| <p><a href="http://php.net/manual/en/function.array-reduce.php" rel="nofollow"><code>array_reduce</code></a> is good for reducing an array to a single value as you're doing here. It takes an array and a function that updates a "carry" value for each item in your array.</p>
<pre><code>$result = array_reduce($your_array, function($carry, $item) {
foreach (explode(',', $item->sum) as $key => $value) {
$carry[$key] = $value + (isset($carry[$key]) ? $carry[$key] : 0);
// (OR $carry[$key] = $value + ($carry[$key] ?? 0); in PHP 7)
}
return $carry;
}, []);
</code></pre>
|
HttpWebRequest.GetResponse() times out after some time <p>I have application that sends requests to same REST server constantly and after some time HttpWebRequest.GetResponse() starts timing out i've noticed that whenever i increase System.Net.ServicePointManager.DefaultConnectionLimit it takes it longer to start timing out again, which should mean that those requests are staying active, but as far as i know i'm closing all of them.</p>
<p>Here is method i'm using for my requests.</p>
<p>Current DefaultConnectionLimit is set to 10.</p>
<p>Also there is 1 request that is going on throughout most of applications lifetime.</p>
<p>I'm using .NET Compact framework and REST server is written using WCF (.NET 4.5)</p>
<pre><code>public static string HttpRequest(string request, string method, string contentType, int timeout)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PodesavanjaManager.TrenutnaPodesavanja.PutanjaServisa + "/" + request);
req.Method = method;
req.ContentType = contentType;
req.Timeout = timeout;
req.KeepAlive = false;
if(method == "POST")
req.ContentLength = 0;
using(Stream stream = req.GetResponse().GetResponseStream())
{
using(StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
reader.Close();
}
stream.Close();
stream.Flush();
}
return result;
}
</code></pre>
<p>EDIT new version of method:</p>
<pre><code>public static string HttpRequest(string request, string method, string contentType, int timeout)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PodesavanjaManager.TrenutnaPodesavanja.PutanjaServisa + "/" + request);
req.Method = method;
req.ContentType = contentType;
req.Timeout = timeout;
req.KeepAlive = false;
if(method == "POST")
req.ContentLength = 0;
using (HttpWebResponse resp =(HttpWebResponse) req.GetResponse())
{
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
reader.Close();
}
}
}
GC.Collect();
return result;
}
</code></pre>
| <p>I agree it does <em>behave</em> like the connection is still in use by a resource that has not been closed. The <a href="https://msdn.microsoft.com/en-us/library/system.net.httpwebresponse(v=vs.110).aspx" rel="nofollow">documentation</a> for <code>HttpWebResponse</code> mentions:</p>
<blockquote>
<p>You must call either the Stream.Close or the HttpWebResponse.Close method to close the response and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error.</p>
</blockquote>
<p>I was hoping for a more straightforward description like "you must either close the stream returned by <code>GetResponseStream</code> or call the <code>HttpWebResponse.Close</code> method - but if my interpretation of the documentation is correct, your code is fine.</p>
<p>We use HttpWebRequest in our CE applications as well, and always put the response in a <code>using</code> block as well - you could try this:</p>
<pre><code>using(HttpWebResponse response = (HttpWebResponse)req.GetResponse())
using(Stream stream = response.GetResponseStream())
{
// ...
}
</code></pre>
<p>Also have you checked your code for other <code>HttpWebRequest</code> usages, just to be sure? </p>
|
Can someone show me how to handle java.lang.NullPointerException in my code below <p>I get the exception whenever I run the program without passing in the usDollarAmount or cancel the program... I'm using swing components to accept user input. The program works fine otherwise.</p>
<p>Please show me how to handle this... Thanks</p>
<pre><code>THE Currency CALCULATOR
Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Currency.main(Currency.java:28)
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class Currency{
public static void main(String[] args)
{
// declare and construct variables
double usDollarAmount, poundsAmount,eurosAmount,rublesAmount;
DecimalFormat twoDigits = new DecimalFormat("####.00");
//print prompts and get input
System.out.println("\tTHE Currency CALCULATOR");
//print prompts and get input
usDollarAmount = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter your dollar amount:"));
// calculations
poundsAmount = 0.64 * usDollarAmount;
eurosAmount = 0.91 * usDollarAmount ;
rublesAmount = 61.73 * usDollarAmount ;
// output
JOptionPane.showMessageDialog(null, "YOUR DOLLAR AMOUNT OF " + twoDigits.format(usDollarAmount) + " is equal to " + twoDigits.format(eurosAmount) + " euros" + " ," + twoDigits.format(poundsAmount) + " pounds" + " " + " and " + twoDigits.format(rublesAmount) + " rubles" );
System.exit(0);
}
</code></pre>
<p>}</p>
| <p>First assign the input to a variable and then do a null check. If not null do the parsing</p>
<pre><code>String input = JOptionPane.showInputDialog(null, "Enter your dollar amount:");
if(input != null && !input.trim().isEmpty())
usDollarAmount = Double.parseDouble();
</code></pre>
|
SQL SELECT: concatenated column with line breaks and heading per group <p>I have the following <code>SQL</code> result from a <code>SELECT</code> query:</p>
<pre><code>ID | category| value | desc
1 | A | 10 | text1
2 | A | 11 | text11
3 | B | 20 | text20
4 | B | 21 | text21
5 | C | 30 | text30
</code></pre>
<p>This result is stored in a temporary table named <code>#temptab</code>. This temporary table is then used in another <code>SELECT</code> to build up a new colum via string concatenation (don't ask me about the detailed rationale behind this. This is code I took from a colleague). Via <code>FOR XML PATH()</code> the output of this column is a list of the results and is then used to send mails to customers.</p>
<p>The second <code>SELECT</code> looks as follows:</p>
<pre><code>SELECT t1.column,
t2.column,
(SELECT t.category + ' | ' + t.value + ' | ' + t.desc + CHAR(9) + CHAR(13) + CHAR(10)
FROM #temptab t
WHERE t.ID = ttab.ID
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)') AS colname
FROM table1 t1
...
INNER JOIN #temptab ttab on ttab.ID = someOtherTable.ID
...
</code></pre>
<p>Without wanting to go into too much detail, the column <code>colname</code> becomes populated with several entries (due to multiple matches) and hence, a longer string is stored in this column (<code>CHAR(9) + CHAR(13) + CHAR(10)</code> is essentially a line break). The result/content of <code>colname</code> looks like this (it is used to send mails to customers):</p>
<pre><code>A | 10 | text1
A | 11 | text11
B | 20 | text20
B | 21 | text21
C | 30 | text30
</code></pre>
<p>Now I would like to know, if there is a way to more nicely format this output string. The best case would be to group the same categories together and add a heading and empty line between different categories:</p>
<pre><code>*A*
A | 10 | text1
A | 11 | text11
*B*
B | 20 | text20
B | 21 | text21
*C*
C | 30 | text30
</code></pre>
<p>My question is: How do I have to modify the above query (especially the string-concatenation-part) to achieve above formatting? I was thinking about using a <code>GROUP BY</code> statement, but this obviously does not yield the desired result.</p>
<p>Edit: I use <code>Microsoft SQL Server 2008 R2 (SP2) - 10.50.4270.0 (X64)</code></p>
| <pre><code>Declare @YourTable table (ID int,category varchar(50),value int, [desc] varchar(50))
Insert Into @YourTable values
(1,'A',10,'text1'),
(2,'A',11,'text11'),
(3,'B',20,'text20'),
(4,'B',21,'text21'),
(5,'C',30,'text30')
Declare @String varchar(max) = ''
Select @String = @String + Case when RowNr=1 Then Replicate(char(13)+char(10),2) +'*'+Category+'*' Else '' end
+ char(13)+char(10) + category + ' | ' + cast(value as varchar(25)) + ' | ' + [desc]
From (
Select *
,RowNr=Row_Number() over (Partition By Category Order By Value)
From @YourTable
) A Order By Category, Value
Select Substring(@String,5,Len(@String))
</code></pre>
<p>Returns</p>
<pre><code>*A*
A | 10 | text1
A | 11 | text11
*B*
B | 20 | text20
B | 21 | text21
*C*
C | 30 | text30
</code></pre>
|
CodenameOne Background color <p>I've got a problem setting background color of a TextField:</p>
<pre><code>private TextField mValueField;
public void setFgColor(int color) {
mValueField.getAllStyles().setBgTransparency(0xFF);
if (color == Controller.WHITE_COLOR) {
mValueField.getAllStyles().setBgColor(0xFFFFFF);
} else if (color == Controller.RED_COLOR) {
mValueField.getAllStyles().setBgColor(0xFF0000);
}
}
</code></pre>
<p>The first call sets white color, subsequent calls set white or red color but the TextField's background remains white all the time. If i change the color of the first call to red then the TextField's background color becomes red but also never changes if setting to white later-on.</p>
| <p>After changing the bg color, you should immediately call <code>mValueField.getComponentForm().repaint();</code> or <code>mValueField.getParent().repaint();</code></p>
|
R: read and parse Json <p>If R is not suitable for this job then fair enough but I believe it should be.</p>
<p>I am calling an API, then dumping the results into Postman json reader. Then I get results like:</p>
<pre><code> "results": [
{
"personUuid": "***",
"synopsis": {
"fullName": "***",
"headline": "***",
"location": "***",
"image": "***",
"skills": [
"*",
"*",
"*",
"*.",
"*"
],
"phoneNumbers": [
"***",
"***"
],
"emailAddresses": [
"***"
],
"networks": [
{
"name": "linkedin",
"url": "***",
"type": "canonicalUrl",
"lastAccessed": null
},
{
"name": "***",
"url": "***",
"type": "cvUrl",
"lastAccessed": "*"
},
{
"name": "*",
"url": "***",
"type": "cvUrl",
"lastAccessed": "*"
}
]
}
},
{
</code></pre>
<p>Firstly I'm not sure on how to import this into R as I've mainly dealt with csv's. I've seen other questions where people use Json packages to call the URL directly but that's not going to work with what I'm doing so I'd like to know how to read a csv with json in it. </p>
<p>I used:</p>
<pre><code>x <- fromJSON(file="Z:/json.csv")
</code></pre>
<p>But perhaps theres a better way. Once this is done the json looks more like:</p>
<pre><code>...$results[[9]]$synopsis$emailAddresses
[1] "***" "***"
[3] "***" "***"
$results[[9]]$synopsis$networks...
</code></pre>
<p>Then what I would like for each result is to store the headline and then email address into a data table.</p>
<p>I tried:</p>
<pre><code>str_extract_all(x, 'emailAddresses*$')
</code></pre>
<p>However I figured * would represent everything between emailAddresses and the $ including new lines etc, however this doesn't work. I also find with extract when you do get * to work, it doesnt extract what * represents.</p>
<p>eg:</p>
<pre><code>> y <- 'some text. email "oli@oli.o" other text'
> y
[1] "some text. email \"oli@oli.o\" other text"
> str_extract_all(y, 'email \"*"')
[[1]]
[1] "email \""
</code></pre>
<p>PART 2:</p>
<p>The answers below worked, however if I call the api directly:</p>
<pre><code>body ='{"start": 0,"count": 105,...}'
x <- POST(url="https://live.*.me/api/v3/person", body=body, add_headers(Accept="application/json", 'Content-Type'="application/json", Authorization = "id=*, apiKey=*"))
y <- content(x)
</code></pre>
<p>Then using </p>
<pre><code>fromJSON(y, flatten=TRUE)$results[c("synopsis.headline",
"synopsis.emailAddresses")]
</code></pre>
<p>Does not work. I tried the following:</p>
<pre><code>z <- NULL
zz <- NULL
for(i in 1:y$count){
z=rbind(z,data.table(job = y$results[[i]]$synopsis$headline))
}
for(i in 1:y$count){
zz=rbind(zz,data.table(job = y$results[[i]]$synopsis$emailAddresses))
}
df <- cbind(z,zz)
</code></pre>
<p>However when the JSON list is returned, some people have multiple emails. Thus the method above only records the first email for each person, how would I save the multi emails as a vector (rather than having multiple columns)?</p>
| <p>Additional test data might be helpful.</p>
<p>Consider:</p>
<pre><code>library(jsonlite)
library(dplyr)
json_data = "{\"results\": [\n {\n\"personUuid\": \"***\",\n\"synopsis\": {\n\"fullName\": \"***\",\n\"headline\": \"***\",\n\"location\": \"***\",\n\"image\": \"***\",\n\"skills\": [\n\"*\",\n\"*\",\n\"*\",\n\"*.\",\n\"*\"\n],\n\"phoneNumbers\": [\n\"***\",\n\"***\"\n],\n\"emailAddresses\": [\n\"***\"\n],\n\"networks\": [\n{\n \"name\": \"linkedin\",\n \"url\": \"***\",\n \"type\": \"canonicalUrl\",\n \"lastAccessed\": null\n},\n {\n \"name\": \"***\",\n \"url\": \"***\",\n \"type\": \"cvUrl\",\n \"lastAccessed\": \"*\"\n },\n {\n \"name\": \"*\",\n \"url\": \"***\",\n \"type\": \"cvUrl\",\n \"lastAccessed\": \"*\"\n }\n ]\n}\n}]}"
(df <- jsonlite::fromJSON(json_data, simplifyDataFrame = TRUE, flatten = TRUE))
#> $results
#> personUuid synopsis.fullName synopsis.headline synopsis.location
#> 1 *** *** *** ***
#> synopsis.image synopsis.skills synopsis.phoneNumbers
#> 1 *** *, *, *, *., * ***, ***
#> synopsis.emailAddresses
#> 1 ***
#> synopsis.networks
#> 1 linkedin, ***, *, ***, ***, ***, canonicalUrl, cvUrl, cvUrl, NA, *, *
df$results %>%
select(headline = synopsis.headline, emails = synopsis.emailAddresses)
#> headline emails
#> 1 *** ***
</code></pre>
|
How to create shorthands for CGPoint & CGVector? <p>I'm doing a lot of positioning and animation stuff in literals, and they're taking up a lot of space and becoming unreadable because of the verbosity.</p>
<p><strong>What I'd like to do is turn this</strong></p>
<pre><code> var xy = CGPoint(x: 100, y: 100)
</code></pre>
<p>Into this: </p>
<pre><code> var xy = â¢(100, 100)
</code></pre>
<hr>
<p><strong>Similarly, I'd like to go from:</strong></p>
<pre><code> CGVector(dx: 200, dy: 200)
</code></pre>
<p>to something like this:</p>
<pre><code> `(200, 200)
</code></pre>
<hr>
<p>But I don't know how a macro-like shorthand or something like this would be done, or even if it could be done. Any pointers (puntendered) would be better than where I'm at.</p>
<p>I get that this is probably, for most people, less readable. </p>
<p>Due to the context I always know what these are. I don't need the parameter labels or function name to understand what I'm doing. And this is private animation and motion testing, there's no need for anyone else to ever understand what's going on.</p>
| <pre><code>extension CGPoint {
init(_ x: CGFloat, _ y: CGFloat) {
self.init(x: x, y: y)
}
}
extension CGVector {
init(_ dx: CGFloat, _ dy: CGFloat) {
self.init(dx: dx, dy: dy)
}
}
typealias P = CGPoint
typealias V = CGVector
let p = P(10, 10)
let v = V(10, 10)
</code></pre>
<p>But no idea about the ⢠and ` part - I replaced them with P and V :)</p>
|
TS2307: Cannot find module '~express/lib/express' <p>I'm converting a working JavaScript file to TypeScript.</p>
<p>I use Express in this file, so I've added the following to the top of the file:</p>
<pre><code>///<reference path="./typings/globals/node/index.d.ts" />
import {Request} from "~express/lib/express";
</code></pre>
<p>But the second line produces an error:</p>
<blockquote>
<p>TS2307: Cannot fine module '~express/lib/express'</p>
</blockquote>
<p>I've installed the typings of express, so I actually didn't wrote those two lines by myself, but WebStorm auto generated them by clicking "alt + enter", so I would expect it to work. Unfortunately I get that error.</p>
<p>What am I doing wrong?</p>
| <p>I think you should try this line</p>
<p><code>import * as express from "express";</code> </p>
<p>it was taken from <a href="http://brianflove.com/2016/03/29/typescript-express-node-js/" rel="nofollow">http://brianflove.com/2016/03/29/typescript-express-node-js/</a></p>
<p>hope it helps you.</p>
|
Complex regular expression ... AND OR, negation <p>I would like to search files by their content in Total Commander so I want to create a regex, but I cannot find any manual where it would really be explained. My situation is that I need something like this:</p>
<pre><code>fileContains("<html>") && fileContains("{myVariable1}") && fileNotContains("<script>")
</code></pre>
<p>I can write cca this:</p>
<pre><code>(<html>)+
({myVariable1})+
(<script>){0} ... but this does not work for me
</code></pre>
<p>And I cannot put it all together. Any ideas, please? Or do you have a link to an excellent regex explanation?</p>
| <p>try this <a href="https://regex101.com/r/VWlZ4T/2" rel="nofollow">regex</a>:</p>
<pre><code>(?=.*\{myVariable1\})(?=.*<html>)(?!.*<script>)
</code></pre>
<p>it's just 3 lookaheads in a row. one of those is a negative lookahead. Note the "single line" modifier to enable 'dot matches newline'. </p>
<p>edit (per comment): I guess Total Commander's regex engine does not support lookarounds at all. While you <em>could</em> combine two positive lookaheads into an equivalent 'consuming' pattern with something like this untested regex: <code>(.*(\{myVariable1\}|<html>)){2}</code>, you cannot include the 'negated search' within a single regex unless you have a legitimate regex engine. </p>
<p>You could try <a href="http://totalcmd.net/plugring/PCREsearch.html" rel="nofollow">this Total Commander regex plug-in</a>:</p>
<blockquote>
<p>A RegEx content plug-in with Unicode support - based on Perl
Compatible Regular Expressions (PCRE) library. This plug-in may
replace TC's RegEx engine for file content</p>
</blockquote>
|
How to make shell script to automatically input value <p>I'm trying to copy ssh public key to all hosts on my network with the following little script</p>
<pre><code>#!/bin/bash
for ip in $(nmap -n -sn 192.0.2.0/24 -oG - | awk '/Up$/{print $2}'); do
ssh-copy-id vagrant@$ip
done
</code></pre>
<p>However, it asks for the password for each IP, which count is unknown until execution of the script. How to make this script to automatically enter the password (which in this case is same for all the hosts)?</p>
| <p>Use the <code>sshpass</code>. Note that it is not a good idea to store passwords in the scripts, but it will do the job for the setup:</p>
<pre><code>#!/bin/bash
for ip in $(nmap -n -sn 192.0.2.0/24 -oG - | awk '/Up$/{print $2}'); do
sshpass -p password ssh-copy-id vagrant@$ip
done
</code></pre>
|
Select the register with not null value in a column with GROUP BY <p>I have the next results with the following query:</p>
<p><a href="https://i.stack.imgur.com/AtoC4.png" rel="nofollow"><img src="https://i.stack.imgur.com/AtoC4.png" alt="enter image description here"></a></p>
<pre><code>SELECT `id_booking`, `id_task`, `type`, `date`
FROM (SELECT `id` AS `id_booking`, null AS `id_task`, 1 AS `type`, `date_in` AS `date`
FROM `booking`
WHERE `date_in` <= '2016-10-24'
AND `date_in` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `id` AS `id_booking`, null AS `id_task`, 2 AS `type`, `date_out` AS `date`
FROM `booking`
WHERE `date_out` <= '2016-10-24'
AND `date_out` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `booking_id` AS `id_booking`, `id` AS `id_task`, `id_type` AS `type`, `date` AS `date`
FROM `task`
WHERE `date` <= '2016-10-24'
AND `date` >= '2016-10-14')
AS `tasks`
ORDER BY `date` ASC
</code></pre>
<p>I'm trying to get the register with not null <code>id_task</code> when the <code>id_booking</code> and <code>type</code> are duplicated but if I introduce the clause GROUP BY I just can get the first one register with <code>id_task</code> = NULL.</p>
<p>Is there any possibility to take the register with not null value between multiple registers grouped by GROUP BY?</p>
| <p>A bit more complex ...</p>
<p>but from the result of the select union you should select only the id whit duplicated rows and for this only these with not null type</p>
<pre><code>SELECT `id_booking`, `id_task`, `type`, `date`
FROM (SELECT `id` AS `id_booking`, null AS `id_task`, 1 AS `type`, `date_in` AS `date`
FROM `booking`
WHERE `date_in` <= '2016-10-24'
AND `date_in` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `id` AS `id_booking`, null AS `id_task`, 2 AS `type`, `date_out` AS `date`
FROM `booking`
WHERE `date_out` <= '2016-10-24'
AND `date_out` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `booking_id` AS `id_booking`, `id` AS `id_task`, `id_type` AS `type`, `date` AS `date`
FROM `task`
WHERE `date` <= '2016-10-24'
AND `date` >= '2016-10-14') AS `tasks`
where (`id_booking`, `type`) in ( select `id_booking`, `type` FROM
(SELECT `id` AS `id_booking`, null AS `id_task`, 1 AS `type`, `date_in` AS `date`
FROM `booking`
WHERE `date_in` <= '2016-10-24'
AND `date_in` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `id` AS `id_booking`, null AS `id_task`, 2 AS `type`, `date_out` AS `date`
FROM `booking`
WHERE `date_out` <= '2016-10-24'
AND `date_out` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `booking_id` AS `id_booking`, `id` AS `id_task`, `id_type` AS `type`, `date` AS `date`
FROM `task`
WHERE `date` <= '2016-10-24'
AND `date` >= '2016-10-14') t
group by `id_booking`, `type`
having count(*) > 1
)
and id_task is not null
union
SELECT `id_booking`, `id_task`, `type`, `date`
FROM (SELECT `id` AS `id_booking`, null AS `id_task`, 1 AS `type`, `date_in` AS `date`
FROM `booking`
WHERE `date_in` <= '2016-10-24'
AND `date_in` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `id` AS `id_booking`, null AS `id_task`, 2 AS `type`, `date_out` AS `date`
FROM `booking`
WHERE `date_out` <= '2016-10-24'
AND `date_out` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `booking_id` AS `id_booking`, `id` AS `id_task`, `id_type` AS `type`, `date` AS `date`
FROM `task`
WHERE `date` <= '2016-10-24'
AND `date` >= '2016-10-14') AS `tasks`
where (`id_booking`, `type`) in ( select `id_booking`, `type` FROM
(SELECT `id` AS `id_booking`, null AS `id_task`, 1 AS `type`, `date_in` AS `date`
FROM `booking`
WHERE `date_in` <= '2016-10-24'
AND `date_in` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `id` AS `id_booking`, null AS `id_task`, 2 AS `type`, `date_out` AS `date`
FROM `booking`
WHERE `date_out` <= '2016-10-24'
AND `date_out` >= '2016-10-14'
AND `status` = 'accepted'
UNION ALL
SELECT `booking_id` AS `id_booking`, `id` AS `id_task`, `id_type` AS `type`, `date` AS `date`
FROM `task`
WHERE `date` <= '2016-10-24'
AND `date` >= '2016-10-14') t
group by `id_booking`, `type`
having count(*) = 1
)
and id_task is null
ORDER BY `date` ASC
</code></pre>
|
I am unable to run my program <pre><code>Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=student.mdb;DriverID=22;READONLY=true
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at withoutdsn.Main.main(Main.java:26)
Java Result: 1
</code></pre>
| <p>In order to successfully execute a connection with a database through java,for example if you are using mysql follow the steps below:</p>
<p>Go to mysql website and download the appropriate driver for Java.
Then go to Project -> Properties -> Java Build Path -> Libraries (in Eclipse) and click on "add external Jars".
Add the .jar you downloaded.
Before doing anything else you should be sure to set your connection right.</p>
<p>For example:</p>
<pre><code>//the default port of mysql is 3306
String url = "jdbc:mysql://127.0.0.1:3306/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
System.out.println("Connecting to database..");
try {
cn = DriverManager.getConnection(url, login, passwd);
System.out.println("Database Connected");
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
rs = st.executeQuery(sql);
while (rs.next()){
//do something
}
}catch(Exception e){
System.out.println("Exception");
}finally{
if (cn != null ){
cn.close();
}
}
</code></pre>
|
Mod security Block GET request to URI path <p>I need to block the GET request for a certain URI path.
I'm using anomaly mode, but im using a straight block rule, I cannot get the rule to work properly</p>
<p>example <code>GET /secure/test/bla/bla/</code>
example <code>https://bla.bla.com/secure/test/bla/bla?www.test.com</code></p>
<pre><code>SecRule REQUEST_URI "@streq \/secure\/test\/bla\/bla\?.+" \
"phase:1,id:92,t:none,t:urlDecode,t:lowercase,t:normalizePath,deny,status:403,msg:'403 Access Denied',chain"
SecRule REQUEST_METHOD "@streq post" "t:none,t:lowercase"
</code></pre>
<p>Can I write this with a reg expression like so ?</p>
<pre><code>SecRule REQUEST_URI "!@rx ^(:?\/secure\/test\/bla\/bla\?.+)$" \
"phase:1,id:91,t:none,t:urlDecode,t:lowercase,t:normalizePath,deny,status:403,msg:'403 Access Denied',chain"
SecRule REQUEST_METHOD "@streq post" "t:none,t:lowercase"
</code></pre>
<p>These are not working and I cannot figure out why, do I need to write the regular expression in a different way?</p>
<p>In the secound rule do I need to add <code>"@rx</code>? whats the difference betweeen <code>"!@rx and @rx</code></p>
| <p>So this is a continuation of this question: <a href="http://stackoverflow.com/questions/39980992/modsecurity-create-rule-disable-get-request/39983843">modsecurity create rule disable GET request</a></p>
<blockquote>
<pre><code>example GET /secure/test/bla/bla/ example
https://bla.bla.com/secure/test/bla/bla?www.test.com
</code></pre>
</blockquote>
<p>I have no idea what this means. Can you rewrite it to be more meaningful? Are you saying the URL will contain another domain?</p>
<p>There's several things wrong with the examples you have given. For example this part:</p>
<pre><code>"@streq \/secure\/test\/bla\/bla\?.+"
</code></pre>
<p>The <code>@streq</code> means this is a straight string comparison. So you cannot use <code>?.+</code> parts - which look to be part of regular expressions I guess? If you want a regular expression then that's the default so don't include the <code>@streq</code> bit:</p>
<pre><code>"\/secure\/test\/bla\/bla\?.+"
</code></pre>
<p>I also don't think you need to escape the forward slashes but should do no harm to do that.</p>
<p>Also you have this:</p>
<pre><code>SecRule REQUEST_METHOD "@streq post" "t:none,t:lowercase"
</code></pre>
<p>Why are you checking for <strong>post</strong> when you want to block <strong>get</strong> requests?</p>
<blockquote>
<p>In the secound rule do I need to add "@rx? whats the difference
betweeen "!@rx and @rx</p>
</blockquote>
<p>@rx means what follows is a regular expression. As I say it is the default so doesn't really need to be included as @rx will be assumed unless another @ command is provided.</p>
<p>!@rx means the regular expression should <strong>not</strong> be matched - i.e. apply this rule to any request which does not match this regular expression.</p>
<blockquote>
<p>Can I write this with a reg expression like so ?</p>
<pre><code>SecRule REQUEST_URI "!@rx ^(:?\/secure\/test\/bla\/bla\?.+)$" \
"phase:1,id:91,t:none,t:urlDecode,t:lowercase,t:normalizePath,deny,status:403,msg:'403
</code></pre>
<p>Access Denied',chain"
SecRule REQUEST_METHOD "@streq post" "t:none,t:lowercase"</p>
</blockquote>
<p>No. this says anything which does <strong>not</strong> match the first regular expression and also is a post should be blocked.</p>
<p>So POST request to /anything will be blocked.
And GET request to /anything will not be blocked.
This seems to be the exact opposite of what you want!
Though a POST to /secure/test/bla/bla/ will still be allowed as it will not match the first rule and so be allowed through.</p>
<p>I really think you need to learn the basics of ModSecurity as you are obviously struggling to understand this.</p>
<p>The basic syntax of a ModSecurity rule is:</p>
<pre><code>SecRule \
VARIABLE_TO_CHECK \
VALUE_TO_CHECK_FOR \
ACTION_TO_TAKE_IF_MATCHED \
</code></pre>
<p>With the \ allowing you to separate a rule over several Iines for readability.</p>
<ul>
<li><p>VARIABLE_TO_CHECK can be any of a list of ModSecurity variables
(<a href="https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#Variables" rel="nofollow">https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#Variables</a>)</p></li>
<li><p>VALUE_TO_CHECK_FOR is a regular expression by default. Though can be
changed to be a straight string comparison for example. It will be
compared to the value of the VARIABLE_TO_CHECK and if it matches the
ACTION_TO_TAKE_IF_MATCHED will be run, if it doesn't match then
ModSecurity will stop processing this rule for this request and move
on to the next rule.</p></li>
<li><p>ACTION_TO_TAKE_IF_MATCHED is a list of actions
(<a href="https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#Actions" rel="nofollow">https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#Actions</a>).
Each rule must have an id and then usually either blocks requests
that match above (using <code>deny</code>) or white lists requests (using
<code>allow</code>).</p></li>
</ul>
<p>So for example:</p>
<pre><code>SecRule \
REQUEST_URI \
"^/secure/test/bla/bla/.*" \
"id:1234,deny"
</code></pre>
<p>Will deny any requests to /secure/test/bla/bla/ (GET and POST).</p>
<p>If you want to check two variables then you need to chain two different rules together, and in this case any disruptive actions (e.g. deny) only happens if the full chain matches for all rules - but confusingly the first rule must state the ultimate action to take.</p>
<pre><code>SecRule \
REQUEST_URI \
"^/secure/test/bla/bla/.*" \
"id:1234,deny,chain"
SecRule \
REQUEST_METHOD \
"GET"
</code></pre>
<p>So this rule will deny any requests to any location starting with /secure/test/bla/bla/ which is also a GET request.</p>
<p>When building chained rules it can quickly get confusing so suggest you test each individual rule first to confirm it blocks as appropriate and then chain the, together.</p>
<p>As I advised before, I strongly suggest you buy and read the <a href="https://www.feistyduck.com/books/modsecurity-handbook/" rel="nofollow">ModSecurity handbook</a> to teach you how ModSecurity works.</p>
|
Subtract two ranges and clear the contents from result <p>I'm trying to subtract RangeA - RangeA+offset to get a new range. After this i need to clear all the values within it. My problem is that the variable columnrange is empty and i'm unable to realize what i'm doing wrong.</p>
<pre><code>Dim rng1 As String
Dim rangeA As Range
Dim columnrange As Range
Dim clearrange As Range
rng1 = TextBoxA.Value
If Not IsNull(RangeboxA.Value) Then
On Error Resume Next
Set rangeA = Sheets("Plan1").Range(RangeboxA.Value)
rangeA.Select
Selection.Copy
rangeA.Offset(0, rng1).Select
ActiveSheet.Paste
columnrange = rangeA.Resize(rangeA.Rows.Count, rangeA.Columns.Count + rng1).Value
columnrange.Select
On Error Resume Next
If rangeA Is Nothing Then MsgBox "Verificar informação A"
End If
</code></pre>
| <h2>This code moves a user-defined range by a user-defined amount.</h2>
<pre><code>Sub RemoveRangeOverlap()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Plan1")
Dim rngOffset As Integer
Dim rangeA As Range, rangeB As Range
Dim cellRange() As String
On Error GoTo ErrHandle
rngOffset = CInt(TextBoxA.Value)
If RangeBoxA.Value <> "" Then
Set rangeA = ws.Range(RangeBoxA.Value) 'Set old range
cellRange = Split(CStr(RangeBoxA.Value), ":") 'Set start/ending cells
ReDim Preserve cellRange(LBound(cellRange) To UBound(cellRange))
Set rangeB = ws.Range(ws.Range(cellRange(0)).Offset(0, rngOffset), _
ws.Range(cellRange(1)).Offset(0, rngOffset)) 'set new range
rangeA.Copy rangeB 'copy new range
Application.CutCopyMode = xlCopy 'remove marching ants
If rangeA.Columns.Count <= rngOffset Then 'remove old values
rangeA.Clear
Else: ws.Range(ws.Range(cellRange(0)), _
ws.Range(cellRange(1)).Offset(0, rngOffset - rangeA.Columns.Count)).Clear
End If
Else: MsgBox "Missing target range input.", vbCritical, "Insufficient Data"
End If
ErrHandle:
If Err.Number = 438 Then
MsgBox "Invalid range format in range input box." & vbNewLine & _
"Proper range format example: A1:A1", vbCritical, "Error 438"
ElseIf Err.Number = 13 Then
MsgBox "Only numbers may be input as the range offset amount", _
vbCritical, "Error 13: Type Mis-match"
ElseIf Err.Number = 5 Then Exit Sub
Else: Err.Raise Err.Number
End If
End Sub
</code></pre>
<hr>
<h2>How the code works:</h2>
<p><strong>The first thing we have set up is information control from user-defined values. To accomplish this (which can also be done with <code>If Then</code> statements to prevent the errors from ever occurring in the first place) I've included an error handling line at the end. We know what 3 errors we expect to get depending on what the user provides us with.</strong></p>
<ul>
<li>Error 438 will occur if the user tries to set RangeBoxA's value as a non-range value. </li>
<li>Error 13 will occur if the user tries to input anything that isn't a number as the offset value.</li>
<li>Error 5 will occur because I'm bad at error handling and I'm not sure why it's occuring.. It loops my error statement at the end after whichever error is thrown (being a non-vba error).</li>
</ul>
<p><strong>Next we split up the range supplied by the user into two 'cells'. Using this we can apply some simple math to show where the copy destination will be as well as delete the proper amount of old range values.</strong></p>
<ul>
<li><p>If the number of columns is greater than the user supplied offset, then the new and old ranges will overlap. Some simple math will remove the old cells while preserving the new one's</p></li>
<li><p>If the number of columns is less than the user supplied offset, delete all of the old cells because they won't be overlapping.</p></li>
</ul>
<hr>
<p><em><strong>Let me know if this works for you.</strong></em></p>
|
understanding the minesweeper programming p.roblem <p>I am trying to understand the minesweeper problem: <br>
<strong>Problem statement:</strong><br>
Have you ever played Minesweeper? This cute little game comes with a certain operating system whose name we canât remember. The goal of the game is to ï¬nd where all the mines are located within a M ÃN ï¬eld. The game shows a number in a square which tells you how many mines there are adjacent to that square. Each square has at most eight adjacent squares. The 4Ã4 ï¬eld on the left contains two mines, each represented by a â * â character. If we represent the same ï¬eld by the hint numbers described above, we end up with the ï¬eld on the right: <br>The test case<br>
<a href="https://i.stack.imgur.com/Z7PbG.png" rel="nofollow"><img src="https://i.stack.imgur.com/Z7PbG.png" alt="here is the test case"></a></p>
<p>I am not understanding the problem. just explain me the problem so that I could solve it on my own. PLEASE DO NO EXPLAIN THE SOLUTION.</p>
<p>( I have already seen <a href="http://stackoverflow.com/questions/24598121/minesweeper-stackoverflowerror">this problem</a> and many others like this but they are not talking about the core programming problems , they are game projects. )</p>
| <p>In theory minesweeper can be made as grid of objects. When player use any object then (in classical minesweeper) surrounding objects checks <strong>THEIR surrounding objects</strong> and count how many are marked as mine.</p>
|
Using web.xml to conf programmatically started jetty <p>I created an eclipse maven project and added jetty dependency. Next I made a simple servlet and a class that starts the jetty server. Here is what i got so far:</p>
<pre><code>package com.example.jetty;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class App {
public static void main(String[] args) throws Exception {
Server server = new Server(80);
ServletContextHandler servletContext = new ServletContextHandler(server, "/");
servletContext.addServlet(MyServlet.class, "/");
server.start();
}
}
</code></pre>
<p>My problem is that most tutorials I see have a web.xml to configure servlets and such. I can't find programmatic ways to do the some of these. Can I create a web.xml and still start my jetty programatically and somehow use that web.xml for configuration?</p>
<p>To be more specific i need to write true in web.xml. I did not find any way to do it programatically.</p>
| <p>I'll start with an example that you may interested in. If you want to use <code>web.xml</code> with programmatic way <code>Jetty</code> server, then you can do it following way:</p>
<pre><code>WebAppContext context = new WebAppContext();
context.setContextPath("/myWebApp");
context.setExtractWAR(false);
context.setDescriptor("/path/to/your/wab/app/WEB-INF/web.xml");
context.setResourceBase("/path/to/your/wab/app");
context.setConfigurationDiscovered(false);
HandlerList handlerList=new HandlerList();
handlerList.addHandler(webAppContext);
Server server = new Server(threadPool);
server.setHandler(handlerList);
server.start();
</code></pre>
<p>As regards to programmatically configuration you can try to use <code>Servlet 3.x</code> API, that is supported from <code>Jetty 8.x</code> (current <code>Jetty</code> version <code>9.x</code>) and can be fully configured programmatically.</p>
|
Button not clickable - Disable Click <p><br></p>
<p>I want to make a button in ionic <strong>not clickable</strong>, so how can I do it?</p>
<p>I have buttons inside a header bar and they are scores, so people can't click on them. </p>
| <p>use <code>ng-disable</code></p>
<pre><code><button ng-disable="true"></button>
</code></pre>
|
Can i fork this code from gist and using it for my own projects? <p>Hello I'm new to Github/Gist and I want to use this code, but I need to modify it a little bit. Can i just fork this code and modify it to use it for my own projects? Or do i have to link to the author etc.? Here is the link: <a href="https://gist.github.com/learncodeacademy/777349747d8382bfb722" rel="nofollow">https://gist.github.com/learncodeacademy/777349747d8382bfb722</a></p>
<p>Thank you!</p>
| <p>When you are using a forked repository.It shows up as "forked from xyz". So attribution is automatic. But if you want to, you can always give an extra credit to the author by mentioning it specifically.</p>
|
Error Couldn't find GPIOController <p>Hope to find some guidance on this one soon, I've added reference for Windows IoT UWT in my project but still getting the following error ?</p>
<pre><code>An exception of type 'System.TypeLoadException' occurred in test_led_alljoyn.exe but was not handled in user code
Additional information: Could not find Windows Runtime type 'Windows.Devices.Gpio.GpioController'.
</code></pre>
<p>Has anyone come across this issue while compiling applications for Raspberry Pi on Windows IoT core, on it's own one of my sample push button app works fine. Here's my code</p>
<pre><code> public IAsyncOperation<testlightbulbSwitchResult> SwitchAsync(AllJoynMessageInfo info, bool interfaceMemberOn)
{
return (Task.Run(() =>
{
SwitchLED(interfaceMemberOn);
return testlightbulbSwitchResult.CreateSuccessResult();
}).AsAsyncOperation());
}
private void SwitchLED (bool state)
{
_ledState = state;
if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Devices.Gpio.GpioController"))
{
this.tController = GpioController.GetDefault();
if (this.tController == null)
{
//GpioStatus.Text = "There is no GPIO controller on this device.";
//return;
this.tPin = this.tController.OpenPin(5);
this.tPin.Write(GpioPinValue.High);
this.tPin.SetDriveMode(GpioPinDriveMode.Output);
}
this.tPin.Write(_ledState ? GpioPinValue.Low : GpioPinValue.High);
}
}
</code></pre>
| <p>Solved. I had to set build platform target compile with .net native tool chain.</p>
|
Locking a fragment after switching <p>I have a query about locking of fragments.Actually I have three fragments in bottom tab navigation.
All of the three fragments are basically entry forms in which I am picking the values from edittexts.However I want a feature to be added in the app such that when I submit one form i.e. when one fragment submits the data, then that fragment should be locked from user switching and user cant go back to that old fragment and an alert message should be displayed, displaying the message that you have already submitted this section,now you cant go back.Can anyone suggest how to make it possible.</p>
<p>e.g. I have three fragments frg1,frg2,frg3 and each of them contains a form to get data.Each of them has a submit button located in the below after the form.Once you submit you goto next fragment automatically(this is already done) but you need to take care that you can not go back to the old fragment again.Till now I have coded the part where you can switch to another fragment after submission but I am still able to go back.So basically i need that feature to stop going back to the old fragment.Please help me solve this.</p>
| <p>if you are using a viewpager the only solution is create a Custom ViewPager like this:</p>
<pre><code>public class NoScrollViewPager extends ViewPager {
private boolean isPagingEnabled = false;
public NoScrollViewPager(Context context) {
super(context);
}
public NoScrollViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onInterceptTouchEvent(event);
}
public void setPagingEnabled(boolean b) {
this.isPagingEnabled = b;
}
</code></pre>
<p>With setPagingEnabled() you will be able to lock and unlock the viewPager</p>
<p>Otherwise if you are inflating fragment use replace() instead add().</p>
<p>Cheers.</p>
|
Python Regex: Using a lookahead <p>I'm trying to detect text of the following type, in order to remove it from the text:</p>
<pre><code>BOLD:Parshat NoachBOLD:
BOLD:Parshat Lech LechaBOLD:
BOLD:Parshat VayeraBOLD
BOLD:Parshat ShâminiBOLD:
</code></pre>
<p>But only to capture this part:</p>
<pre><code>BOLD:Parshat Noach
BOLD:Parshat Lech Lecha
BOLD:Parshat Vayera
BOLD:Parshat Shâmini
</code></pre>
<p>I thought to use this regex using lookahead:</p>
<pre><code>re.sub(r"BOLD:Parshat .*?(?=(:BOLD))","",comment) #tried lookahead with and without parens
</code></pre>
<p>But it doesn't seem to be detecting them. What might be the problem? The text is followed by a snippet in Hebrew, not sure if that is what is causing the problem.</p>
<p>Please note that these segments are embedded in the middle of different lines, as mentioned followed by a Hebrew snippet.</p>
| <p>In python you can just do:</p>
<pre><code>str = re.sub(r'BOLD:?$', '', str, 0, re.MULTILINE)
</code></pre>
<p><a href="https://regex101.com/r/qiNd4L/3" rel="nofollow">RegEx Demo</a></p>
<p>That will remove <code>BOLD</code> followed by optional <code>:</code> from the end of each line.</p>
<hr>
<p><strong>EDIT:</strong> If this <code>BOLD:</code> term is not always at end of line, one can use:</p>
<pre><code>>>> print re.sub(r'\b(BOLD:.*)BOLD:?', r'\1', str)
BOLD:Parshat Noach
BOLD:Parshat Lech Lecha
BOLD:Parshat Vayera
BOLD:Parshat Shâmini
</code></pre>
|
Is it possible to give a url like this in laravel http://sitename/store/us/walmart.com <p>Is it possible to give a route in <em>laravel 5.3</em> similar to </p>
<p>Please give me an answer before down voting the question</p>
<p><a href="https://i.stack.imgur.com/oCJN4.png" rel="nofollow">Image of not found page </a></p>
<blockquote>
<p>**http://**sitename/store/us/walmart.com or amazon.com etc</p>
</blockquote>
<p>After putting .com after the store name then i am getting a not found error page which is not of laravel , its of <strong>apache not found page</strong> </p>
<p><a href="http://182.72.164.230:8000/store/beststores.com" rel="nofollow">Reference Site</a></p>
| <p>Try Laravel Annotations and annotate the function to handle the request with the desired url. check out <a href="http://dunebook.com/docblock-annotations-in-laravel-5-1/3/" rel="nofollow">http://dunebook.com/docblock-annotations-in-laravel-5-1/3/</a>
for how to use Laravel Annotations if you don't know how to already.</p>
|
Verify Records Before Updating in Stored Procedure <p>Let's say I have 2 counties:</p>
<ul>
<li>A</li>
<li>B</li>
</ul>
<p>Each has it's own URL:</p>
<ul>
<li>www.A.com</li>
<li>www.B.com</li>
</ul>
<p>I have a stored procedure that accepts 3 variables to enable or disable the service to the URL. The <code>@Enable</code> variable is required but the user can enter the <code>@County_Code</code> or <code>@WebserviceURL</code> variables - or both. But if they enter both, I want to verify that the record exits in the database.</p>
<p>For example,</p>
<p><code>EXEC [dbo].usp_webservice_change_status
@enable = 1,
@county_code = 'A',
@webserviceURL = 'www.A.com';</code></p>
<p>should execute and update the Enable flag.</p>
<p>But if I execute with the following values, I would like to have an error returned stating something to the effect that County A does not have a corresponding value of www.B.com.</p>
<p><code>EXEC [dbo].usp_webservice_change_status
@enable = 1,
@county_code = 'A',
@webserviceURL = 'www.B.com';</code></p>
<p>Here is the complete stored procedure:</p>
<pre><code>ALTER PROCEDURE [dbo].[usp_webservice_change_status]
@enable AS BIT,
@county_code AS CHAR(2) = NULL,
@webserviceURL AS VARCHAR(4000) = NULL
AS
BEGIN
SET NOCOUNT ON;
IF @enable IS NULL
RAISERROR ('The value for @enable should not be null', 15, 1);
IF ( @county_code IS NULL AND @webserviceURL IS NULL )
RAISERROR ('The value for @county_code and @webserviceURL cannot both be null', 15, 1);
IF ( @county_code IS NOT NULL AND @webserviceURL IS NULL )
UPDATE dbo.webservice_config
SET [enable] = @enable,
comments = CASE
WHEN @enable = 1 THEN 'Enabled by ' + SUSER_SNAME()
ELSE 'Disabled by ' + SUSER_SNAME()
END
WHERE county_code = @county_code
ELSE IF (@county_code IS NULL AND @webserviceURL IS NOT NULL )
UPDATE dbo.webservice_config
SET [enable] = @enable,
comments = CASE
WHEN @enable = 1 THEN 'Enabled by ' + SUSER_SNAME()
ELSE 'Disabled by ' + SUSER_SNAME()
END
WHERE webservice_URL = @webserviceURL
ELSE IF ( @county_code IS NOT NULL AND @webserviceURL IS NOT NULL )
UPDATE dbo.webservice_config
SET [enable] = @enable,
comments = CASE
WHEN @enable = 1 THEN 'Enabled by ' + SUSER_SNAME()
ELSE 'Disabled by ' + SUSER_SNAME()
END
WHERE ( county_code = @county_code AND webservice_URL = @webserviceURL )
END;
</code></pre>
| <p>You could do this with another IF statement if I understand what you want correctly... just add these two lines at the bottom of your <code>PROCEDURE</code> just before your <code>END;</code></p>
<pre><code>IF(@@ROWCOUNT) < 1
RAISERROR('Nothing Updated Due to Non Matching Records',15,1)
</code></pre>
<p>So it will look like this</p>
<pre><code>--all your other code
WHERE ( county_code = @county_code AND webservice_URL = @webserviceURL )
IF(@@ROWCOUNT) < 1
RAISERROR('Nothing Updated Due to Non Matching Records',15,1)
END;
</code></pre>
<p>You could also wrap the entire thing in another <code>IF</code> if you want</p>
<pre><code>ELSE IF ( @county_code IS NOT NULL AND @webserviceURL IS NOT NULL )
IF(SELECT 1 FROM dbo.webservice_config WHERE county_code = @county_code AND webservice_URL = @webserviceURL) < 1
RAISERROR('Nothing Updated Due to Non Matching Records',15,1)
ELSE
UPDATE dbo.webservice_config
SET [enable] = @enable,
comments = CASE
WHEN @enable = 1 THEN 'Enabled by ' + SUSER_SNAME()
ELSE 'Disabled by ' + SUSER_SNAME()
END
WHERE ( county_code = @county_code AND webservice_URL = @webserviceURL )
END;
</code></pre>
<p>You could also use <code>EXISTS</code> and other syntax instead of what I used... just some examples.</p>
|
Counting words from a text-file in Java <p>I'm writing a program that'll scan a text file in, and count the number of words in it. The definition for a word for the assignment is: 'A word is a non-empty string consisting of only of letters (a,. . . ,z,A,. . . ,Z), surrounded
by blanks, punctuation, hyphenation, line start, or line end.
'.</p>
<p>I'm very novice at java programming, and so far i've managed to write this instancemethod, which presumably should work. But it doesn't. </p>
<pre><code>public int wordCount() {
int countWord = 0;
String line = "";
try {
File file = new File("testtext01.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
line = line + input.next()+" ";
input.next();
}
input.close();
String[] tokens = line.split("[^a-zA-Z]+");
for (int i=0; i<tokens.length; i++){
countWord++;
}
return countWord;
} catch (Exception ex) {
ex.printStackTrace();
}
return -1;
}
</code></pre>
| <p>Quoting from <a href="http://stackoverflow.com/questions/28462719/counting-words-in-text-file">Counting words in text file?</a> </p>
<pre><code> int wordCount = 0;
while (input.hasNextLine()){
String nextLine = input.nextLine();
Scanner word = new Scanner(nextline);
while(word.hasNext()){
wordCount++;
word.next();
}
word.close();
}
input.close();
</code></pre>
|
How to run multiple background thread tasks one at a time? (Swift 3) <p>First of all, I'm a beginner and I'm about to make a few assumptions of what's causing my problem down here, which may sound really stupid, so please bare with me.</p>
<p>I'm trying to loop through an array of String objects containing dates of the month October 2016, which means 31 String objects: 1 October 2016...31 October 2016. For each object I want to retrieve some data from the database and append the returned value (also a String object) to a new array. The tricky part, though, is that the new array of String objects should be in the exact same order as the dates array. So for example, the 5th object in the new array should be the returned value of the 5th object in my dates array (5 October 2016) and 14th object in the new array should be the returned value of the 14th object in my dates array (14 October 2016) and so on and so forth. Now obviously, the database retrieval process happens in a background thread, and assuming the system wants the entire process to be done as quickly as possible, it fires off multiple retrieval tasks simultaneously (all in their own thread). The problem with this is that it really messes up the order in which the new array is constructed. To be honest, it looks really confusing and the weird part is the order of the array isn't random (which would've probably confirmed my assumption): the order of the new array is basically the first 8 return values in the correct order and then from the 9th value the first 8 values get repeated, so kinda like this:</p>
<pre><code>1 October -> 5
2 October -> 8
3 October -> 4
4 October -> 11
5 October -> 9
6 October -> 7
7 October -> 6
8 October -> 14
9 October -> 5
10 October -> 8
11 October -> 4
12 October -> 11
13 October -> 9
14 October -> 7
15 October -> 6
16 October -> 14
17 October -> 5
18 October -> 8
19 October -> 4
20 October -> 11
21 October -> 9
22 October -> 7
23 October -> 6
24 October -> 14
25 October -> 5
26 October -> 8
27 October -> 4
28 October -> 11
29 October -> 9
30 October -> 7
31 October -> 6
</code></pre>
<p>So as you can notice in this pattern, it just fetches 8 different values and then repeats all over again until the array is full. If I run the entire looping process twice in a really short time, the order is usually still the same, except the first value in the array isn't the same anymore (so basically every value moves 1 date up). Anyway, to cut to the chase: I assume running each retrieval task one by one would fix my problem. This is the loop I'm currently running:</p>
<pre><code>// Loop through each date
for date in self.datesToDisplay {
// Fire off retrieval method with date object as its only parameter
self.getMessagesForDate(date)
}
</code></pre>
<p>My model will append the returned values to a new array and pass the newly created array back to the caller, like this:</p>
<pre><code>// Delegate method which gets called whenever retrieval is finished
func messagesRetrieved() {
// Pass newly created array back to caller
self.messagesForDatesToDisplay = self.retrieveModel.messages
}
</code></pre>
<p>The above code is a little simplified version of the actual code that I'm running in my project, but you get the idea. First question is: am I anywhere near the right direction with my assumption of what could be causing this issue? Second follow-up question is: If I am correct, how can I be sure that the second retrieval process doesn't start until the first one is FULLY COMPLETED (so after the delegate method to return the value has been called and run)?</p>
| <p>One approach is to retrieve the results into a structure that is not dependent upon the order that the results come in i.e. a dictionary.</p>
<p>So, you could do something like:</p>
<pre><code>let syncQueue = DispatchQueue(label: "...") // use dispatch_queue_create() in Swift 2
let group = DispatchGroup() // use dispatch_group_create() in Swift 2
var results = [String: [Message]]()
for date in datesToDisplay {
group.enter() // use dispatch_group_enter in Swift 2
getMessages(for: date) { messages in
syncQueue.async { // use dispatch_async in Swift 2
results[date] = messages
group.leave() // use dispatch_group_leave in Swift 2
}
}
}
group.notify(queue: .main) { // use dispatch_group_notify in Swift 2
syncQueue.sync { // use dispatch_sync in Swift 2
// update your model with `results` here
}
// trigger UI update here
}
</code></pre>
<p>Personally, I'd just stick with the dictionary structure for the results.</p>
<p>For example, if I wanted to get the third entry ("3 October"), it would be</p>
<pre><code>let oct3Messages = modelDictionary[datesToDisplay[2]]
</code></pre>
<p>But if you really feel compelled to convert it back to an array of the original order, you can do that:</p>
<pre><code>group.notify(queue: .main) {
syncQueue.sync {
self.retrieveModel = self.datesToDisplay.map { results[$0]! }
}
// trigger UI update here
}
</code></pre>
<p>Now, I made a few subtle changes here. For example, I added a completion handler to <code>getMessagesForDate</code>, so I'd know when the request was done, and I pass the results back in that closure. You want to avoid updating model objects asynchronously and you want to know when everything is done, and I use a dispatch group to coordinate that. I also am using a synchronization queue to coordinate the updates to the results to ensure thread-safety.</p>
<p>But I don't want you to get lost in those details. The key point is that you should simply want to use a structure that is not dependent upon the order that objects are retrieved. Then, either retrieve directly from that unordered dictionary (using your ordered <code>datesToDisplay</code> as the key), or convert it to an ordered array.</p>
<hr>
<p>In the interest of full disclosure, we should say that it may be more complicated than I suggest here. For example, if your asynchronous <code>getMessagesForDate</code> is just using a global queue, you might want to do something to constrain how many of these run concurrently. </p>
<p>And you might also want to benchmark this against performing these requests sequentially, because while the database may run on a background thread, it might not be able to run multiple requests concurrent with respect to each other (often, the database will synchronize its queries), so you might be going through more work than necessary.</p>
|
Switch contents of footer based on page <p>Switch contents of footer</p>
<p>Is it possible to switch the contents of the footer based on the page number?</p>
<p>On the first page, I would like to show a text based footer, and on the last page I would like to show a logo.</p>
<p>I've tried adding:</p>
<pre><code>=IIf(Globals!PageNumber<>1,logo1,logo2)
</code></pre>
<p>In the Report Data section within the Images folder, the logos are embedded as logo1 and logo2.</p>
<p>Image Properties > General > Use this image, in the (fx) button, but once I have compiled the project, i am unable to upload the rdl file to Dynamics.</p>
<p>Also, as soon as I add the above script to the image, the image becomes a broken image in the design view, and as soon as I replace the above script with the original script which was simply</p>
<p><code>logo1</code></p>
<p>everything is back to normal again, the image can be see in the designer, and the file can be uploaded into dynamics.</p>
<p>If this is possible, would appreciate some help.</p>
| <p>You need to surround the image names with quotes, as mentioned in the comments. Additionally, the image will appear broken in the designer. If you preview or upload to CRM, the image will show correctly.</p>
<p>Double-check that both images are embedded in the report:</p>
<p><a href="https://i.stack.imgur.com/w7dX1.png" rel="nofollow"><img src="https://i.stack.imgur.com/w7dX1.png" alt="Embedded images"></a></p>
<p>Ensure that the image source is set to Embedded:</p>
<p><a href="https://i.stack.imgur.com/UHkFA.png" rel="nofollow"><img src="https://i.stack.imgur.com/UHkFA.png" alt="Select the image source: Embedded"></a></p>
<p>Ensure that the image names are surrounded by quotes:</p>
<p><a href="https://i.stack.imgur.com/AJEc4.png" rel="nofollow"><img src="https://i.stack.imgur.com/AJEc4.png" alt="Image name surrounded by quotes"></a></p>
<p>After this, the report can either be previewed or uploaded to CRM. The image on the first page will be different from the image on the remaining pages, as expected.</p>
|
Unresolved reference: flask_sqlalchemy <p>I have installed flask_sqlalchemy using pip. </p>
<p>I try to import it using the following line:</p>
<pre><code>from flask_sqlalchemy import SQLAlchemy
</code></pre>
<p>But PyCharm does not recognize flask_sqlalchemy and when I run the code I get "NameError: name 'SQLalchemy' is not defined.</p>
<p>Any insight would be appreciated.</p>
| <p>Your error is <code>"NameError: name 'SQLalchemy' is not defined.</code> but what you've done in your file is <code>from flask_sqlalchemy import SQLAlchemy</code></p>
<p>The difference is that you forgot to cap the A:</p>
<pre><code>SQLAlchemy
SQLalchemy
</code></pre>
<p>Fix that in your file and the error should resolve.</p>
|
Laravel 5.3 - htmlspecialchars() expects parameter 1 to be string <p>I am new to laravel and I am enjoying it. While working on a social media project I got this error: <code>htmlspecialchars() expects parameter 1 to be string, object given (View: C:\wamp64\www\histoirevraie\resources\views\user\profile.blade.php)</code></p>
<p>I have checked some questions on this site but I have not found a question that solves my problem.</p>
<p>this is what my <code>profile.blade.php</code> is made of:</p>
<pre><code><ul class="profile-rows">
<li>
<span class="the-label">Last visit: </span>
<span class="the-value mark green">{{ \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $user->lastVisit)->diffForHumans(\Carbon\Carbon::now())}}</span>
</li>
<li>
<span class="the-label">Member since: </span>
<span class="the-value mark light-gray">{{ $user->created_at->format('F Y') }}</span>
</li>
<li>
<span class="the-label">Profile views: </span>
<span class="the-value mark light-gray">5146</span>
</li>
<li>
<span class="the-label">Living In: </span>
<span class="the-value">{{ $user->town }}</span>
</li>
<li>
<span class="the-label">Website: </span>
<span class="the-value"><a href="{{ url($user->website) }}">{{ $user->website }}</a></span>
</li>
</ul>
</code></pre>
<p>All the information about the user are given by a controller:</p>
<pre><code>public function index($username){
$user = User::where('username', $username)->first();
return view('user.profile', compact('user'));
}
</code></pre>
<p>Kindly help me solve this problem!</p>
| <p>I think your <code>$user->website</code> is empty/blank.</p>
<p>If you look at the <a href="https://github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/helpers.php#L808-L810" rel="nofollow"><code>url()</code> helper method</a>, Laravel will return an <em>instance</em> of <code>UrlGenerator</code> if <code>$path</code> is null.</p>
<p>So in your case if <code>$user->website</code> is empty, you'd get <code>UrlGenerator</code> back and thus your error about <code>htmlspecialchars</code> getting an object.</p>
<p>One simple solution would be to wrap your html chunk with a check:</p>
<pre><code>@if($user->website)
<li>
...
</li>
@endif
</code></pre>
|
Unable to parse bash output using regex and collect a part of it <p>I am trying to parse out the recent load, from the output of this command - </p>
<pre><code>[sandeepan@ip-10-169-92-150 ~]$ w
14:22:21 up 17 days, 51 min, 2 users, load average: 0.00, 0.01, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
sandeepa pts/0 115.112.95.170 06:38 43:57 0.51s 0.51s -bash
sandeepa pts/1 115.112.95.170 13:17 4.00s 0.03s 0.00s w
</code></pre>
<p>The first one after the load average: -</p>
<pre><code> |
\|/
load average: 0.00, 0.01, 0.05
</code></pre>
<p>I was using this, which worked - </p>
<pre><code>w | awk '{print $10}' | tr -d ,
</code></pre>
<p>However, I realised that the value I am looking for may not always be the 10th variable. Hence I am trying to use regex here, but unfortunately, not able to use it with any of the few bash commands/utilities I know. </p>
<p>I have this regular expression, with which I am able to match the desired value -</p>
<pre><code>/.*load average:\s([0-9]+\.[0-9]+),.*/m
</code></pre>
<p>I tried looking at the sed manual, looking at some other questions like <a href="http://stackoverflow.com/questions/22078519/using-sed-to-remove-unwanted-characters-from-output">Using sed to remove unwanted characters from output</a>, but could not understand much to make mine working.</p>
| <p>When you know what text comes before and after, it is best to use a look-behind that does this: checks the text in a given place, no matter what is the rest of the line.</p>
<p>Given your sample file, I stored it in a file and did this:</p>
<pre><code>$ grep -Po '(?<=load average: )[^,]*' file
0.00
</code></pre>
<p>This is saying: hey, get all the text after <code>load average:</code> and until a comma is found.</p>
<p>So if you have a file like this:</p>
<pre><code>$ cat file
14:22:21 up 17 days, 51 min, 2 users, load average: 0.00, 0.01, 0.05
hello how are you, load average: 1.23, 0.01, 0.05
</code></pre>
<p>It will return as follows:</p>
<pre><code>$ grep -Po '(?<=load average: )[^,]*' file
0.00
1.23
</code></pre>
<hr>
<p>Note by the way that <code>man w</code> can give you good hints on how to get this info with some options, as well as <code>man top</code>.</p>
|
Sitecore Ucommerce - How to access RavenDB Studio <p>I need to access the data in RavenDB shipped with Ucommerce in Sitecore application. The Ucommerce doc page says you can do it. </p>
<p><a href="http://docs.ucommerce.net/ucommerce/v7.1/manage-ucommerce/access-ravendb-studio.html" rel="nofollow">http://docs.ucommerce.net/ucommerce/v7.1/manage-ucommerce/access-ravendb-studio.html</a></p>
<p>I set the binding for the port 1337</p>
<p>I tried <a href="http://mysite:1337" rel="nofollow">http://mysite:1337</a> and <a href="http://mysite:1337/databases" rel="nofollow">http://mysite:1337/databases</a></p>
<p>I set NETWORK SERVICES as Administrator and recycled the AppPool</p>
<p>But it does not seem to work.
I cannot figure out what exactly should I do for it.
Can anyone help me?</p>
| <p>Did you perform all the steps outlined in article?</p>
<p>If you did there are a few extra things you can check:</p>
<ul>
<li>Make sure the app pool runs with an identity which is in the admin group.</li>
<li>After you change the configuration, make sure you recycle the app pool to force it to pick up the new configuration</li>
</ul>
<p>Hope this helps.</p>
|
How to prompt the user with message when combo box item is changed <p>I am new to C#, I am trying to prompt the user with a message once the <code>combobox</code> item is changed, but the below code doesn't work even though the <code>combobox</code> item is changed.</p>
<pre><code> namespace NormingPointTagProgrammer
{
public partial class normingPointTagProgrammer : Form
{
public normingPointTagProgrammer()
{
InitializeComponent();
// User Message to start the tag programming
MessageBox.Show("To Read the data programmed in a Tag, Click on READ Button\n" +
"To Write data into the tag, \n" +
"Please select the Data Format, under DATA TO PROGRAMMER frame.");
}
private void dataFormatComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// When the user has decided to program the tag. Check the Data format selected by the user, and ask the user to
// enter required fields based on the format selected.
if (datFormatcomboBox.Text == "RSO")
{
MessageBox.Show("Within DATA TO PROGRAMMER frame, under RSO DATA from DataBase Enter the following fields: \n" +
"Region (1-254),\n" +
"Segment (1-255),\n" +
"Offset (0 to 6553.5) and \n" +
"select Type dropdown Field, Under");
}
else if (datFormatcomboBox.Text == "INDEX")
{
MessageBox.Show("Within DATA TO PROGRAMMER frame, under INDEX DATA from DataBase Enter the following fields: \n" +
"Region (255) and \n" +
"Index (1-65535) ");
}
else if (string.IsNullOrWhiteSpace(datFormatcomboBox.Text))
{
MessageBox.Show("Please select the Data Format, under DATA TO PROGRAMMER frame.");
}
else
{
MessageBox.Show("Required fields not entered by the user.\n" +
"Please enter the data to be programmed based on the Data Format selected");
}
}
}
}
</code></pre>
| <p>Verify that your event is being subscribed to, a shorthand would be using the below for example,</p>
<pre><code>ComboBoxChanged += dataFormatComboBox_SelectedIndexChanged();
</code></pre>
<p>Or,</p>
<pre><code>ComboBoxChanged += new EventHandler(dataFormatComboBox_SelectedIndexChanged);
// This will be called whenever the ComboBox changes:
private void dataFormatComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//Your datFormatcomboBox.Text logic here.
}
</code></pre>
<p>Essentially, whatever is passed to ComboBoxChanged, use <code>e</code> to obtain the input of ComboBox text.</p>
<p>More information here: <a href="https://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx</a></p>
<p>Hope that helps!</p>
|
Error with springboard class XCUITesting <p>I have found a link (<a href="http://stackoverflow.com/questions/33107731/is-there-a-way-to-reset-the-app-between-tests-in-swift-xctest-ui-in-xcode-7">Is there a way to reset the app between tests in Swift XCTest UI in Xcode 7?</a>) what was referring to creating a springboard class in order to delete the app after each test for xcode ui testing....</p>
<p>I have created the bridging header with both the XCUIApplication and XCUIElement documents. However I am getting a "Argument passed to call that takes no arguments, could someone explain why I am getting this and how to resolve? </p>
<pre><code>class Springboard {
static let springboard = XCUIApplication(
privateWithPath: nil, bundleID: "uk.co.vouchercodes.VoucherCodes"
)
/**
Terminate and delete the app via springboard
*/
class func deleteMyApp() {
XCUIApplication().terminate()
// Resolve the query for the springboard rather than launching it
springboard.resolve()
// Force delete the app from the springboard
let icon = springboard.icons["MyAppName"]
if icon.exists {
let iconFrame = icon.frame
let springboardFrame = springboard.frame
icon.pressForDuration(1.3)
// Tap the little "X" button at approximately where it is.
// The X is not exposed directly
springboard.coordinateWithNormalizedOffset(
CGVectorMake((iconFrame.minX + 3) / springboardFrame.maxX,
(iconFrame.minY + 3) / springboardFrame.maxY)
).tap()
springboard.alerts.buttons["Delete"].tap()
}
}
}
</code></pre>
| <p>One way you can avoid the error is by declaring the method you are trying to access in Objective-C header. Create a bridge header file from Objective-C to Swift and then use the method.</p>
<p>In your particular case what you can do is create a Objective-C header file: CustomXCUIApplication.h with contents:</p>
<pre><code>#import <XCTest/XCUIApplication.h>
@interface CustomApplication : XCUIApplication
- (id)initPrivateWithPath:(id)arg1 bundleID:(id)arg2;
- (id)init;
@end
</code></pre>
<p>Create Objective-C source file: CustomXCUIApplication.m with contents:</p>
<pre><code>#import <Foundation/Foundation.h>
#import "CustomXCUIApplication.h"
@implementation CustomApplication : XCUIApplication
@end
</code></pre>
<p>Now create a Brdige Header file BridgeUITesting.h with contents:</p>
<pre><code>#import "CustomXCUIApplication.h"
</code></pre>
<p>As a last step Specify the path and name of Bridging Header file in your targets Build Settings -> Swift Compiler - General -> Objective-C Bridging Header</p>
<p>In your code use </p>
<pre><code>CustomApplication(privateWithPath: nil, bundleID: "uk.co.vouchercodes.VoucherCodes")
</code></pre>
|
How do I write a doctest in python 3.5 for a function using random to replace characters in a string? <pre><code>def intoxication(text):
"""This function causes each character to have a 1/5 chance of being replaced by a random letter from the string of letters
INSERT DOCTEST HERE
"""
import random
string_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
text = "".join(i if random.randint(0,4) else random.choice(string_letters) for i in text)
return text
</code></pre>
| <p>You need to mock the random functions to give something that is predetermined.</p>
<pre><code>def intoxication(text):
"""This function causes each character to have a 1/5 chance of being replaced by a random letter from the string of letters
If there is 0% chance of a random character chosen, result will be the same as input
>>> import random
>>> myrand = lambda x, y: 1
>>> mychoice = lambda x: "T"
>>> random.randint = myrand
>>> random.choice = mychoice
>>> intoxication("Hello World")
'Hello World'
If there is 100% chance of a random character chosen, result will be the same as 'TTTTTTTTTTT'
>>> import random
>>> myrand = lambda x, y: 0
>>> mychoice = lambda x: "T"
>>> random.randint = myrand
>>> random.choice = mychoice
>>> intoxication("Hello World")
'TTTTTTTTTTT'
If every second character is replaced
>>> import random
>>> thisone = 0
>>> def myrand(x, y): global thisone; thisone+=1; return thisone % 2
>>> mychoice = lambda x: "T"
>>> random.randint = myrand
>>> random.choice = mychoice
>>> intoxication("Hello World")
'HTlToTWTrTd'
If every third character is replaced
>>> import random
>>> thisone = 0
>>> def myrand(x, y): global thisone; thisone+=1; return thisone % 3
>>> mychoice = lambda x: "T"
>>> random.randint = myrand
>>> random.choice = mychoice
>>> intoxication("Hello World")
'HeTloTWoTld'
"""
import random
string_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
text = "".join(i if random.randint(0,4) else random.choice(string_letters) for i in text)
return text
if __name__ == "__main__":
import doctest
doctest.testmod()
</code></pre>
|
How can I only create a file without opening it <p>I've been trying to create a file without using system commands. This code I wrote has multiple problems, If i create fptr in the start and check it for NULLity then the double free or corruption occurs, otherwise this way it gives memory dump. Even through previous method I wasnt closing file more than once but I think there's something very simple hiding between the lines I cant see. </p>
<pre><code>int main()
{
char* filename;
char x;
cout << "enter filename.**: ";
cin >> filename;
struct stat buffer;
if (! stat (filename, &buffer))
{
cout << ("It exists\n");
}
else
{
FILE* fptr;
fptr = fopen (filename,"w");;
fclose (fptr);
}
}
</code></pre>
<p>Really Appreciate your help! :)</p>
| <p>You can use <a href="http://man7.org/linux/man-pages/man2/mknod.2.html" rel="nofollow"><code>mknod()</code></a> on some systems (such as Linux; note this is not portable to all operating systems).</p>
<pre><code>if (mknod(filename, S_IFREG|0666, 0) != 0) {
throw std::system_error(errno, std::system_category());
}
</code></pre>
<p>In portable code you will have to open a file in order to create it.</p>
|
What is the difference between these two codes it seems like they are exactly same but The second one causes a segmentation fault? <p>I am trying to make different 1d arrays from 1d array each of which separated with space .I am using this in a project which is causing a serious problem to my code if i use the second one . Even debugging didn't help me.
This generally aims at converting a statement with spaces into a different strings. The first code does the job for me but the second one is identical but causing segmentation fault .</p>
<p>For Example "This is C program" is input
The Output should be
"This" -must be in a[0],
"is" -must be in a[1],
"C" -must be in a[2],
"program" -must be in a[3].</p>
<p>Here is the first one</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
void gets(char *);
main()
{
char str[100];
char **a;
int i=0,j=0,k=0,count=0,n;
printf("Enter a String : ");
gets(str);
while(str[k])
if(str[k++]==32)
count++;
count=count+1;
printf("%d\n",count);
a=calloc(count,sizeof(char *));
n=count;
for(i=0;i<count;i++)
{
k=0;
a[i]=calloc(1,20);
while((str[j]!=32)&&(str[j]!=0))
{
a[i][k]=str[j];
j++;
k++;
}
j++;
}
for(j=0;j<n;j++)
printf("%s\n",a[j]);
}
</code></pre>
<p>Here is the second one </p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
void gets(char *);
main()
{
char str[100];
char **a;
int i=0,j=0,k=0,count=0,n;
printf("Enter a String : ");
gets(str);
while(str[k])
if(str[k++]==32)
count++;
count=count+1;
printf("%d\n",count);
a=calloc(count,sizeof(char *));
n=count;
for(i=0;i<count;i++)
a[i]=calloc(1,20);
while(count)
{
while((str[j]!=32)&&(str[j]!=0))
{
a[i][k]=str[j];
j++;
k++;
}
j++;
i++;
k=0;
count--;
}
for(j=0;j<n;j++)
printf("%s\n",a[j]);
}
</code></pre>
| <p>2nd loop lacks re-assignment of <code>i</code>. Deduced by <a href="http://stackoverflow.com/questions/40046270/what-is-the-difference-between-these-two-codes-it-seems-like-they-are-exactly-sa?noredirect=1#comment67383128_40046270">OP</a> after <a href="http://stackoverflow.com/questions/40046270/what-is-the-difference-between-these-two-codes-it-seems-like-they-are-exactly-sa?noredirect=1#comment67370844_40046270">hint</a></p>
<pre><code>for(i=0;i<count;i++)
a[i]=calloc(1,20);
// add
i = 0;
while(count)
{
while((str[j]!=32)&&(str[j]!=0))
{
// i has a value of count without re-assignment.
// This is UB as a[i] is eventually access outside range of a[]
a[i][k]=str[j];
j++;
k++;
}
...
</code></pre>
<p>Perhaps other issues?</p>
|
Python C Extension: PyEval_GetLocals() returns NULL <p>I need to read local variables from Python in C/C++. When I try to <code>PyEval_GetLocals</code>, I get a NULL. This happens although Python is initialized. The following is a minimal example.</p>
<pre><code>#include <iostream>
#include <Python.h>
Py_Initialize();
PyRun_SimpleString("a=5");
PyObject *locals = PyEval_GetLocals();
std::cout<<locals<<std::endl; //prints NULL (prints 0)
Py_Finalize();
</code></pre>
<p>In <a href="https://docs.python.org/3/c-api/reflection.html#c.PyEval_GetLocals" rel="nofollow">the manual</a>, it says that it returns NULL if no frame is running, but... there's a frame running!</p>
<p><strong>What am I doing wrong?</strong></p>
<p>I'm running this in Debian Jessie.</p>
| <p>Turns out the right way to access variables in the scope is:</p>
<pre><code>Py_Initialize();
PyObject *main = PyImport_AddModule("__main__");
PyObject *globals = PyModule_GetDict(main);
PyObject *a = PyDict_GetItemString(globals, "a");
std::cout<<globals<<std::endl; //Not NULL
Py_Finalize();
</code></pre>
|
Uncaught TypeError: $thirdColumnCells.each is not a function <p>I am running this but I have the console keeps giving me the error in the question title. basically I am reading the <code>href</code> value from a link and I am pushing it into a <code><ul></code></p>
<p>HTML</p>
<pre><code><div id="link"><ul></ul></div>
</code></pre>
<p>JQUERY</p>
<pre><code>var $thirdColumnCells = $hiddenContentB.find('table.wikitable tr').find('td:nth-child(3) a').attr("href");
$thirdColumnCells.each(function(idx, cell) {
var valB = $(cell).text().match(/\d+/)[0];
valuesB.push($(cell).html());
$('#link').append('<li>'+ valB + '</li>');
});
</code></pre>
| <p>jQuery's <code>.attr()</code> returns a string.</p>
<p>jQuery's <code>.each()</code> iterates over objects and arrays, usually array-like objects holding elements</p>
<p>What you're doing is </p>
<pre><code>var $thirdColumnCells = $(element).attr("href");
$thirdColumnCells.each(... // <- that's a string !!!
</code></pre>
|
RecyclerView not showing items. Adapter is not called <p>So I'm sure im making some trivial mistake somewhere and just can't see it. But I am simply trying to create a basic recyclerview list. However when I run the app nothing is shown, I put in log statements and found out that the adapter is created but nothing is ever called on it (like the bindviewholder, createviewholder, or getItemsize). I am unsure what is going on. Code is below"</p>
<p>MainActivity:</p>
<pre><code>public class MainActivity extends GvrActivity {
private ArrayList<SampleItem> videos;
private RecyclerView recyclerView;
private SampleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intialization();
}
private void intialization() {
Log.e("tree","mata intialized");
videos = new ArrayList<>();
videos.add(new SampleItem("http://vid1383.photobucket.com/albums/ah303/intellidev/congo_zpsrtmtey4l.mp4", "Adrian", 50, 100));
Log.e("tree","video added");
recyclerView = (RecyclerView) findViewById(R.id.recycle);
adapter = new SampleAdapter(this, videos);
recyclerView.setAdapter(adapter);
Log.e("tree","intialization completed");
}
}
</code></pre>
<p>Adapter</p>
<pre><code>public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.ItemHolder> {
private Context context;
private ArrayList<SampleItem> items;
public SampleAdapter(Context context, ArrayList<SampleItem> videos) {
this.context = context;
this.items = videos;
Log.e("tree","adapter created");
}
@Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.video_item, parent, false);
Log.e("tree","onCreateView Done");
return new ItemHolder(itemView);
}
@Override
public void onBindViewHolder(ItemHolder holder, int position) {
Uri uri = Uri.parse(items.get(0).getVideoUrl());
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_STEREO_OVER_UNDER;
try {
holder.view.loadVideo(uri, options);
holder.view.playVideo();
} catch (IOException e) {
Log.e("tree","onBindViewError " +e.getMessage());
}
holder.likes.setText(items.get(position).getNumOfLikes());
holder.shares.setText(items.get(position).getNumOfShares());
holder.profile.setText(items.get(position).getProfileName());
Log.e("tree","onBindViewDone");
}
@Override
public int getItemCount() {
Log.e("tree","items size is "+items.size());
return items.size();
}
class ItemHolder extends RecyclerView.ViewHolder {
private VrVideoView view;
private Button likes;
private Button shares;
private Button profile;
public ItemHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
view = (VrVideoView) itemView.findViewById(R.id.video_view);
likes = (Button) itemView.findViewById(R.id.likesButton);
shares = (Button) itemView.findViewById(R.id.sharesButton);
profile = (Button) itemView.findViewById(R.id.videoProfileButton);
}
}
}
</code></pre>
| <p>If you want to use a <code>RecyclerView</code>, you will need to work with the following:</p>
<ul>
<li><p><code>RecyclerView.Adapter</code> - To handle the data collection and bind it to
the view</p></li>
<li><p><code>LayoutManager</code> - Helps in positioning the items</p></li>
<li><p><code>ItemAnimator</code> - Helps with animating the items for common operations
such as Addition or Removal of item</p></li>
</ul>
<p>item animator is optional but adapter and Layoutmanager are necessary </p>
<p>you forgot to add layout manager. this two line of code probably solves your problem</p>
<pre><code>LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.