Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
36,747,956 | Letting users two times a day on Application | I just wanna know how to let users for **maximum two times a day** on my application. That means that the app will block the users if they are going to enter for a third time in a day. | <java><android> | 2016-04-20 15:06:40 | LQ_EDIT |
36,749,367 | how to make autoincriment key in ms sql which reset to 0 on every day start? | hey I hope you all will fine. I want to make auto_incriment key in ms sql which starts to 0 (zero) on every day start. can anyone tell me that query. thanx in advance | <sql-server> | 2016-04-20 16:04:32 | LQ_EDIT |
36,750,201 | PHP - Anti mitm attack idea | <p>I've got an idea against mitm(man-in-the-middle) attacks that i'd like to implement to my site, so i decided to ask you how secure this is. First i'd get 10 page loading times from the client computer in seconds. Then i'd calculate the standard with all those loading times. Then each time the user loads a new page i check if his/her ip address has changed and if it has i recalculate that standard and compare it to the previous standard. If this standard is 1 or 2 bigger that doesn't really matter, but if it's 4 i can log out the user. Then if the attacker has a slower internet connection he would get logged out. I'm sure i'm not the only one who has thought of this, but i don't know if this is used.</p>
| <php><security><man-in-the-middle> | 2016-04-20 16:46:57 | LQ_CLOSE |
36,751,601 | How to deserialize and array string inside an array string in C# | i have an array string such a:
[{"633" : [{"8768" : "hello","8769" : "world"}],"634" : [{"8782" : "on","8783" : "No"}]}]
i am trying to deserialize/parse this string into an array.
Here is what I have done so far:
var arrString = "[{\"633\" : [{\"8768\" : \"hello\",\"8769\" : \"world\"}],\"634\" : [{\"8782\" : \"on\",\"8783\" : \"No\"}]}]"
var attendeeArray = JsonConvert.DeserializeObject<List<Dictionary<int, string>>>(arrString); //error
this gives me the error: *Additional information: Unexpected character encountered while parsing value: [. Path '[0].633', line 1, position 11.*
i'm wondering if its because I'm calling int, string. when it should be something like int, array (int, string)??? | <c#><arrays><json><string> | 2016-04-20 17:56:43 | LQ_EDIT |
36,752,271 | Angular: How to show right and cross symbol conditionally with ng-repeat | i am new in angular.suppose i am showing employee info through **ng-repeat** in tabular format. suppose employee info has one property called **isDeveloper**. if **isDeveloper value is 1** then i will show right symbol in row and **if isDeveloper is 0** then i will show cross symbol in row. how to do it.
the trick is not coming to my head.do i need to achieve it by custom filter or custom directive ? please share the idea with bit of code sample if possible. thanks
| <angularjs><filter> | 2016-04-20 18:32:16 | LQ_EDIT |
36,752,683 | Java if else loop not working | I am currently working on a interactive timeline page generated all in js, but this loop is making the page not work
<!-- begin snippet: js hide: false -->
<!-- language: lang-js -->
if (i = 0) {
console.log('magic');
} else if (i = 1) {
console.log('magic');
} else if (i = 2 ) {
console.log('magic');
} else if (i = 3) {
console.log('magic');
} else if (i = 4) {
console.log('magic');
} else if (i = 5) {
console.log('magic');
} else if (i = 6) {
console.log('magic');
} else if (i = 7) {
console.log('magic');
} else {
console.log('magic');
}
<!-- end snippet -->
| <javascript> | 2016-04-20 18:53:44 | LQ_EDIT |
36,753,558 | Not finding occurences as intended | I have the following program, the programs purpose is to display how many times each value in the list vector occurred.
if the tuple 2:3 occurs 3 times in the array, then the program displays this to the user.
**Expected output**
- 0:8 occurred 1 time %x
- 2:3 occurred 3 time %x
- 1:5 occurred 1 time %x
- 9:5 occurred 2 time %x
**Actual Output:**
- 2:3 occurred 3 time %42
- 8:9 occurred 1 time %14
- 9:5 occurred 3 time %42
Any idea what I'm doing incorrectly? Here's a complete and verifiable working version of the code I'm using
Any assistance is greatly appreciated.
#include <vector>
#include <iostream>
#include <tuple>
using namespace std;
int counter = 0;
double percentage;
int val = 0;
vector<tuple<int, int>> list = { make_tuple(2, 3), make_tuple(0, 8), make_tuple(2, 3), make_tuple(8, 9), make_tuple(9, 5), make_tuple(9, 5), make_tuple(2, 3) };
int binarysearch(vector<tuple<int, int>> list, int low, int high, tuple<int, int> number)
{
int index = low;
int mid = 0;
// loop till the condition is true
while (low <= high) {
// divide the array for search
mid = (low + high) / 2;
if (list.at(mid) > number) {
high = mid - 1;
}
else {
low = mid + 1;
}
}return (high - index + 1);
}
int main()
{
while (counter <= list.size() - 1) {
val = binarysearch(list, counter, list.size() - 1, list.at(counter));
percentage = val * 100 / list.size();
cout << "Value: " << get<0>(list.at(counter)) << ":" << get<1>(list.at(counter)) << " Occurs: " << val << " Time(s)" << " %" << percentage << endl;
counter += val;
}
return 0;
} | <c++><frequency><find-occurrences> | 2016-04-20 19:37:58 | LQ_EDIT |
36,756,163 | keeps on giving error on the line compareResult = v.compareTo(t.getdat Thanks | public void insert(int v){
Node t = root;
int compareResu`enter code here`lt ;
compareResult = 0 ;
if((t.getData()).equals(v))return ;
if(t == null){
Node n =
Heading
-------
new Node<>(v, t, null, null);
}
else
while(t!=null){
compareResult = v.compareTo(t.getData());
if( compareResult >0){
if(t.getRight()!=null){
t = t.getRight() ;
}
else{
Node n = t.getRight();
break ;
}
}
else{
compareResult = v.compareTo(t.getData());
if(compareResult < 0){
if(t.getLeft()!=null){
t = t.getLeft() ;
}
else{
Node n = t.getLeft() ;
break ;
}
}
}
} | <java> | 2016-04-20 22:13:09 | LQ_EDIT |
36,757,313 | Java Math Prooblem | <p>I have a problem with my Java code:</p>
<pre><code>public static void GetEquation () {
equation = Main.userInput.replaceAll(" ", "");
num1 = Double.parseDouble(equation.substring(0, 1));
operator = equation.substring(1, 2);
num2 = Double.parseDouble(equation.substring(2, 3));
if (operator == "+") {
result = num1 + num2;
}
else if (operator == "-") {
result = num1 - num2;
}
else if (operator == "/") {
result = num1 / num2;
}
else if (operator == "*") {
result = num1 * num2;
}
System.out.println(result);
}
</code></pre>
<p>I found that it gets rid of the whitespace fine and it assigns the variables fine but when it comes to doing the math and displaying the result it fails.
Whatever I typed in, I would get a result of 0. I can't see what is wrong.</p>
| <java><math> | 2016-04-21 00:03:25 | LQ_CLOSE |
36,757,896 | syntax issue with a simple python script | <p>Please suggest what mistake is being made...</p>
<pre><code> #!/usr/bin/python
import datetime
get = datetime.datetime.now()
name = input("Your Name:\n")
age = int(input("Your Age:\n")
#numcopy = int(input("Number of result messages:\n"))
numcopy = int(input("Number of result messages:\n"))
currYear = get.year
century = ((100-age)+currYear)
print (numcopy * ("""Hello %r. Your current age is %r and you will turn 100 in year %r\n""" %(name,age,century)))
</code></pre>
<p>i keep getting the below error, what mistake am I making? </p>
<pre><code> File "py1", line 8
numcopy = int(input("Number of result messages:\n"))
^
SyntaxError: invalid syntax
</code></pre>
| <python> | 2016-04-21 01:15:41 | LQ_CLOSE |
36,758,705 | How to get icon back in dock(Mac)? | <p>I delete <a href="https://i.stack.imgur.com/CYFmR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CYFmR.png" alt="enter image description here"></a> by mistake. How can I get it back? Thanks!</p>
| <macos><dock> | 2016-04-21 02:48:02 | LQ_CLOSE |
36,760,308 | I already asked , but how to access view page without id value in the url. | my view.php
<?php
echo
Html::beginForm(['contactpersons/update'], 'post',['id' => 'update-form']) .
'<input type="hidden" name="id" value="'.$model->id.'">
<a href="javascript:{}" onclick="document.getElementById(\'update-form\').submit();
return false;">Update</a>'.
Html::endForm();
?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
my controller is
public function actionView($id)
{
$model = $this->findModel($id);
return $this->render('view', [
'model' => $model
]);
}
How to modify this for getting my view page without id value in the url.
Thanks in advance. | <php><yii2> | 2016-04-21 05:21:38 | LQ_EDIT |
36,761,307 | Xcode 7.2 quits unexpectedly | <p>I am trying to open the lower version of Xcode and suddenly my Xcode got crash and now whenever I am opening any of the Xcode version, I am getting this error that says " Xcode quit Unexpectedly " with three options: Ignore, Report & Reopen but still none of the option is working.</p>
| <ios><xcode7><ios9.2> | 2016-04-21 06:27:29 | LQ_CLOSE |
36,761,913 | Oracle Perfromance Tuning | I need some help with wildcard search with % operator at both ends. The no of records are nearly 7 million.
Is there any option to setup an index for this. I already created an index of index type CTXSYS which works well for single % operator at one end.
Please help. | <sql><oracle><performance><full-text-search> | 2016-04-21 06:57:15 | LQ_EDIT |
36,763,080 | can't Javascript ajax response stored in global variable | i can not access the global variable which store some ajax response data, when I console log the object itself, it give me all the details, but when i console log the arrays in that object, it returns me []. i have set the ajax request to be synchronous.
Please take a look this http://codepen.io/stanleyyylau/pen/reKrdG
//let's append content
console.log(resultObject);
console.log(resultObject.logo);
for(var ii=0; ii<channelArr.length;ii++){
resultObject.append(resultObject.logo[ii],resultObject.url[ii],resultObject.namee[ii],resultObject.statuss[ii]);
}
| <javascript><ajax> | 2016-04-21 07:46:57 | LQ_EDIT |
36,764,957 | unable to fetch data from sql | <p>i am trying to make web app for mobile repair management so far i have made it submit data to MySQL but whenever i try to retrieve data either displays blank page or it gives MySQL_num_rows() expects parameter 1 to be resource error</p>
<p>here is my code</p>
<pre><code><?php
$connect = mysqli_connect('localhost','root','password','shopdata');
if(mysqli_connect_errno($connect)){
echo 'FAILED';
}
?>
<?php
$result = mysqli_query($connect,"SELECT * FROM `jobsheets` ");
?>
<table width="1350" cellpadding=5 cellspacing=5 border=1>
<tr>
<th>JOBSHEET NO.</th>
<th>CUSTOMER NAME</th>
<th>CUSTOMERS PH.</th>
<th>MOBILE BRAND</th>
<th>MODEL NAME</th>
<th>IMEI NO.</th>
<th>FAULT</th>
<th>BATEERY</th>
<th>BACKPANEL</th>
<th>CONDITION</th
</tr>
<?php
If (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['job_number']; ?></td>
<td><?php echo $row['cust_name']; ?></td>
<td><?php echo $row['cust_mob']; ?></td>
<td><?php echo $row['mob_brand']; ?></td>
<td><?php echo $row['mob_name']; ?></td>
<td><?php echo $row['imei_number']; ?></td>
<td><?php echo $row['fault_name']; ?></td>
<td><?php echo $row['bat_status']; ?></td>
<td><?php echo $row['panel_status']; ?></td>
<td><?php echo $row['misc_note']; ?></td>
</tr>
</table>
<?php
}
}
?>**strong text**
</code></pre>
| <php><html><mysql> | 2016-04-21 09:11:05 | LQ_CLOSE |
36,764,983 | Async and Await programming help please. | want to run a void function that writes to a textblock in WPF
private async Task<int> TASK_ClickthroughBuild(string server, int frame, int click)
{
if (server == "value")
{
CreativeCode.Inlines.Add(openScript + newLine);
CreativeCode.Inlines.Add("var " + click + " = '%%CLICK_URL_ESC%%%%DEST_URL%%';" + newLine);
CreativeCode.Inlines.Add("var " + frame + " = document.getElementById('" + frame + "');" + newLine);
CreativeCode.Inlines.Add(frame + ".href = " + click + ";" + newLine);
CreativeCode.Inlines.Add(closeScript);
PASSBACKframeINT = frame;
}
return PASSBACKframeINT;
}
The above function returns an integer value and writes code to a textblock.
This is the second function.
private async Task clickElementBuild()
{
CreativeCode.Inlines.Add("<a href='#' id='" + PASSBACKframeINT + "' target='_blank' class='" + PASSBACKwrapINT + "' >" + newLine);
CreativeCode.Inlines.Add("<div class='" + PASSBACKblockINT + "' id='" + overlayINT + "'></div>" + newLine);
}
The second function, the code needs to write the textblock code ABOVE the first function, but depends on the returned value of first function to write properly.
So I need to write this in an Asynchronous format. Can I have pointers or a better way of doing this?
Thanks
| <c#><wpf><asynchronous> | 2016-04-21 09:11:58 | LQ_EDIT |
36,766,907 | How to write correctly regex pattern for less comman | How convert this pattern
Some_Word>[\n\t\r].*?[\n\t\r].*?[\n\t\r].*?<symbol>BK<\/symbol>
to be **less** recognize his?
P.S. I checked [here][1] that patter with the text and it work correctly:
before bla bla<Some_Word>
ssssssssssssssssssss>
dddddddddddddddddddd>
ccccccccccccccccccccc <symbol>BK</symbol>
after bla bla>
Help me please.
Thanks for advance!
[1]: https://regex101.com/ | <regex><linux><less-unix> | 2016-04-21 10:32:36 | LQ_EDIT |
36,767,564 | How to insert Null Values of type double in ANDROID | <p>I created a table with six cloumns as described below when am i putting the null vales in second row of type double it shows error.</p>
<p>How to put empty values in double place </p>
<pre><code>myDB.insert("Hotel MidCity",16.5048,80.6338,"Vijayawada",16.251,80.666);
myDB.insert("Minerva Hyderabad",16.5024,80.6432,"Null", , );
</code></pre>
<p>Thank you..</p>
| <android> | 2016-04-21 10:59:31 | LQ_CLOSE |
36,768,552 | C#. Count Consecutive 1 bits in ulong | <p>Basically i want to count the number of consecutive 1 bits (1 bit groups) in a ulong. for example:
ulong x = 0x1BD11BDAA9FC1A22UL;
In binary it becomes: 1101111010001000110111101101010101001111111000001101000100010.
I need output as No of consecutive 1 bits = 16.</p>
| <c#> | 2016-04-21 11:42:51 | LQ_CLOSE |
36,768,642 | How do I display RSS feeds from other web sites | <p>I am trying to display a blog: <a href="http://miletich2.blogspot.co.uk/" rel="nofollow">http://miletich2.blogspot.co.uk/</a> on my clients Wordpress site and as I have been looking around people have been recommending <code>simple pie</code> and their demo works great, but their Wordpress plugin hasn't been updated in 2 years and has loads of bugs.</p>
<p>Does any one know of another plugin that has the same functionality? Any help would be appreciated!</p>
| <php><wordpress><rss> | 2016-04-21 11:46:44 | LQ_CLOSE |
36,770,341 | usage of interface in the android development | <p>Hi friends I want to know how to use interfaces in the android development I had searched everywhere, but there is no clear document to know how to use an interface in our android development </p>
| <java><android><android-layout><android-fragments><android-studio> | 2016-04-21 12:57:25 | LQ_CLOSE |
36,770,646 | The Value value from final Variable Give me minus | I try to make some some with various variables and it should give 200 on final response But It Give me -200 What Is Wrong With My Code Why It give -200 i want it to give me 200 on final some
My App Send An Ajax call With a variable $Points but for security i have made a some with more two variables
for example if the user have 200 points the app it will add the ntruck=412020 and truck=20201
so on final it send to the php script the value 432221+200=432421
wen the script is load it take from total 432421-ntruck-truck so it will stay only the value of the points 200
This Is my code:
<!-- begin snippet: js hide: false -->
<!-- language: lang-html -->
<?php
$point = "432421";
$ntruck = "412020";
$truck = "20201";
$sum_total = $truck + $ntruck;
$npoints = $sum_total - $point;
$points = $npoints;
echo $points;
?>
<!-- end snippet -->
But Wen I Make An Echo It Give me minus -200 where i have failed | <php> | 2016-04-21 13:09:56 | LQ_EDIT |
36,770,676 | nodeJs - can't acces required properties | <p>I have 2 separate files - the main script file and config.js located in the same folder.</p>
<p>I then require the config.js as a variable, and try to access it's url property, but somehow it does not get injected properly. What am I doing wrong?</p>
<p>If I define a local variable with the url, and pass it into my function everything works as expected.</p>
<p>main.js:</p>
<pre><code>//import configuration
var config = ("./config.js");
casper.start(config.url);
</code></pre>
<p>config.js</p>
<pre><code>module.exports = {
url: 'http://stage2.btobet.net/en',
credentials: [{ user: 'Tester', password: '' },
{ user: 'Automat', password: '' }]
};
</code></pre>
<p>Thanks for the help.</p>
| <javascript><node.js> | 2016-04-21 13:11:12 | LQ_CLOSE |
36,770,700 | Illegal instruction 4 - Python | I can’t get Pycharm in my current project to run the debugger.
When I run the debugger, it throws me that:
/Users/jeremie/.local/share/virtualenvs/proxi-server/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 52293 --file /Users/jeremie/Code/proxi-server/server.py
Process finished with exit code 132
I ran that command on my terminal to figure out the problem:
Illegal instruction: 4
Didn't help me much. | <python><pycharm><gevent> | 2016-04-21 13:12:14 | LQ_EDIT |
36,770,959 | java return statement not returning | Why does the code below return -1 instead of arr.length-1? If the find function is looking for 24 it should return 5, but returns -1. It should only return -1 if n is not found in arr. Thanks for your help.
public class linearArraySearch {
public static void main(String[] args) {
int[] numbers = new int[]{ 12, 42, 56, 7, 99, 24, 6, 1, 5 };
System.out.println( find(numbers, 24) );
}
public static int find( int[] arr, int n ){
if( arr[arr.length-1] == n ){
return arr.length-1;
}else if( arr.length > 1 && arr[arr.length-1] != n ){
int[] temp = new int[arr.length-1];
for( int i = 0; i < temp.length; i++ ){
temp[i] = arr[i];
}
find( temp, n );
}
return -1;
}
} | <java><recursion><return><linear-search> | 2016-04-21 13:23:13 | LQ_EDIT |
36,771,777 | Diffrent size on nav-bar on diffrent pages | Hi if you check the site im building http://pripper.github.io/obk/index.html
So can you see that the nav bar is changing size on difrent pages and I dont know why it does it. plz some1 help me out. | <html><css> | 2016-04-21 13:53:13 | LQ_EDIT |
36,773,104 | How do I return multiple strings from a method in C# | <p>If I have something like:</p>
<pre><code> static string characterName()
{
Console.Write("Name your character: ");
string name = Console.ReadLine();
Console.Write("Is this correct? (Y/N): ");
string nameConfirm = Console.ReadLine();
return nameConfirm;
}
</code></pre>
<p>How can I change this so it outputs both nameConfirm and name.
The nameConfirm goes into:</p>
<pre><code> static string stageOne(string nameConfirm)
{
while (nameConfirm != "Y")
nameConfirm = Program.characterName();
if (nameConfirm == "Y")
{
Console.WriteLine("Alright, lets continue.");
nameConfirm = Console.ReadLine();
}
return nameConfirm;
</code></pre>
<p>That works fine but I want to be able to call upon the name later if its needed.</p>
| <c#><methods> | 2016-04-21 14:47:25 | LQ_CLOSE |
36,773,830 | Why templates must be defined outside class | <p>I know that templates must be declared and defined in the same file. But, why I cannot:</p>
<pre><code>#ifndef guard
#define guard
template<typename T>
class Test{
void method(){
}
};
#endif
</code></pre>
<p>And it is causes compiler error ( not directly but instatantiation template Test in two different place- for example in main() and as field in any class causes error. </p>
<p>It must be defined outside class ( It doesn't cause error like here)</p>
<pre><code>#ifndef guard
#define guard
template<typename T>
class Test{
void method();
};
#endif
template<typename T>
void Test<T>::method(){}
</code></pre>
<p>Why?</p>
| <c++> | 2016-04-21 15:16:17 | LQ_CLOSE |
36,774,337 | convert char* to int in C | Is there any way to convert char* to int?
Got string(string1) of characters received from UART
this string looks like: {3600,32,300}
char t1_s[32],t2_s[32],t3_s[32];
static char string1[15];
strcpy(t3_s, strtok(string1 , ","));
strcpy(t2_s, strtok(NULL , ","));
strcpy(t1_s, strtok(NULL , ","));
t1= t1_s - '0';
t2= t2_s - '0';
t3= t3_s - '0';
and compiller get warning
#515-D a value of type "char *" cannot be assigned to an entity of type "int" main.c
Need to get values t1_s,t2_s,t3_s to integer.
| <c> | 2016-04-21 15:36:29 | LQ_EDIT |
36,775,700 | plots the function with arraysin matlab | <p>funcplot that plots the following function on interval [-pi,pi] using 1000
linearly spaced data points.How can I do that with arrays ? Idon't have any idea.</p>
<p>f(x) = 5cos (x4
/3)tan(e
0.2x
)cos(ln(4x))</p>
| <matlab><function><plot> | 2016-04-21 16:37:17 | LQ_CLOSE |
36,776,523 | read textfile to a 2D verctor in c99 | i have a textfile with some rows of text
i want to put the text into a 2D vector because i
need to be able to call each character seperatly [x][y]
this is what i got:
int main() {
// Variable declarations
fstream file;
int i=0;
vector<vector<char> > maze(1,vector<char>(1));
ifstream myReadFile;
myReadFile.open("input.txt");
while (!myReadFile.eof()) {
for (int j=0; maze[i][j] != "\0"; j++){
myReadFile >> maze[i][j];
}
i++;
}
file.close();
for (int i = 0; i < maze.size(); i++)
{
for (int j = 0; j < maze[i].size(); j++)
{
cout << maze[i][j];
}
}
return 0;
}
| <c++><file-io><stdvector> | 2016-04-21 17:22:12 | LQ_EDIT |
36,777,229 | How to show an bootsrap modal popup using inside php code | i want to display this modal popup after php condition check.
<div id="myModal65" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Subscribe our Newsletter</h4>
</div>
<div class="modal-body">
<p>Subscribe to our mailing list to get the latest updates straight in your inbox.</p>
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email Address">
</div>
<button type="submit" class="btn btn-primary">Subscribe</button>
</form>
</div>
</div>
</div>
</div>
in this php code used for display the popup.but it cannot display.
<?php
if($intwschdle==1)
{
echo "<script type='text/javascript'>$('#myModal65').modal('show');</script>";
}
?>
| <javascript><php> | 2016-04-21 18:04:59 | LQ_EDIT |
36,777,718 | Double variable to setlatitude error | NullPointerException this error happens when i try to set `location2.setLatitude(latitudeclick);`
I test the app and i receive when i click the value out of latitudeclick
@Override
public void onResult(PlaceBuffer places) {
if (places.getCount() == 1) {
localizacao = (places.get(0).getLatLng());
Double latitudeclick = localizacao.latitude;
Double longitudeclick = localizacao.longitude;
Location location2 = null;
location2.setLatitude(latitudeclick);
location2.setLatitude(longitudeclick);
} | <android> | 2016-04-21 18:29:54 | LQ_EDIT |
36,777,736 | How can I determine whether a checkbox is checked in jQuery? | <p>I dynamically create a bunch of checkboxes like so:</p>
<pre><code>@foreach (var rpt in reports)
{
@* convert id to lowercase and no spaces *@
var morphedRptName = @rpt.report.Replace(" ", string.Empty).ToLower();
<input class="leftmargin8, ckbx" id="ckbx_@(morphedRptName)" type="checkbox" value="@rpt.report" />@rpt.report
}
</code></pre>
<p>I've got this event handler where I want to determine their state - checked or unchecked:</p>
<pre><code>$(".ckbx").change(function () {
if ($(this).checked) {
alert('checkbox is unchecked');
checkboxSelected = false;
return;
}
alert('checkbox is checked');
. . .
</code></pre>
<p>However, the condition "if ($(this).checked)" is <em>always</em> false, both when I check a checkbox and when I subsequently uncheck/deselect it.</p>
<p>So what do I need to do to determine when it is unchecked? I actually tried this first: "if (!$(this).checked)" but that just did the reverse - the condition was always true.</p>
| <javascript><jquery><checkbox><onchange> | 2016-04-21 18:30:57 | LQ_CLOSE |
36,777,873 | Why does this code using fork() work? | <p>I've this code that executes some code depending of if the active process is the parent or the child process in an infinite loop:</p>
<pre><code>pid_t childPID;
childPID=fork();
while (1)
{
if (childPID >=0)
{
if (childPID==0)
{
[do child process stuff]
}
else
{
[do parent process stuff]
}
}
else
{
printf("\n Fork failed, quitting!!!!!\n");
return 1;
}
}
</code></pre>
<p>Code is simple but there's one very big thing on it for me which I don't understand how it happens although I have a guess:</p>
<p>If not taking into consideration that we're creating 2 processes it looks like childPid is constantly being reasigned which I don't think makes any sense.</p>
<p>So my guess, is that fork creates a childPid for each process, returning a 0 to the parent process and the pid to the child process, even though this syntax makes me think it should only return only one result and assign it to chilPid.</p>
<p>Is my guess correct or is there some other thing involved?</p>
<p>Thank you.</p>
| <c><fork> | 2016-04-21 18:38:20 | LQ_CLOSE |
36,778,239 | Longest substring of repeated characters | <p>I have an assignment for school in which, given an input string of entirely 0's and 1's, I must return the length of the longest substring of repeated 1's. I am not allowed to use I am having trouble fleshing out my idea.
So far I have found the length of the input string and converted the input string to uint8. That way I can use find to find the indices of the ones. My next thought was to do some sort of for loop to store the indices, or maybe the check the length of each subset and only save the longest one? But I'm not sure how to go about this part or if this is even the right way to think about it. Any guidance is appreciated.</p>
| <string><matlab> | 2016-04-21 18:58:17 | LQ_CLOSE |
36,778,684 | Why I am getting null exception when using an Interface | <pre><code>public class Blah
{
public bool Whatever { get; set; }
public string WhatYouJustSaid { get; set; }
}
public interface IBlah
{
Blah BlahValues { get; set; }
}
class Class1:IBlah
{
public Blah BlahValues { get; set; }
}
</code></pre>
<p>And then for example:</p>
<pre><code> Class1 c1 = new Class1();
c1.BlahValues.WhatYouJustSaid = "nothing";
c1.BlahValues.Whatever = false;
</code></pre>
<p>So how should I change my code that <code>BlahValues</code> doesn't get null? </p>
| <c#> | 2016-04-21 19:22:52 | LQ_CLOSE |
36,778,692 | What is the benefit of using a pointer C++ | <p>I Was just confused on the part of using a pointer on C++.. well you might say, "a pointer is obviously a memory adress of another variable and there are certaintly conditions in your program where you will need them". But i dont mean pointer in general, i mean the pointer you use to like "simulate" a class... I think code will explain it more:</p>
<pre><code>#include <iostream>
#include <string>
#include "Book.h"
int main() {
Book book1;
Book *bookPointer = &book1;
book1.setBooksId(123);
std::cout << "BOOK ID: " << book1.getBookId() << std::endl;
(*bookPointer).setBooksId(300);
std::cout << (*bookPointer).getBookId() << std::endl;
/*When usage of arrow member selection member, left is always a pointer.
Same thing as above, but better practice!
*/
bookPointer->setBooksId(100);
std::cout << "POINTER ARROW : " << bookPointer->getBookId() << std::endl;
return 0;
}
</code></pre>
<p>Here you see i have another pointer that is called bookPointer which all it does is the same as the original instance of book class book1... I dont get it.. What is the advantage of using this? Give me a scenario if you can! Thanks for Helping!!</p>
| <c++><pointers> | 2016-04-21 19:23:16 | LQ_CLOSE |
36,780,776 | python application that queries a database | <p>I need to develop a GUI desktop application that takes input from the user, does some calculations, and then runs a bunch of queries which should be exported into a csv, xls or txt file. I want to create an installation package which the user can install without installing any other applications (used for front end) and other database (other than MS Access). My questions are</p>
<ol>
<li><p>If I use python for my front-end/GUI, can I create an installation package? I understand that we can create and .exe file from the .py file. I want the dB to be get copied in the right folder (path referenced in my program) on the end-user's computer when the user installs the package.</p></li>
<li><p>MS Access (2010) on my computer (Windos 7 OS) is 32-bit and I'm having trouble using it with 64-bit python (version 3.5.1) and pyodbc(version 3.0.10). Can I use any alternate dB (sqlite?) that the user doesn't have to install to run the application and I don't have to worry about getting the dB in the right folder on the end-users computer. My dB is very small (few tables with about 1000 rows each).</p></li>
</ol>
<p>Thanks much!</p>
| <python><database><user-interface> | 2016-04-21 21:25:53 | LQ_CLOSE |
36,781,123 | Sorting top three using mysql/php | <p>I want to get the three entities with highest value from my database, sort them and place them in each their div's just like a scoreboard with the top three. I will also be able to separate the fields (id, name, description etc.) and retrieve those by using for example:</p>
<pre><code><?php echo $sql['id']; ?>
</code></pre>
<p>I already know the code to retrieve the info and sort it:</p>
<pre><code>$sql = ("SELECT * FROM table ORDER BY tablefield DESC LIMIT 3");
</code></pre>
<p>But I don't know how to place the three entities into each their div's and separate the entity's fields like name, description etc.</p>
| <php><html><mysql><database><limit> | 2016-04-21 21:52:02 | LQ_CLOSE |
36,781,273 | Unreachable code? user image upload | <p>Eclipse keeps showing me the syntax error to insert '}' to complete Classbody at the dne of my code, but when i do so, it shows a different error that the last part of the code is unreachable? What am i doing wrong?</p>
<p>My code: </p>
<pre><code> public class GetImage extends Activity {
private static final int MyImage =1;
ImageView iv;
@Override
protected void onCreate(Bundle savedInsatnceState){
super.onCreate(savedInsatnceState);
setContentView(R.layout.diary_edit);
iv=(ImageView)findViewById(R.id.imageView1);
}
public void btnClick(View v){
Intent int3 = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(int3,MyImage);
}
@Override
protected void onActivityResult (int requestCode , int resultCode , Intent data){
super.onActivityResult(requestCode , resultCode , data);
switch (requestCode){
case MyImage :
if(resultCode == RESULT_OK){
Uri uri=data.getData();
String[]projection ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver ().query(uri,projection , null,null,null);
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(projection[0]);
String filePath=cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage=BitmapFactory.decodeFile(filePath);
Drawable d=new BitmapDrawable(yourSelectedImage);
iv.setBackground(d);
}
break;
ault:
break;
}
}
</code></pre>
| <java><android> | 2016-04-21 22:05:22 | LQ_CLOSE |
36,781,308 | Passing any array type to a function in C | <p>I am trying to write a function that makes ordenations over any numeric array given to it.
The problem is that C needs to know the data type to iterate through the array properly, because of its "pointer nature".
Is there any way that I can pass any array without knowing the type? Maybe using the void type?</p>
<pre><code>void ordenation (void *array, ...) {}
</code></pre>
| <c><arrays><function> | 2016-04-21 22:07:32 | LQ_CLOSE |
36,781,453 | If abstract base class contains parameterised constructor (and derived does not) why can't it be used? | <p>I have a DDD type solution with "domain model" classes which are constructed using a "DTO" class (i.e. raw data from DB). </p>
<p>The domain model classes all inherit from an abstract base class, which is intended to provide generic injecting/retrieving of the DTO data. Here is a sample:</p>
<pre><code>public abstract class DomainModelBase<T> where T : IDto, new()
{
protected T _data;
protected DomainModelBase()
{
_data = new T();
}
protected DomainModelBase(T data)
{
_data = data;
}
protected void SetData(T data)
{
_data = data;
}
public T GetData()
{
return _data;
}
}
public class AttributeOption : DomainModelBase<AttributeOptionData>
{
//public AttributeOption(AttributeOptionData data)
//{
// SetData(data);
//}
}
</code></pre>
<p>I thought (because DomainModelBase contains a parameterised constructor) I would be able to do this:</p>
<pre><code> var data = new AttributeOptionData();
var model = new AttributeOption(data);
</code></pre>
<p>However, the compiler says "Constructor 'AttributeOption' has zero parameters, but is invoked with one argument". The only way to make it work seems to be to create a parameterised constructor in the derived class (like the commented out one above).</p>
<p>Is there a way to make this work by modifying the base class, i.e. without the work of setting up parameterised constructors in every derived class?</p>
| <c#><generics><inheritance><constructor><domain-driven-design> | 2016-04-21 22:21:35 | LQ_CLOSE |
36,782,473 | Haveing trouble getting rid of the extra space to the right of my content | <p>I am using a bootstrap 3 grid on my website and I am having trouble with getting rid of this extra space thats to the right of all my content. Allowing the bottom scrollbar to be visible and move. I dont want to hide the scrollbar I know How to do that. I simply just want to fit the content to the page so that there isnt reason for the bottom scrollbar to display. Just want to make my content fit to the page. So I can continue redesigning..... </p>
<p>www.Trillumonopoly.com/index2.html</p>
| <html><css><twitter-bootstrap-3> | 2016-04-22 00:04:46 | LQ_CLOSE |
36,784,340 | Finding the last row with data using vba | <p><strong>I am creating a program in which everytime it generates, the generated data will appear in a specific sheet and arranged in specific date order . It looks like this.</strong></p>
<p><a href="https://i.stack.imgur.com/1vUeq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1vUeq.png" alt="Generated data"></a></p>
<p>But when I generate again, the existing data will be replaced/covered by the new data generated. Looks like this.</p>
<p><a href="https://i.stack.imgur.com/KM55r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KM55r.png" alt="enter image description here"></a></p>
<p>Now my idea is, before I am going to paste another data, I want to find out first what is the last used cell with value so that in the next generation of data, it wont be replaced/covered by the new one. Can someone help me with this. The output should look like this.</p>
<p><a href="https://i.stack.imgur.com/YLXnq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YLXnq.png" alt="enter image description here"></a></p>
<p>Any help everyone? Thanks! </p>
| <vba><excel><row> | 2016-04-22 03:33:16 | LQ_CLOSE |
36,786,655 | How to Connect Mongodb to PHP Please tell me step by step | I am unable to Connect to PHP with mongodb. I have already done the all of process but unknown error is occur again and again.
Fatel error: Mongo Class not Found.
If anyone face this problem and solved it, so please tell me about this and how to fix this problem. | <php><mysql><mongodb> | 2016-04-22 06:39:36 | LQ_EDIT |
36,787,167 | Install programm on computer | <p>I have jar file. </p>
<p>Also I have batch file, which contains:</p>
<blockquote>
<p>start javaw -jar Name.jar</p>
</blockquote>
<p>I want make .exe-file, which copy jar-file in choosen folder and add batch-file to autorun. </p>
<p>How I may make it?</p>
| <java><windows><batch-file><jar><installation> | 2016-04-22 07:05:39 | LQ_CLOSE |
36,787,467 | DJANGO: Showing many-to-many fields in template | # I have this situation :
**Models:-**
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
date = models.DateTimeField()
class Meta:
ordering = ["-name"]
def __unicode__(self): # __unicode__ on Python 2
return self.name
class Author(models.Model):
publisher = models.ForeignKey(Publisher)
salutation = models.CharField(max_length=10)
name = models.CharField(max_length=200)
email = models.EmailField()
headshot = models.ImageField(upload_to='author_headshots')
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField('Author')
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
publication_date = models.DateField()
def __str__(self):
return self.title
def get_authors(self):
return "\n".join([a.name for a in self.authors.all()])
# i want to show authors field in template with Publishers
**Template**:
{% for a in obj.pk|get_author %}
{{ a.name }}<br/>
{{ a.headshot }}
{% endfor %}
**Custom Template Tags:**
def get_author(pk):
try:
publisher = Publisher.objects.get(pk=pk)
print type(publisher)
author = Author.objects.filter(Publisher=publisher)
print author
except:
author = []
return author
register.filter('get_author', get_author)
| <django> | 2016-04-22 07:21:25 | LQ_EDIT |
36,787,577 | Linux:i can not understand a m4 command | My work is converting Linux command into CMake execute_process(COMMAND ...), and there are some differences between them, so i need to understand each Linux command. But this m4 command really beat me. The m4 command as below:
<!-- language: lang-html -->
m4 -Isource/analyzer/ -P < source/analyzer/aParser.m4y > source/analyzer/aParser.by
What does this command mean?
| <m4> | 2016-04-22 07:27:17 | LQ_EDIT |
36,789,179 | Get the id of the clicked link | <p><strong>I'd like to get the id of the clicked link with jQuery.</strong> Why does this return <code>Undefined</code> instead?</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>test = function(e) {
alert($(e).attr('id'));
return false;
}
$('.bleu').click(test)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="" class="bleu" id="h12">azeaze12</a>
<a href="" class="bleu" id="h13">azeaze13</a>
<a href="" class="bleu" id="h14">azeaze14</a></code></pre>
</div>
</div>
</p>
| <javascript><jquery> | 2016-04-22 08:49:44 | LQ_CLOSE |
36,789,626 | PHP Fatal error, Uncaught Error Exception | <p>This is the error i am getting when i run any script in localhost.My connection is right and in another laptop all the scripts are executing perfectly in localhost.How to solve this error..?</p>
<p><a href="http://i.stack.imgur.com/4jZXR.png" rel="nofollow">IMAGE</a></p>
| <php><mysql> | 2016-04-22 09:11:08 | LQ_CLOSE |
36,790,919 | Why do we need object Serialization in C++? | <p>Do we always need to serialize the object in c++ if we want to persist that object or to transfer over network, or in special cases only.</p>
<p>For instance if I have an object of the class </p>
<pre><code>class Test
{
int a;
char b;
float c;
};
</code></pre>
<p>i.e. it contains only primitive types do I need to serialize it?</p>
| <c++><c++11><serialization> | 2016-04-22 10:10:28 | LQ_CLOSE |
36,791,290 | UNIX script to check if httpd service is on or off and if off send a email | <p>Script to check if httpd is on or no</p>
<p>How do I make this script run in background so that it keeps checking if httpd service is on or off and emails a message if it goes off !! ( PS-: I DON'T WANT TO MAKE THE SCRIPT AS A CRONJOB) just like a daemon process which runs in background!!
Please Help</p>
| <linux><bash><email><unix><command> | 2016-04-22 10:27:52 | LQ_CLOSE |
36,793,446 | I am not able to get specific values from url | I have a url
market://details?id=com.balancehero.truebalance&referrer=utm_source%3Dapp%26utm_medium%3Dlink%26utm_term%3D%26utm_content%3D%26utm_campaign%3Dmgm%26campid%3D2FC42T27%26m%3D1%26trackingid%3D000146132647632302db63d958690001
How can i get this value from above url 000146132647632302db63d958690001
Can i use preg_match function or something else.
| <php> | 2016-04-22 12:07:08 | LQ_EDIT |
36,795,897 | how to convert mysql query to php query? | SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(CASE WHEN ca.date = ''',
date_format(date, '%Y-%m-%d'),
''' THEN coalesce(p.status, ''P'') END) AS `',
date_format(date, '%Y-%m-%d'), '`'
)
) INTO @sql
FROM calendar
where date>='2013-06-01'
and date <= '2013-06-05';
SET @sql
= CONCAT('SELECT ca.studentname,
ca.rollno,
ca.class, ', @sql, '
from
(
select c.date, a.studentname, a.rollno, a.class
from calendar c
cross join tbl_admission a
) ca
left join tbl_absentees p
on ca.rollno = p.rollno
and ca.date = p.date
where ca.date>=''2013-06-01''
and ca.date <= ''2013-06-05''
group by ca.studentname, ca.rollno, ca.class
order by ca.rollno');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt; | <php><mysql> | 2016-04-22 14:01:40 | LQ_EDIT |
36,796,243 | building a calendar using javascript where you can add and modify events | <p>I want to build a calendar with javasCript that allow users to enter their shift manually and have 2 option when a date is clicked on( swap or give away)? any thought on how to do it? im I going to need an API? building the calendar will I have to build it using table or which is most efficient way?
I am a rookie coder who started less than a month so pardon if I am not too specific.</p>
| <javascript><jquery><html> | 2016-04-22 14:16:56 | LQ_CLOSE |
36,797,435 | PCR (Doller weighted Put Call Ratio)calculation issues | I am trying to generate a Put / Call Ratio calculation program for my own purpose.Here is the code: problem is I am stuck in some places.
1.I need to generate a summation of all strikes volume * all strikes prices
2. and final one is generating the ratio.
So far I tried a lot and ended up having buggy program.However I am providing the code for now for further so that I can complete the rest of the part get the OutPut properly.(nse DO not provide PCR as CBO does provide a solution)
from nsepy import get_history
from datetime import date
import pandas as pd
import requests
from io import BytesIO
import certifi
from scipy import stats
from dateutil.relativedelta import relativedelta
import numpy as np
#import matplotlib.pyplot as plt
import datetime
import numpy as np
import matplotlib.colors as colors
import matplotlib.finance as finance
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import talib as ta
from talib import MA_Type
import statsmodels as sm
nf_calls=[]
nf_puts=[]
wPCR=[]
#nf_calls[['VolumeCalls']]=np.nan
#nf_puts[['VolumeCalls']]=np.nan
i=min_avalable_strikes=4850
max_avalable_strike=9400
while i in range(min_avalable_strikes,max_avalable_strike):
nf_opt_CE = get_history(symbol="NIFTY",
start=date(2016,4,1),
end=date(2016,4,22),
index=True,
option_type="CE",
strike_price=i,
expiry_date=date(2016,4,28))
#print(nf_opt_CE.head())
#if nf_opt_CE['Number of Contracts'].values >0 :
'''if nf_opt_CE.empty :
nf_opt_CE.append(0)
'''
nf_opt_PE = get_history(symbol="NIFTY",
start=date(2016,1,1),
end=date(2016,4,18),
index=True,
option_type="PE",
strike_price=i,
expiry_date=date(2016,4,28))
print(nf_opt_PE.head())
#print(nf_opt_PE.head())
#print(i)
#if nf_opt_PE['Number of Contracts'].values>0 :
'''if nf_opt_CE.empty :
nf_opt_PE.append(0)
'''
i=i+50
#print(wPCR)
'''def PCRForSym():
return NULL
'''
nf_opt_PE['NewCols']=nf_opt_PE['Number of Contracts']* nf_opt_PE['Close']
nf_opt_CE['NewCols']= nf_opt_CE['Number of Contracts']*nf_opt_CE['Close']
#wPCR=nf_puts
print(nf_opt_PE.head())
| <python><pandas><numpy> | 2016-04-22 15:10:04 | LQ_EDIT |
36,797,925 | Include path with constant and variable | <p>I'm trying to include a file to current php page but the name of the file depens on the lang.</p>
<p>This line does not work:</p>
<pre><code>include_once PATH.'lang/'.$_SESSION['lang'].'.php';
</code></pre>
<p>How can I achieve that?</p>
| <php><include> | 2016-04-22 15:33:06 | LQ_CLOSE |
36,798,304 | PHP if condition number issue | <p>The php code is returing true in both cases show below. I dont know why?</p>
<pre><code><?php
$cid = 150;
if ($cid=100)
{
echo $cid;
echo "<BR>";
}
if ($cid==100)
{
echo "NEW";
echo "<BR>";
echo $cid;
echo "<BR>";
}
?>
</code></pre>
<p>The output is: <BR>
100<BR>
NEW<BR>
100<BR></p>
<p><BR>Why is the if condition not working?</p>
| <php> | 2016-04-22 15:51:40 | LQ_CLOSE |
36,798,763 | could not convert string to float: price[0] - python | <p>I want to make a currency converter which will take the current exchange rate from yahoo and multiply it with the amount the user wants. But I cannot multiply them. Could you please help me?</p>
<p>I always get:
Traceback (most recent call last):File "C:\Users\Ioannis\Desktop\c.py", line 17, in realprice = float("price[0]")</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import urllib
import re
stocklist = ["eurusd"]
i=0
while i<len(stocklist):
url = "http://finance.yahoo.com/q?s=eurusd=X"
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
regex = '<span id="yfs_l10_eurusd=x">(.+?)</span>'
pattern = re.compile(regex)
price = re.findall(pattern,htmltext)
print "the price of", stocklist[i],"is" ,price[0]
i+=1
realprice = float("price[0]")
print ("Currency Exchange")
ex = raw_input("A-Euro to Dollars, B-Dollars to Euro")
if ex == "A":
ptd = int(raw_input("How much would you like to convert: "))
f = ptd*price[0]
print("It is $",f)
if ex == "B":
ptd = float(raw_input("How much would you like to convert"))
f = ptd*0.7
f2 = round(f,2)
print ("It is $",f2)</code></pre>
</div>
</div>
</p>
<p>ValueError: could not convert string to float: price[0]</p>
<p><a href="http://i.stack.imgur.com/xsaXB.jpg" rel="nofollow">python code</a></p>
| <python> | 2016-04-22 16:17:18 | LQ_CLOSE |
36,799,950 | Operator Overloading in Binary Tree c++ | I am writing various operator overloads for a binary tree function that I am creating, the specifications require an overload for
binary_tree& binary_tree::operator=(const binary_tree &other)
{
return binary_tree();
}
the test for the operator working is as follows,
int main(int argc, char **argv)
{
tree = new binary_tree(vector<int>{11, 5, 3, 7});
binary_tree temp = *tree;
temp.insert(12);
str = temp.inorder();
if (str != string("3 5 7 11 12") && temp.inorder() != tree->inorder())
cerr << "test failed (assignment operator)" << endl;
else
cout << "test passed (assignment operator)" << endl;
}
Obviously the point of this test is to create a new tree temp, which has the values of the original, but I can't seem to get it to work so that when .insert(12) is called, it doesn't alter the original tree. The operator has to work based on the test given in main, unedited.
I have tried various things inside the = operator but none of them seem to have any effect. I have methods that can copy values from one tree to another, but none that seem to work with the given test.
Thanks for any help | <c++><tree><operator-overloading><binary-tree> | 2016-04-22 17:26:12 | LQ_EDIT |
36,800,380 | Perl: using unpack to split a string into fixed length - then reading the next line | I have an JSON Body of an http post that has to be split into 80 character double quoted strings - but - whenever I use unpack to read the first 80 characters, the string pointer in the source string (which is not CR/LF delimited at the end of each line yet) never changes - e.g. the loop below keeps reading the same string over and over:
@row =unpack 'A80', $body;
foreach $line (@row)
{
@row =unpack 'A80', $body;
print '"'.$line.'"' ;
}
| <perl><unpack> | 2016-04-22 17:53:50 | LQ_EDIT |
36,800,503 | Javascript- Uncaught SyntaxError: Unexpected token if | I'm new to Javascript!
if (fname == null || fname == "") {
Getting uncaught syntax error:unexpected token if in line 13. It says "SyntaxError: missing variable name" in Javascript lint
function validateregistration()
{
var emailRegex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/;
var fname = document.form.user_firstname.value,
lname = document.form.user_lastname.value,
uname = document.form.username.value,
femail = document.form.email.value,
freemail = document.form.verify_email.value,
fpassword = document.form.password.value,
if (fname == null || fname == "") {
document.form.user_firstname.focus();
document.getElementById("errorBox")
.innerHTML = "enter the first name";
return false;
}
if (lname == null || lname == "") {
document.form.user_lastname.focus();
document.getElementById("errorBox")
.innerHTML = "enter the last name";
return false;
}
if (femail == null || femail == "") {
document.form.email.focus();
document.getElementById("errorBox")
.innerHTML = "enter the email";
return false;
} else if (!emailRegex.test(femail)) {
document.form.Email.focus();
document.getElementById("errorBox")
.innerHTML = "enter the valid email";
return false;
}
if (freemail == null || freemail == "") {
document.form.verify_email.focus();
document.getElementById("errorBox")
.innerHTML = "Re-enter the email";
return false;
} else if (!emailRegex.test(freemail)) {
document.form.enterEmail.focus();
document.getElementById("errorBox")
.innerHTML = "Re-enter the valid email";
return false;
}
if (fpassword == null || fpassword == "") {
document.form.password.focus();
document.getElementById("errorBox")
.innerHTML = "enter the password";
return false;
}
} | <javascript> | 2016-04-22 18:01:10 | LQ_EDIT |
36,801,645 | My site won't display content images | My website won't display images on http://teretana.mk/. When I open the debugging console in Chrome I get 2 errors which I do not understand at all(can be seen here http://i.imgur.com/2tLcsl3.jpg). I hope someone will be able to resolve this issue I've had all day. And hopefully this will fix the images, it's also really weird if you go in a post like this one http://teretana.mk/2016/04/22/td_d_slug_20/ you can actually drag the blank image in Chrome(maybe in other browsers too) and the actual image will display. | <javascript><wordpress> | 2016-04-22 19:12:48 | LQ_EDIT |
36,801,665 | Invalid types 'int[int]' for array subscript - multi-dimensional array | <p>I'm getting an " Invalid types 'int[int]' for array subscript error ".
I searched for the same, but the previously asked Q's involved objects. This is a simple snippet.</p>
<blockquote>
<p>Code</p>
</blockquote>
<pre><code> #include<iostream>
#include<cmath>
using namespace std;
int main()
{
int *a;
a = new int a[10][10]; //Line 8
for(int z=0;z<10;z++)
{
for(int y=0;y<10;y++)
{
a[z][y]=y; // Line 13
cout <<"\t"<<a[z][y]<<endl; // Line 14
}
}
return 0;
}
</code></pre>
<blockquote>
<p>Error</p>
</blockquote>
<ol>
<li><p>Line 8 error: expected ';' before 'a'</p></li>
<li><p>Line 13 error: invalid types 'int[int]' for array subscript</p></li>
<li>Line 14 error: invalid types 'int[int]' for array subscript</li>
</ol>
| <c++><arrays><c++11><multidimensional-array><c++14> | 2016-04-22 19:14:18 | LQ_CLOSE |
36,801,729 | php how to save the day , month and year enter by user in variables to show value in database | <p>User enter the date , month and year and then press a button to show him the value of database based on the day he picked but I do not know how to save the day , month and year in $d , $m and $y variables</p>
<pre><code><style>
.button {border-radius: 8px;}
.button1 {font-size: 20px;}
</style>
<form>
اليوم : <input id="txtDay" type="text" placeholder="DD" />
الشهر : <input id="txtMonth" type="text" placeholder="MM" />
السنة : <input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="daily()">إظهار الإستهلاك اليومي</button>
</form>
<script>// <![CDATA[
// to show the right value from database
function daily() {
$current_user=get_current_user_id();// to fetch the right data for the right user
// takes the values entered by the user
global $wpdb;
$d=???????????//define variable to store the day enter by user
$m=???????????//define variable to store the month enter by user
$y=???????????//define variable to store the year enter by user
$daily_amount= $wpdb->get_var("SELECT daily_amount FROM arduino_period_use where ID=$current_user and day=$d and month=$m and year=$y ");
print_r($daily_amount);
}
// ]]></script
</code></pre>
| <php><database><wordpress> | 2016-04-22 19:17:55 | LQ_CLOSE |
36,801,910 | Formatting Joda Time LocalDate to MMddyyyy | <p>I am attempting to format a desired joda time LocalDate type to a mmddyyy format and I am running into trouble and not sure how to proceed. I've tried a couple different things so far and had no luck.</p>
<p>So I pretty much want to take a date like 04-15-2016 and get a LocalDate type from it in format, 04152016, but it still needs to be in the LocalDate format, not a string.</p>
<pre><code>DateTimeFormatter dtf = DateTimeFormat.forPattern("MMddyyyy");
LocalDate currentDate = LocalDate.parse("04152016", dtf);
System.out.println(currentDate);
</code></pre>
<p>The date comes out as 2016-04-15. If anyone could help me I would greatly appreciate it. Perhaps I am missing something fundamental when it comes to the Joda Time library.</p>
<p>THank you.</p>
| <java><jodatime> | 2016-04-22 19:30:48 | LQ_CLOSE |
36,803,752 | Replace values in json string | I want to replace all string values in below json string to empty string, true to false, and 1 to 0 in square brackets using JavaScipt.
Addition informatio: json string is placed in a string type variable.
NOTE: properties are dynamic. Meaning sometimes I could have MobilePhone and there will be a case that this property will be missing. So referencing the property name is not an option.
My JSON string:
{"MobilePhone":true,"ToDeleteIndex":1,"BusinessPhone":true,"ApplicantType":"HOLDER","Title":"Mr","FirstName":"Andrew","RemoveApplicant":[1,null]}
Expected results:
{"MobilePhone":false,"ToDeleteIndex":1,"BusinessPhone":false,"ApplicantType":"","Title":"","FirstName":"","RemoveApplicant":[0,null]} | <javascript><json> | 2016-04-22 21:42:18 | LQ_EDIT |
36,804,103 | How to change label text by the value of Progress View | <p>I'm trying to make an app that, when the progress bar comes 10%, 20%, 30% etc... shows an different text on a label. Can you help me on the code?</p>
| <ios><swift2> | 2016-04-22 22:13:12 | LQ_CLOSE |
36,805,406 | How to find unique identifier for an android device? | <p>Sorry if the title is not adequate, but I couldn't think of what else to call it. Anyway, Iv'e been searching how to find a particular android id but when I search "device ID android" or "android ID android", most solutions lead me to the ANDROID_ID which is "A 64-bit number (as a hex string) that is randomly generated when the user first sets up the device". </p>
<p>I am trying to find another type of device ID (which I'm pretty sure is unique and doesn't change) which looks similar to this: android:36e32805-d44a-20fd-72dd-dc1366ec8a71.</p>
<p>Any help with finding this ID would be greatly appreciated!</p>
<p>Thanks!</p>
| <android><unique> | 2016-04-23 01:00:15 | LQ_CLOSE |
36,805,418 | thread.sleep not doing what is supposed to | <p>So, the program is for school and i am having some problems, the basic premise is to have to user choose shape, size and colour, then draw the shape or animate it to move across the screen. </p>
<p>My programs works fine without the thread.sleep (it moves across the screen instantly). When i added the thread.sleep it was not working and waited 10 seconds before immediately moving to the end. </p>
<p>After testing around, it seems to have some correlation with the for loop it was in as when the for loop was to 1000 it waited 10 seconds then moved 1000 spaces instantly but when the for loop was 100 it only took one second to move 100 spaces instantly.</p>
<p>My understanding was that it should just wait 10 milliseconds before going into the for loop again.</p>
<pre><code>import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AppletAssignemntIsFucked extends Applet
implements ActionListener
{
int colourChoice;
int shapeChoice;
int location;
int x, y;
TextField height = new TextField ("00");
TextField width = new TextField ("00");
boolean animating = false;
//declare the two types of checkboxes
CheckboxGroup shape, colour;
//declare all the shape checkboxes
Checkbox buttonSquare, buttonCircle, buttonRectangle, buttonOval;
//declare all the colour checkboxes
Checkbox buttonRed, buttonBlue, buttonGreen, buttonYellow;
Button buttonDraw, buttonAnimate, buttonReset;
public void init ()
{
setBackground (Color.lightGray);
shape = new CheckboxGroup ();
colour = new CheckboxGroup ();
buttonCircle = new Checkbox ("Circle", shape, true);
add (buttonCircle);
buttonSquare = new Checkbox ("Square", shape, false);
add (buttonSquare);
buttonRectangle = new Checkbox ("Rectangle", shape, false);
add (buttonRectangle);
buttonOval = new Checkbox ("Oval", shape, false);
add (buttonOval);
buttonRed = new Checkbox ("Red", colour, true);
add (buttonRed);
buttonBlue = new Checkbox ("Blue", colour, false);
add (buttonBlue);
buttonGreen = new Checkbox ("Green", colour, false);
add (buttonGreen);
buttonYellow = new Checkbox ("Yellow", colour, false);
add (buttonYellow);
buttonDraw = new Button ("draw");
buttonDraw.addActionListener (this);
add (buttonDraw);
buttonAnimate = new Button ("animate");
buttonAnimate.addActionListener (this);
add (buttonAnimate);
buttonReset = new Button ("reset");
buttonReset.addActionListener (this);
add (buttonReset);
add (height);
add (width);
}
public void paint (Graphics g)
{
switch (colourChoice)
{
case 1:
g.setColor (Color.red);
break;
case 2:
g.setColor (Color.green);
break;
case 3:
g.setColor (Color.yellow);
break;
case 4:
g.setColor (Color.blue);
break;
}
switch (shapeChoice)
{
case 1:
g.fillOval (location, 80, x, x);
break;
case 2:
g.fillRect (location, 80, x, x);
break;
case 3:
g.fillRect (location, 80, x, y);
break;
case 4:
g.fillOval (location, 80, x, y);
break;
}
}
public void actionPerformed (ActionEvent evt)
{
y = Integer.parseInt (height.getText ());
x = Integer.parseInt (width.getText ());
//set the colour
if (evt.getSource () == buttonAnimate)
{
for (int i = 0 ; i < 1000 ; i++)
{
try
{
Thread.sleep (10);
}
catch (InterruptedException ex)
{
Thread.currentThread ().interrupt ();
}
location += 1;
repaint ();
}
}
if (evt.getSource () == buttonReset)
{
location = 10;
repaint ();
}
if (evt.getSource () == buttonDraw)
{
if (buttonRed.getState () == true)
{
colourChoice = 1;
}
else if (buttonGreen.getState () == true)
{
colourChoice = 2;
}
else if (buttonYellow.getState () == true)
{
colourChoice = 3;
}
else if (buttonBlue.getState () == true)
{
colourChoice = 4;
}
//set the shape
if (buttonCircle.getState () == true)
{
shapeChoice = 1;
}
else if (buttonSquare.getState () == true)
{
shapeChoice = 2;
}
else if (buttonRectangle.getState () == true)
{
shapeChoice = 3;
}
else if (buttonOval.getState () == true)
{
shapeChoice = 4;
}
repaint ();
}
}
</code></pre>
<p>}</p>
| <java><applet><thread-sleep><jradiobutton> | 2016-04-23 01:01:50 | LQ_CLOSE |
36,805,459 | Java retreive and compare two dates plus time | So basically I want to ask the user for a date and time of departure then ask the user for time of arrival to compare and get duration. I was wondering what kind of method of input would be good for this input. I was thinking either a multi drop down box or some kind of scrolling bar type deal. Can any one give me and suggestion on a good input method and what it is called? Thank you | <java> | 2016-04-23 01:08:41 | LQ_EDIT |
36,805,757 | What's the difference between ArrayList<Integer> a[]; and ArrayList<Integer> a;? | <p>What is the difference in adding the [] to an ArrayList <code>a</code>, as opposed to initializing like ArrayList <code>b</code>? Is there any purpose for one way or the other?</p>
<pre><code>ArrayList<Integer> a[];
ArrayList<Integer> b;
</code></pre>
| <java> | 2016-04-23 01:56:47 | LQ_CLOSE |
36,806,671 | Include and compile cpp header file from c | I have a cpp file and its header file. I need to include this cpp header file in a c code and use the functions in it.
When the cpp.h file is compiled through main.c, compilation fails because of the cpp linkage.
On using the macro __cplusplus stream and string are not resolved, is there some way to compile the cpp.h file through and execute.
I have given a outline of my code only.
Kindly help me out in this. Thanks
**cpp header file cpp.h**
struct s1
{
string a;
string b;
};
typedef struct s1 s2;
class c1
{
public:
void fun1(s2 &s3);
private:
fun2(std::string &x,const char *y);
};
**cpp file cpp.cpp**
c1::fun1(s2 &s3)
{
fstream file;
}
c1::fun2(std::string &x,const char *y)
{
}
**c file main.c**
#include "cpp.h"
void main()
{
c1 c2;
s1 structobj;
c2.fun1(&structobj);
printf("\n value of a in struct %s",structobj.a);
}
| <c++><c> | 2016-04-23 04:34:04 | LQ_EDIT |
36,806,960 | Deal with segmentation fault | <p>I am trying to solve a CodeChef problem. Whenever I run it I get a segmentation fault. This is the link to the problem: <a href="https://www.codechef.com/problems/CHN09" rel="nofollow">Malvika is peculiar about color of balloons</a></p>
<p>Here is my code :</p>
<pre><code>#include<iostream>
#include<cstring>
#include<algorithm>
int main(){
std::string balloonColors;
size_t numberOfAmber;
size_t numberOfBrass;
int t;
int results[t];
std::cin >> t;
for (int i = 0; i < t; i++){
int result = 0;
std::cin >> balloonColors;
numberOfAmber = std::count(balloonColors.begin(), balloonColors.end(), 'a');
numberOfBrass = std::count(balloonColors.begin(), balloonColors.end(), 'b');
if (numberOfAmber == 0 || numberOfBrass == 0){
result = 0;
}
if (numberOfAmber <= numberOfBrass){
result = (int)numberOfAmber;
}
else {
result = (int)numberOfBrass;
}
results[i] = result;
}
for (int x = 0; x < t; x++){
std::cout << results[x] << std::endl;
}
}
</code></pre>
| <c++><segmentation-fault> | 2016-04-23 05:18:48 | LQ_CLOSE |
36,807,721 | Attempt to invoke virtual method when displaying TOAST? | <p>when you click a button in my activity it starts/displays a <code>DatePickerDialog</code>. When the user selects a date and clicks "ok" i want to run an <code>AsyncTask</code> in the original class (the activity where the button was clicked). Everything works but i want to display to the user a TOAST when the AsyncTask is finished but it keep on getting an error when doing so.</p>
<p>Heres my code:</p>
<p>Button method in the BuyerHomePage.java</p>
<pre><code> public void MeetingCreator(){
CalenderImageButton = (ImageButton)findViewById(R.id.CalenderImageButton);
CalenderImageButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
}
);
}
</code></pre>
<p>DatePickerFragment.java code</p>
<pre><code> public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static String formattedDate;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = sdf.format(c.getTime());
BuyerHomePage Meeting = new BuyerHomePage();
Meeting.new MeetingSender().execute();
}
}
</code></pre>
<p>BuyerHomePage.java (post method in the AsyncTask)</p>
<pre><code>@Override
protected void onPostExecute (String result){
if (result.equals("email sent")) {
//This is where i get the error
Toast.makeText(BuyerHomePage.this, "Email sent!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(BuyerHomePage.this, "Can't send email", Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p>Error Logs:</p>
<pre><code>04-23 02:25:31.631 22071-22071/com.wilsapp.wilsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wilsapp.wilsapp, PID: 22071
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.widget.Toast.<init>(Toast.java:102)
at android.widget.Toast.makeText(Toast.java:259)
at com.wilsapp.wilsapp.BuyerHomePage$MeetingSender.onPostExecute(BuyerHomePage.java:930)
at com.wilsapp.wilsapp.BuyerHomePage$MeetingSender.onPostExecute(BuyerHomePage.java:836)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code></pre>
<p>if there's any confusion or i need to explain anything please comment! Thank you!</p>
| <java><android><android-fragments><android-asynctask><android-dialogfragment> | 2016-04-23 07:00:39 | LQ_CLOSE |
36,808,330 | ReferenceError: $ is not defined or Uncaught ReferenceError: $ is not defined | <p>I am trying to call a bootstrap model in my page. but it throws an error in console output as <strong>ReferenceError: $ is not defined</strong>. Code for the reference as below :-</p>
<pre><code><head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="<?php echo base_url(); ?>assets/css/style.css" rel="stylesheet" type="text/css"/>
<link href="<?php echo base_url(); ?>assets/css/bootstrap.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="text-center">
<button class="btn btn-danger" id="delete" > Delete ID</button>
</div>
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Delete
</div>
<div class="modal-body">Are you sure you want to Delete contact list ?</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a id="sureDelete"><button class="btn btn-danger success">Delete</button></a>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).on('click', '#delete', function () {
$('#confirm-delete').modal('show');});
</script>
<script src="<?php echo base_url(); ?>assets/js/jquery.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script>
</body>
</code></pre>
| <javascript><jquery><twitter-bootstrap> | 2016-04-23 08:10:44 | LQ_CLOSE |
36,809,036 | How to use VBA to write a macros that will format all the cells in the workbook? | I have recently started to use VBA Excel for financial modeling purposes and already found that it can optimize my work process.
Right now I try to develop a macro that will help me to automatically format all the cells in the workbook, and I have no idea how to write such macro.
What I want to do is the following - I have 3 types of numbers:
1. Hard Numbers
2. Numbers that are internal links - they are values from other sheets of the workbook.
3. Numbers that are external links - they are values from other workbooks.
Is it possible to write a macro that will format cells depending on type of number (mentioned-above)?
Thanks
| <vba><excel> | 2016-04-23 09:32:52 | LQ_EDIT |
36,809,080 | Find all possible latitudes/longitudes in 500 meter circle radius | <p>I have a google map in my android application. and I have drawn a circle on specific latitude and longitude on the map, and the circle's radius is 500 meters. I want to find the maximum and minimum latitudes and longitudes in that circle, how to do this?</p>
<p>to explain my idea further, see the picture below:</p>
<p><a href="http://i.stack.imgur.com/uE6fR.jpg" rel="nofollow">The picture</a></p>
<p>I want to calculate all of the possible latitudes and longitudes on that red circle, can someone please tell me how to do it?</p>
| <android><google-maps> | 2016-04-23 09:37:42 | LQ_CLOSE |
36,810,922 | How can I run time in C++? | I'm learning C++ and I got this time program question.So what this program has got to do is to get time from user and should display time also it must work like a clock. For example when the user gives 20:13:10 it must work on it like after 60 seconds if the user asks for time it must give 20:14:10, how do I make it count in the background while it asks for user for time, I've made a basic program and can you help how do I make it the way it is asked for?
program is down there:
//om! god is great, greatest
#include <iostream>
#include<conio.h>
using namespace std;
class Time{
int hour, minute, second;
public:
void SetTime(int hour1=0, int minute1=0, int second1=0){
hour = hour1;
minute=minute1;
second=second1;
cout<<"set time working";
}
void display(){
cout<<"hour | minute | second"<<endl;
cout<<hour<<" "<<minute<<" "<<second;
}
};
int main(){
Time time;
//char om;
int hour1, minute1,second1;
cout<<"enter the hour,minute,second: ";
cin>>hour1;
cin>>minute1;
cin>>second1;
time.SetTime(hour1,minute1,second1);
cout<<"\n The current time?";
time.display();
return 0;
} | <c++><time> | 2016-04-23 12:37:52 | LQ_EDIT |
36,811,448 | How to Get Windows 10 Insider Preview Build Faster? | <p>I have turned on the <em>fast</em> way of getting insider preview builds.
However, it is too slow.
I want the build <em>14316</em> or newer. </p>
<hr>
<p>How can you get Windows 10 insider preview builds faster? </p>
| <windows-10><auto-update> | 2016-04-23 13:26:27 | LQ_CLOSE |
36,811,538 | Cython interfaced with C++: segmetation fault for large arrays | I am transferring my code from Python/C interfaced using ctypes to Python/C++ interfaced using Cython. The new interface will give me an easier to maintain code, because I can exploit all the C++ features and need relatively few lines of interface-code.
The interfaced code works perfectly with small arrays. However it encounters a *segmentation fault* when using large arrays. I have been wrapping my head around this problem, but have not gotten any closer to a solution. I have included a minimal example in which the segmentation fault occurs. Please note that it consistently occurs on Linux and Mac, and also valgrind did not give insights. Also note that the exact same example in pure C++ does work without problems.
The example contains a Sparse matrix class (of the compressed row format) in C++. An interface is created in Cython. As a result the class can be used from Python.
# C++ side
``sparse.h``
#ifndef SPARSE_H
#define SPARSE_H
#include <iostream>
#include <cstdio>
using namespace std;
class Sparse {
public:
double* data;
int* row_ptr;
int* col_ind;
int* shape;
int nnz;
Sparse();
~Sparse();
Sparse(int* shape, int nnz, double* data, int* row_ptr, int* col_ind);
void view(void);
};
#endif
``sparse.cpp``
#include "sparse.h"
// =============================================================================
Sparse::Sparse()
{
data = NULL;
row_ptr = NULL;
col_ind = NULL;
shape = NULL;
nnz = 0 ;
}
// =============================================================================
Sparse::~Sparse() {}
// =============================================================================
Sparse::Sparse(int* Shape, int NNZ, double* Data, int* Row_ptr, int* Col_ind)
{
shape = Shape ;
nnz = NNZ ;
data = Data ;
row_ptr = Row_ptr;
col_ind = Col_ind;
}
// =============================================================================
void Sparse::view(void)
{
if ( row_ptr==NULL || col_ind==NULL || data==NULL || shape==NULL ) {
cout << "NULL-pointer found" << endl;
return;
}
int i,j;
for ( i=0 ; i<shape[0] ; i++ )
for ( j=row_ptr[i] ; j<row_ptr[i+1] ; j++ )
printf("(%3d,%3d) %4.1f\n",i,col_ind[j],data[j]);
}
// =============================================================================
# Cython interface
``csparse.pyx``
import numpy as np
cimport numpy as np
# ==============================================================================
cdef extern from "sparse.h":
cdef cppclass Sparse:
Sparse(int*, int, double*, int*, int*) except +
double* data
int* row_ptr
int* col_ind
int* shape
int nnz
void view()
# ==============================================================================
cdef class PySparse:
# ----------------------------------------------------------------------------
cdef Sparse *ptr
# ----------------------------------------------------------------------------
def __init__(self,**kwargs):
pass
def __cinit__(self,**kwargs):
cdef np.ndarray[np.int32_t , ndim=1, mode="c"] shape, col_ind, row_ptr
cdef np.ndarray[np.float64_t, ndim=1, mode="c"] data
shape = np.array(kwargs['shape' ],dtype='int32' )
data = kwargs['data' ].astype(np.float64)
row_ptr = kwargs['row_ptr'].astype(np.int32 )
col_ind = kwargs['col_ind'].astype(np.int32 )
self.ptr = new Sparse(
<int*> shape.data if shape is not None else NULL,
data.shape[0],
<double*> data .data if data is not None else NULL,
<int*> row_ptr.data if row_ptr is not None else NULL,
<int*> col_ind.data if col_ind is not None else NULL,
)
# ----------------------------------------------------------------------------
def __dealloc__(self):
del self.ptr
# ----------------------------------------------------------------------------
def view(self):
self.ptr.view()
# ----------------------------------------------------------------------------
``setup.py``
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(ext_modules = cythonize(Extension(
"csparse",
sources=["csparse.pyx", "sparse.cpp"],
language="c++",
)))
# Python side
import numpy as np
import csparse
N = 5000
matrix = csparse.PySparse(
shape = np.array([N,N],dtype='int32'),
data = np.random.rand(N*N),
row_ptr = np.arange(0,N*N+1,N ,dtype='int32'),
col_ind = np.tile(np.arange(0,N,dtype='int32'),N),
)
matrix.view() # --> segmentation fault
| <python><c++><arrays><numpy><cython> | 2016-04-23 13:35:45 | LQ_EDIT |
36,812,552 | check internet on application launch in android | found a code that will check internet connectivity [here][1]
[1]: http://stackoverflow.com/questions/6493517/detect-if-android-device-has-internet-connection/25816086#25816086
but I do not have any idea how to implement or call this class or method as I am still studying android programming using android studio.
Please see my code below and kindly let me know how to arrange it in a way that it will fire on application launch plus including the toast message stating that it is connected or not..
package com.example.enan.checkinternetconnection;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "";
private static final String LOG_TAG = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
| <java><android> | 2016-04-23 15:14:24 | LQ_EDIT |
36,812,664 | can someone help me I can't get rid of that typeerror:'tuple' object is not callable | <p><a href="http://i.stack.imgur.com/o7muZ.png" rel="nofollow">screenshot</a></p>
<p>I don't know how to have the right thing, like whats descriped in the picture
thank you</p>
| <python> | 2016-04-23 15:23:47 | LQ_CLOSE |
36,812,933 | I have 2 CTE.When i try to join them i get an error message "ORA-01789: ".how can i merge the 2 CTE.Is there any other way to get the desired result | WITH IMPORT_CTE
AS ((select A.*
FROM IMPORT_REGISTRY_ERROR_LOG_1 A
INNER JOIN (select distinct POD_ID,CONFLICTED_POD_ID,ERROR_CODE
FROM IMPORT_REGISTRY_ERROR_LOG_1
GROUP BY POD_ID,CONFLICTED_POD_ID,ERROR_CODE
HAVING COUNT(*) > 1) B
on A.POD_ID = B.POD_ID AND A.CONFLICTED_POD_ID = B.CONFLICTED_POD_ID AND A.ERROR_CODE = B.ERROR_CODE ) order by a.pod_id desc)
select t1.*
from IMPORT_CTE t1
where t1.insert_date =(select max(t2.insert_date)
from IMPORT_CTE t2
where t2.POD_ID =t1.POD_ID)
WITH IMPORT_CTE1
AS ((select A.*
FROM IMPORT_REGISTRY_ERROR_LOG_1 A
INNER JOIN (select distinct POD_ID,CONFLICTED_POD_ID,ERROR_CODE
FROM IMPORT_REGISTRY_ERROR_LOG_1
GROUP BY POD_ID,CONFLICTED_POD_ID,ERROR_CODE
HAVING COUNT(*) > 1) B
on A.POD_ID = B.POD_ID AND A.CONFLICTED_POD_ID = B.CONFLICTED_POD_ID AND A.ERROR_CODE = B.ERROR_CODE ) order by a.pod_id desc)
select t1.insert_date
from IMPORT_CTE1 t1
where t1.insert_date =(select min(t2.insert_date)
from IMPORT_CTE1 t2
where t2.POD_ID =t1.POD_ID)
| <oracle><join> | 2016-04-23 15:48:12 | LQ_EDIT |
36,813,047 | non standard characters cause program to end | I learning python for data mining and I have a text file that contains a list of world cities and their coordinates. In my code, I am trying to find the coordinates of a list of cities. All works well until there is a name with non-standard characters. I was expecting that the program will skip that city name and move to the next, but it terminates. How to make the program skip names that it cannot find and continue to the next?
lst = ['Paris', 'London', 'Helsinki', 'Amsterdam', 'Sant Julià de Lòria', 'New York', 'Dublin']
source = 'world.txt'
fh = open(source)
n = 0
for line in fh:
line.rstrip()
if lst[n] not in line:
continue
else:
co = line.split(',')
print lst[n], 'Lat: ', co[5], 'Long: ', co[6]
if n < (len(lst)-1):
n = n + 1
else:
break
The outcome of this run is:
>>>
Paris Lat: 33.180704 Long: 67.470836
London Lat: -11.758217 Long: 17.084013
Helsinki Lat: 60.175556 Long: 24.934167
Amsterdam Lat: 6.25 Long: -57.5166667
>>> | <python><python-2.7><text-mining> | 2016-04-23 15:56:53 | LQ_EDIT |
36,813,503 | clarification using strdup() or strcpy() | <p>i have a problem
this method works fine, it returns a struct with the right NaME value</p>
<pre><code>prodotti creaProdotto(char *name, float price, prodotti next){
prodotti p = malloc(sizeof(prodotti));
p->name = malloc(30 * sizeof(char));
p->name = strdup( name);
p->price = price;
p->next = next;
return p;
}
</code></pre>
<p>else this do not works,</p>
<pre><code>prodotti creaProdotto(char *name, float price, prodotti next){
prodotti p = malloc(sizeof(prodotti));
p->name = malloc(30 * sizeof(char));
strcpy(p->name, name);
p->price = price;
p->next = next;
return p;
}
</code></pre>
<p>the problem in the second is: name does not contains the right value,
please explain ne why.</p>
| <c> | 2016-04-23 16:38:43 | LQ_CLOSE |
36,814,220 | assign a default value to a variable and change into database | i have a method
getlisting(string url,int ID)
i am passing this parameter ID to another function in another class
Controller __cc = new Controller();
int Status = 1;
__cc.UpdatePaging(ID, Status);
i am passing this to update function and want to assign a default value of zero to ID and 1 to status and then return it and make changes in database,
public void UpdatePaging(int ID,int Status)
{
if (ID != null)
{
ID = 0;
}
else
{
ID = 0;
}
SqlCommand cmd = new SqlCommand("UPDATE Paging SET Status='1' WHERE ID = @ID", obj.openConnection());
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@Status", SqlDbType.Int).Value = 1;
cmd.Parameters.AddWithValue("@ID", SqlDbType.Int).Value = ID;
cmd.ExecuteNonQuery();
}
but i can't do it, is there something wrong with my code? or tell me how to assign a 0 value to int and update it in Database, whenever i get any value from getlisting method it should be assigned zero and update in DB any help? | <c#><sql><oop> | 2016-04-23 17:39:28 | LQ_EDIT |
36,814,550 | What counts as a transaction on the free API license? | <p>I'm working on a book for Manning and want to use Alchemy News API as part of one of the examples. I have a free license which says it allows for 1,000 transactions per day. Does that mean 1,000 queries or something else? I hit the limit today way earlier than I expected to, at significantly less than 1,000 queries. </p>
| <alchemyapi> | 2016-04-23 18:08:03 | LQ_CLOSE |
36,816,701 | how to translate this PHP code to PDO form , brcause i am getting undefined function in PHP 7 (using XAMPP)? | this is my PHP file, but i am getting fatal error : undefined function mysql_connect, i have searched it and it looks like i have to use PDO instead of mysql_connect on PHP 7 , and i dont know how so i need help please, i want this code as PDO, thanks for your time
<?php
// connection , which gives fatal exception : undefined function..
$con = mysql_connect("localhost",'root','');
//error handling
if (!$con)
{
die("Could not connected".mysql_error()); else
{
//select the DB name in PhpMyAdmin
mysql_select_db("tm-mobile",$con);
//Vlidation
if (!empty($_POST['owner_name']) && !empty($_POST['owner_email']))
{
$owner_id=$_POST['owner_id'];
$owner_name=$_POST['owner_name'];
$owner_email=$_POST['owner_email'];
$owner_password=$_POST['owner_password'];
$market_name=$_POST['market_name'];
//SQL statement
$sql = "UPDATE owner_table SET owner_id = '$owner_id',owner_name =
'$owner_name' , owner_email = '$owner_email', owner_password =
'$owner_password' , market_name = '$market_name' ";
$re = mysql_query ($sql,$con);
//Close the Connection
mysql_close();
}
}
?> | <php> | 2016-04-23 21:33:22 | LQ_EDIT |
36,816,926 | C# Parent and Child class - picking the child out of a parent class | <p>Does anyone know, why this underlines(error) Suit (Child class of Stock)in the part that says "stock is Suit"?</p>
<pre><code>//Picking Suit out of the Stock
public System.Collections.ArrayList Suit()
{
System.Collections.ArrayList array = new System.Collections.ArrayList(); //looping through Persons array
foreach (Stock stock in allStock)//using code snippets
{
if (stock is Suit) //if it is a customer, display value, if not, return to the array list
{
array.Add(stock);
}
}
return array;
}
</code></pre>
| <c#> | 2016-04-23 21:57:04 | LQ_CLOSE |
36,817,565 | Python: IndentationError: unexpected indent | <p>Been pulling what hair I have left over this :-(</p>
<pre><code>if tIn.find("play again") != -1:
tn.write("yes\n")
print tn.read_until("WordsWeNeverSee",1.0)
tn.write("O\n")
</code></pre>
<p>I get the error</p>
<pre><code>root@kali:~# ./TTT.py
File "./TTT.py", line 79
print tn.read_until("WordsWeNeverSee",1.0)
^
IndentationError: unexpected indent
</code></pre>
<p>Any idea how to resolve?</p>
| <python> | 2016-04-23 23:21:21 | LQ_CLOSE |
36,817,996 | mysql workbench trying to produce a set of results that i can't figure out | I need the query to produce this:
person_idlast_name first_name region_id region name year month amount_sold
1 barnum phineas 1 maricopa 2016 1 800000
1 barnum phineas 1 maricopa 2016 2 850000
1 barnum phineas 1 maricopa 2016 3 990000
2 loman willy 2 pima 2016 1 425000
2 loman willy 2 pima 2016 2 440000
2 loman willy 2 pima 2016 3 450000
2 loman willy 3 pinal 2016 1 200000
2 loman willy 3 pinal 2016 2 210000
2 loman willy 3 pinal 2016 3 220000
2 loman willy 4 santa cruz 2016 1 50000
2 loman willy 4 santa cruz 2016 2 52000
2 loman willy 4 santa cruz 2016 3 55000
3 kay mary 5 cochise 2016 1 40000
3 kay mary 5 cochise 2016 2 41000
3 kay mary 5 cochise 2016 3 42000
3 kay mary 6 gila 2016 1 3000
3 kay mary 6 gila 2016 2 31000
3 kay mary 6 gila 2016 3 32000
3 kay mary 7 graham 2016 1 20000
3 kay mary 7 graham 2016 2 21000
3 kay mary 7 graham 2016 3 22000
4 lillian vernon NULL NULL NULL NULL NULL checksum 4,994,000
I have this code written:
select person_id, last_name, first_name,
sales_region.Region_id, name AS 'Region Name',
year, month, amount_sold
from sales
join sales_people
on person_id = person_id
join sales_region
on sales_region.region_id = sales_region.region_id
group by month asc, region_id, person_id
order by person_id, region_id, month asc
;
i do not get a check sum and the last persons items do not come in null.
| <mysql><null> | 2016-04-24 00:34:28 | LQ_EDIT |
36,818,211 | Functions in Haskell (specifically swap function) | <p>Alright I know that this question has been asked before, but no answers have compiled. I've researched Haskell function tutorials to no avail. Basically I just want to know how to declare a function in Haskell and how to call it. Most of the tutorials I've found are answering how to do this with ghci, which I understand should be basically the same thing, but I need to write this in a .hs file and compile with ghc for a school assignment. Basically I'd like something like this:</p>
<pre><code>main = do
let list = [1,2,3,4]
-- declare swap
swap (list !! 0) (list !!2)
-- Or
swap 1 2 list
</code></pre>
<p>I'm using ghc version 7.4.1 which I understand isn't the latest version, but it's not a terribly old version either, so it shouldn't make a difference here, should it? Any and all help would be greatly appreciated. Thank you.</p>
| <haskell><functional-programming><ghc> | 2016-04-24 01:11:17 | LQ_CLOSE |
36,818,634 | PHP insert ' into SQL | <pre><code>$type_of_poker = "hold'em no limit";
$sql = "INSERT INTO hands (type_of_poker) VALUES ('$type_of_poker')";
</code></pre>
<p>Im trying to put <code>hold'em no limit</code> into a SQL database but it won't let me
use <code>'</code> i cant upload <code>holdem no limit</code> for a long list resones that have to do
with the rest of my code.</p>
| <php><mysql> | 2016-04-24 02:23:42 | LQ_CLOSE |
36,818,857 | how to auto create new app in Google Play by API | <p><strong>Hi</strong>,</p>
<p>I have to build many app from one source frequently.</p>
<p>So i want to create new app auto in Google Play by API for convenient, and after that i will use Supply mobile in <a href="https://fastlane.tools/" rel="nofollow">Fastlane</a> to upload metadata.</p>
<p>Anyone can help me solve this case :)
Thanks for your investigating!</p>
| <android><fastlane> | 2016-04-24 03:08:50 | LQ_CLOSE |
36,819,395 | How to add and retrieve from array list? | <p>I'm creating a mock banking program and want to use arraylists to keep track of things like first, last name, account balance, etc. then I want to display these values later with print statements. How do I do this?</p>
| <java> | 2016-04-24 04:51:58 | LQ_CLOSE |
36,819,816 | iOS - Objective C, Sort NSArray of NSDictionary(s) via key name | <p>How to sort NSArray of dictionaries on the basis of NSDictionary's key name.</p>
<p>lets say, JSON format of NSArray is</p>
<pre><code>[
{
"keyName" : "C",
"value" : "0.1"
},
{
"keyName" : "A",
"value" : "1.1"
},
{
"keyName" : "B",
"value" : "2.1"
}
]
</code></pre>
| <ios><objective-c><sorting><nsarray><nsdictionary> | 2016-04-24 05:58:56 | LQ_CLOSE |
36,819,951 | What is wrong with my Syntax here? (SQLite) | <p>Well I make some changes in my Table and now is showing me this error. I am try to Debug but with no luck. Any idea?</p>
<p>"android.database.sqlite.SQLiteException: no such table: tablename (code 1): , while compiling: select * from tablename"</p>
<pre><code> import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONT_TABLE_NAME = "tablename";
public static final String CONT_COLUMN_ID = "id";
public static final String CONT_COLUMN_CONDUCTIVITY = "conductivity";
public static final String CONT_COLUMN_MOISTURE = "moisture";
public static final String CONT_COLUMN_OXYGEN = "oxygen";
public static final String CONT_COLUMN_PH = "ph";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table tablename " +
"(id integer primary key, conductivity text,ph text,oxygen text, moisture text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS tablename");
onCreate(db);
}
public boolean insertContact (String conductivity, String ph, String oxygen, String moisture)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("conductivity", conductivity);
contentValues.put("ph", ph);
contentValues.put("oxygen", oxygen);
contentValues.put("moisture", moisture);
db.insert("tablename", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from tablename where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONT_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String conductivity, String ph, String oxygen, String moisture)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("conductivity", conductivity);
contentValues.put("ph", ph);
contentValues.put("oxygen", oxygen);
contentValues.put("moisture", moisture);
db.update("tablename", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("tablename",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from tablename", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONT_COLUMN_CONDUCTIVITY)));
res.moveToNext();
}
return array_list;
}
}
</code></pre>
| <java><android><sqlite> | 2016-04-24 06:19:50 | LQ_CLOSE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.