lundi 31 août 2015

Firefox is blocking insecure content

I am running a UI automation script on a https site. I get 'Firefox is blocking insecure content" warning every-time on a particular page. for now i am manually disabling protection from options but, how to set protection disabled permanently so that my scripts won't break when i run them for regression?

enter image description here



via Chebli Mohamed

SQL query to make distinct lines with case being used

Here is what my data looks like on the table I am querying

Table 1

ITEM     SEQUENCE     CODE
Item1       1            A 
Item1       2            B
Item2       1            B
Item2       2            C
Item2       3            D

My current Query looks like

  Select Distinct Table1.ITEM, 
  case when Table1.SEQUENCE = '1' Then Table2.DSC end As FirstDSC,
  Case When Table1.SEQUENCE = '2' then Table2.DSC End As SecondDSC,
  Case When Table1.SEQUENCE = '3' Then Table2.DSC End As ThirdDSC
    From Table1
    Join Table2 on Table2.Code = Table1.Code
    Where Table1.Item In (Subquery here to find distinct values that Item can be)

It currently returns the data looking like

ITEM  FIRSTDSC SECONDDSC THIRDDSC
Item1   DSC-A     NULL      NULL
Item1   NULL     DSC-B      NULL 

I was wondering how to make the data return looking like

ITEM FIRSTDSC  SECONDDSC  THIRDDSC
Item1  DSC-A      DSC-B       NULL
Item2  DSC-B      DSC-C       DSC-D

Is there a good way to do this or am I going in the completely wrong direction with my query currently?



via Chebli Mohamed

On mouseout animate line to disappear

Right now, I've got it to draw a line when you mouseon but I want it so that when you mouseout the line disappears left to right.

http://ift.tt/1IA9dl9

$( "#name" ).mouseover(function() { 

$('.slider').animate({
    width: $('#name').width()
}, 1000);

});



via Chebli Mohamed

Access to GitHub only possible with

I can successfully add files to a local repository and push it to github using github desktop. When I try to commit to github using the git commandline or GitExtensions I get an error

"C:\Program Files\Git\bin\git.exe" push --recurse-submodules=check --progress "origin" refs/heads/master:refs/heads/master
remote: Invalid username or password.
fatal: Authentication failed for 'http://ift.tt/1EtNNuM'
Done

I dont have 2fa enabled. What is github desktop doing different that it can login?



via Chebli Mohamed

Are there Powershell cmdlets that install and remove Windows drivers?

Note: For this question, when I refer to "Windows drivers" I mean .inf and associated files which can otherwise be installed by right-clicking the .inf and clicking "Install" in Windows Explorer. I do not mean any kind of setup.exe-style executable which might install a driver.


There exists the following:

I have not, however, found a corresponding Powershell Cmdlet that supports installing and uninstalling drivers on the running system. I'm sure I could wrap dpinst.exe in some powershell, but I'd like to avoid mapping command line parameters and parsing output if a more Powershell-native method exists.

Do Powershell Cmdlets exist that install and uninstall Windows drivers on the running system? Is there some other way to install and uninstall Windows drivers using Powershell that does not involve dpinst.exe?



via Chebli Mohamed

Accessing audio input while loading a project from file://

I wonder to know if it is possible to somehow prevent Chrome from blocking my project audio input because I'm not loading it from a local host but from file://... a.k.a. my HDD. I'm asking about this because I've understood that when the script is non-server but loaded from file:// Chrome automatically blocks it and it can't reach the asking for mic usage permission step. I'm playing around with annyang, so yeah, if someone knows how to enable the described above, please share, as I still have no idea of php, mysqul and others for establishing a local host environment.



via Chebli Mohamed

Which index is needed for a Mongoid order_by and find_by query?

To find the most recently created user named "Jeff",

User.order_by(created_at: :desc)
    .find_by(name: "Jeff")

Which indexes should be created for this query? Would it be 2 indexes, on created_at and name?

Or a compound index on both?



via Chebli Mohamed

Dynamically resize columns based on how many there are in a row

I'm trying to make a responsive column layout that resizes depending on the number of columns.

Link to JsFiddle

<div class="row">
<div class="box half">1/2</div>
<div class="box quarter">1/4</div>
<div class="box quarter">1/4</div>
</div>

<div class="row">
<div class="box half">1/2</div>
<div class="box quarter hidden">1/4</div>
<div class="box quarter">1/4</div>
</div>

So, what I'm trying to do is if I add the class "hidden" to one of the boxes, the other boxes will resize and fill up the row. For example, in the first row we have one column 50% and two columns 25%; If I hide one 25% column, the first column will have 66% and the 2nd one will have 33%.

I have to do this without adding any other classes to html and work in IE8+.



via Chebli Mohamed

Subtraction/dfference between bytes in Java

I'm trying to subtract one byte from another while making sure no overflow happens, but get unexpected results.

In the following code, I expect data2 array to be subtracted from data1 array. However I get low values when I am sure there should be high ones.

    for (int i = 0; i < data1.length; i++) {
        if (data1[i] > data2[i]) {
            dest[i] = (byte) (data1[i] - data2[i]);
        } else {
            dest[i] = 0;
        }
    }

I figured I should make sure data2 byte isn't negative and being added to data1. So I came to:

    for (int i = 0; i < data1.length; i++) {
        if (data1[i] > data2[i]) {
            dest[i] = (byte) (data1[i] & 0xff - data2[i] & 0xff);
        } else {
            dest[i] = 0;
        }
    }

However this also doesn't give the right results.

I hope I'm doing something stupidly wrong here, or my problem resides somewhere else of which I can't figure out where.



via Chebli Mohamed

Check if pointer object created is less than today Parse.com

hey guys i have a table A which has a pointer to Table B. I am trying to query Table A where Table B created At is less than today

Table A (columns)

Name, Table B pointer, ....

Table B CreatedAt

So far I have this

    let query = PFQuery(className:Globals.ParseObjects.ProLeagueWinnings)
    query.fromLocalDatastore()
    query.fromPinWithName("XXX")

    query.includeKey("TableB")

    query.whereKeyExists("TableB")
    query.whereKey("TableB.CreatedAt", lessThanOrEqualTo: NSDate())
    query.findObjectsInBackground().continueWithSuccessBlock {
        (task: BFTask!) -> AnyObject! in

        let leagues = task.result as? [ProLeagueWinnings]
        if (completion != nil){
            if leagues != nil{
                completion!(leagues!)
            }else{
                completion!([])
            }
        }

        return task
    }

But it returns everything.



via Chebli Mohamed

Implementation of method accepting lambda

I'm interested to understand how are implemented LabelFor, EditorFor... methods that accept lambda expressions in MVC.

Lets say I have a class Person and I want to print the name and the value of a property. How must be implemented Label() and Editor() methods?

  class Person
  {
     public int Id { get; set; }
  }

  void Label(Expression<Func<Person, int>> expression)
  {
     //...
  }

  void Editor(Expression<Func<Person, int>> expression)
  {
     //...
  }

  public void Test()
  {
     Person p = new Person
     {
        Id = 42
     };

     Label(x => x.Id );  // print "Id"
     Editor(x => x.Id); // print "42"

  }



via Chebli Mohamed

Panel sliding from the bottom

I want to implement panel, that by default appears from the bottom only by 1/4. And when i tap on this part, or swipe it, it should roll out on full screen.

exactly what i want was implemented in this app

So what i tried already: Making UIView and trying to apply tap and swipe gestures. UIView didn't catch it. But it caught touchesMoved, touchesEnded etc. UITableView. Same. Making UIViewController. Ended without any idea how to handle it to right way.

So any ideas or links are appreciated. Thanks in advance.



via Chebli Mohamed

Finding and replacing strings with certain character patterns in array

I have a pretty large database with some data listed in this format, mixed up with another bunch of words in the keywords column.

BA 093, RJ 342, ES 324, etc.

The characters themselves always vary but the structure remains the same. I would like to change all of the strings that obey this character structure : 2 characters A-Z, space, 3 characters 0-9 to the following:

BA-093, RJ-342, ES-324, etc.

Be mindful that these strings are mixed up with a bunch of other strings, so I need to isolate them before replacing the empty space.

I have written the beginning of the script that picks up all the data and shows it on the browser to find a solution, but I'm unsure on what to do with my if statement to isolate the strings and replace them. And since I'm using explode it is probably turning the data above into two separate arrays each, which further complicates things.

<?php

require 'includes/connect.php';

$pullkeywords = $db->query("SELECT keywords FROM main");

while ($result = $pullkeywords->fetch_object()) {

    $separatekeywords = explode(" ", $result->keywords);
    print_r ($separatekeywords);
    echo "<br />";
}

Any help is appreciated. Thank you in advance.



via Chebli Mohamed

Autocomplete: from pure JS to ReactJS

I am working on an auto-complete, right now I have it in pure JS

here I have this example in JSFiddle

<input type="text" onkeyup="changeInput(this.value)">

<div id="result"></div>

the js part

var people = ['Steven', 'Sean', 'Stefan', 'Sam', 'Nathan'];

function matchPeople(input) {
  var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
  return people.filter(function(person) {
    if (person.match(reg)) {
      return person;
    }
  });
}

function changeInput(val) {
  var autoCompleteResult = matchPeople(val);
  document.getElementById("result").innerHTML = autoCompleteResult;
}

but I need to translate it to ReactJS, and I am not getting good results

let people = ['Steven', 'Sean', 'Stefan', 'Sam', 'Nathan'];

class Login extends Component {

  render () {
    return (
      <Grid>
          <input type="text" onkeyup={this._changeInput(this.value)} />
          <div id="result"></div>
      </Grid>
    );
  }

  _matchPeople = (input) => {
    var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
    return people.filter(function(person) {
      if (person.match(reg)) {
        return person;
      }
    });
  }

  _changeInput = (val) => {
    var autoCompleteResult = this._matchPeople(val);
    document.getElementById("result").innerHTML = autoCompleteResult;
  }  

}

Error in the console:

Uncaught TypeError: Cannot read property 'split' of undefined

what am I missing ?



via Chebli Mohamed

Matching values from different columns, GOOGLE SHEETS

Google sheets,

I have columns a with 5000 rows and column b with 3000 rows.

How to check if value from A1,A2,A3 ETC is in B1:B3000 so I would see 5000 rows in column C with either True or False?



via Chebli Mohamed

Send a bitmap image in an email

I looked over similar questions and tried to write this simple code. This code takes an bitmap image of the view then allows the user to attach it to email. for some reason I get the message "can't attach an empty file" in the email application. I'm fairly new to this and I read a few examples and tried different things but non worked. I suspect that something might be wrong with my path.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.example.asamater.myapplication" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"   android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/scrollView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/linearLayout">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:text="Q1" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton2" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText2"
            android:text="Q2" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton3" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton4" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText3"
            android:text="Q3" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton5" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton6" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText4"
            android:text="Q3" />


        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton7" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton8" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText5"
            android:text="Q4" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton10" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton9" />
        </RadioGroup>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Email"
            android:id="@+id/button"
            android:layout_alignTop="@id/radioButton9"
            android:onClick="email" />

    </LinearLayout>



</ScrollView>

</RelativeLayout>

.

 package com.example.asamater.myapplication;

 import android.app.Activity;
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.BitSet;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public void email(View view){
    ScrollView z = (ScrollView) findViewById(R.id.scrollView);
    int totalHeight = z.getChildAt(0).getHeight();
    int totalWidth = z.getChildAt(0).getWidth();
    Bitmap bitmap = getBitmapFromView(z,totalHeight,totalWidth);
    String path = saveImageToStorage(bitmap);

    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "ammar5001@gmail.com");
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "report");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, " ");

    emailIntent.setType("image/jpeg");
    File bitmapFile = new File(Environment.getExternalStorageDirectory()+
            "/"+ path);
    Uri myUri = Uri.fromFile(bitmapFile);
    emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);


    startActivity(Intent.createChooser(emailIntent, "Send your email in:"));

}


private String saveImageToStorage(Bitmap bitmap) {
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/req_images");
    myDir.mkdirs();
    String fname = "Image-Report.jpg";
    File file = new File(myDir, fname);
    Log.i("myActivity", "" + file);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
        return root + "/req_images" + fname;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}


public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
    Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}

}



via Chebli Mohamed

How to convert Multilevel numbering list from Word document into text value in HTML

I am reviewing multiple Rich Text Editors to find the right one for a VB.NET web application which has IE11 incompatible Rich Text Editor.

With the IE11 compatibility, the most important requirement from clients is a functionality that copies contents from Word documents over into text editor without losing it Word formatting. (The content will be saved into database and be read by MS Word again)

However, all the Rich Text Editors that I have reviewed do not support the multilevel list formatting correctly. They change the multi-level numbers into single level numbers when coping the multi-level list from Word into them. - Rad Editor, CKEditor, tiny-mce and Rich Text Editor and so on.

Example,

1. A
  1.1. B
  1.2. B
    1.2.1. C
2. A
  2.1. B
  2.2. B

becomes

1. A
  1. B
  2. B
    1. C
2. A
  1. B
  2. B

I found a CSS trick to display <li> tag as multilevel numbers in the browser, but the numbers are not actual text values that can be saved into database. So, I need another solution that can save numbers and their format into the database like the current Rich Text Editor in my VB.Net web application. (It is a DLL, but not JavaScript library)

Can I get some helps/advices how to resolve this problem when copying over multi-level numbering list from Word into the RichTextEditor?

Thanks for answering in advance.



via Chebli Mohamed

Bootstrap column reordering on at least three screen sizes

I have problem with Bootstrap column rendering when I try to specify column reordering for three different screen sizes.

XS devices:

  • A
  • B
  • C
  • D

SM and MD devices:

  • B A
  • D C

LG devices:

  • D C B A

I can achieve XS and LG pattern or XS and MD pattern, but unfortunately not all three options at the same time. Is this possible with Bootstrap's classes?

Solution for XS and LG:

<div class="container">
    <div class="row">
        <div class="col-xs-12 col-lg-3 col-lg-push-9">
            <div class="form-group">
                <label>Label1</label>
                <input type="text" class="form-control" />
             </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-push-3">
            <div class="form-group">
                <label>Label2</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-pull-3">
            <div class="form-group">
                <label>Label3</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-pull-9">
            <div class="form-group">
                <label>Label4</label>
                <input type="text" class="form-control" />
            </div>
        </div>
    </div>
</div>

Now when I add middle view classes all get messed up. Is there an option to fix this?

<div class="container" style="background-color: pink">
    <div class="row">
        <div class="col-xs-12 col-md-6 col-md-push-6 col-lg-3 col-lg-push-9 col-lg-pull-0">
            <div class="form-group">
                <label>Label1</label>
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6 col-md-pull-6  col-lg-3 col-lg-push-3 col-lg-pull-0">
            <div class="form-group">
                <label>Label2</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6 col-md-push-6 col-lg-3 col-lg-pull-3 col-lg-pull-0">
            <div class="form-group">
                <label>Label3</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6  col-md-pull-6 col-lg-3 col-lg-pull-9 col-lg-push-0">
            <p>empty</p>
        </div>
    </div>
</div>

The following code is my best try but it simply does not work... Any ideas?



via Chebli Mohamed

Why does my OneToOne mapping through a JoinTable not work?

I've searched but cannot seem to find the answer.

I have two tables:

select ts_id, tsjoin_id, workdate from TimeSheets
select e_id, lastname from Employees

I also have a join table:

TSJoin
tsjoin_id, employee_id

There is only one Employee to a TimeSheet. So with any given TimeSheet entity, I'd expect to be able to:

TimeSheet ts = tsService.getTimeSheet(123);
String lastName = ts.getEmployee().getLastName();

In SQL, to get the employee of a TimeSheet:

select e.lastname from TimeSheets t
    join TSJoin x on (x.tsjoin_id = t.tsjoin_id)
    join Employees e on (e.e_id = x.employee_id)
where t.ts_id = 123

In my Hibernate mapping, I have:

@OneToOne
@JoinTable(
        name = "TSJoin",
        joinColumns = {
                @JoinColumn(name = "tsjoin_id", nullable = false)
        },
        inverseJoinColumns = {
                @JoinColumn(name = "e_id", nullable = false)
        }
)

However, the SQL it's generating is:

select * from TimeSheet t
    left outer join TSJoin x on (t.ts_id = x.tsjoin_id)

Which returns null for the Employee.

It's taking the primary key of the TimeSheet and trying to match the primary key of the join table.

What am I doing wrong?

EDIT

I also want to state that I have only setup one direction at this point. Which is a TimeSheet -> Employee (OneToOne) and that Employee is not mapped to TimeSheet yet. Not sure if this makes a difference but I wanted to mention it.

EDIT 2 I also want to state that I believe the error might be because my join table does not contain a reference to the TimeSheet. And Hibernate is assuming that a join table is going to contain the primary keys of each entity involved (legacy database). I could probably create a mapping of TimeSheet -> JoinTable -> Employee and access it as: ts.getJoin().getEmployee() but that's pretty ugly.



via Chebli Mohamed

Odd Errors Displayed Only in Console When Trying to Run Program

So I'm watching a tutorial to learn how to program in Java using Eclipse. So I got a few episodes in and I had to clear out all out the errors. I looked around and found no more errors so I tried to run the program and I got errors in that were only displayed in the console, and was being displayed next to the lines it was referencing. I have completely no idea how to solve these errors I haven't seen anything like them before. Also my program is fairly simple it is just the code to display and window and then have pixels of a random colour fill that window. I really would appreciate any help I can get, because I have no clue how to fix this error.

Thanks, Nova

Tutorial

Error:

`Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar` 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 65536 
at cpm.mime.GameP1.graphics.Screen.<init>(Screen.java:14) 
at com.mime.GameP1.Display.<init>(Display.java:29) 
at com.mime.GameP1.Display.main(Display.java:92)`



via Chebli Mohamed

Linq Expression in Case Statement

I'm using LINQ with Expression trees and a case Statement in my Select. I'm doing this because the Where Condition is build dynamically and in my Result, I need to know, which part of the where was true.

This works fine:

ParameterExpression peTbl = Expression.Parameter(typeof(MyTbl), "mytbl");

Expression left = Expression.Property(peTbl, "Col1");
Expression right = Expression.Constant((ulong)3344, typeof(ulong));
Expression e1 = Expression.Equal(left, right);

left = Expression.Property(peTbl, "Col2");
right = Expression.Constant((ulong)27, typeof(ulong));
Expression e2 = Expression.Equal(left, right);

Expression predicateBody = Expression.Or(e1, e2);

Expression<Func<MyTbl, bool>> whereCondition = Expression.Lambda<Func<MyTbl, bool>>(predicateBody, new ParameterExpression[] { peTbl });

var query = myTbl.Where(whereCondition)
            .Select(s => new { mytbl = s, mycase = (s.Col1 == 3344 ? 1 : 0) });

But now, I want to use the Expression e1 in my case Statement.

Something like this:

var query = myTbl.Where(whereCondition)
            .Select(s => new { mytbl = s, mycase = (e1 == true ? 1 : 0) });

Any idea how to do this?



via Chebli Mohamed

Python One-Liner: Sorting by multiple, interdepending keys

Disclaimer: This question is about me and hopefully others understanding Python better. My problem can be solved easily in more than one line, I know that.

Suppose I have two functions f(x), g(x,y) so that I can compute the tuple ( f(x), g(x,f(x)) ) as a function of x. I want to sort a list X by these two keys but computing f(x) is expensive so I want to do it only once per x. My current solution is:

X_s = sorted( X , key =  lambda x: (lambda y: ( y , g(x,y) ) )( f(x) ) )

Can I achieve the same without using two lambda functions?



via Chebli Mohamed

Database for user Accounts ionic framework

I need to incorporate a simple user profile for each person who uses my ionic android app. That way they can login and access or edit personal information unique to their personal accounts.

I've been browsing all over the net for a day, and especially the ionic documentation for any info on how to make such a feature on my app. I can do that using php and mysql but don't know about ionic's approach. Please advice.



via Chebli Mohamed

asp call to java script removes brackets

I am new to asp and vbscript and attempting to pass a database critera list to javascript. The criteria will be used in sql statements in clause, if that is what it is called. The problem is the parethesis are removed!

The criterias for the in clause look like

  • "('Not Defined')"
  • "('A Condition')"
  • "('B Condition')"
  • "('C Condition', 'D Condition')"
  • "('E Condition', 'F Condition', 'G Condition')"
  • "('H Condition', 'I Condition', 'J Condition', 'K Condition')"

The javascipt take to parameters for row and column and searches a database and returns a list of table entries dependent on those conditions or set of conditions.

I've been working with the following:

Response.Write "<td WIDTH='6%'  VALIGN='TOP' ALIGN='CENTER' bgcolor = " & ObjDic(elem).clrPreExisting & ">" & vbCRLF
Response.Write "<a href = ""javascript:alert("objDic(elem).critRow")""><font size='2' face='Arial' color='#000000'>" & ObjDic(elem).Get_PreExistingVal(RunningTotal.PreExisting) & "</font></a>" &vbCRLF
Response.Write "</td>" & vbCRLF

the value of objDic(elem).critRow from the immediate window shows

objDic(elem).critRow "('Not Defined')" But thie Java alert shows Not Defined.



via Chebli Mohamed

Converting curl call to Java

I login to a server (php page) using the code below:

$curl -b cookies --output 'result' \
    --data 'user=me@myself.com' \
    --data 'password=donttellanyone' \
    http://ift.tt/1JxDJA3

After executing this command in terminal, a file named result will be created and inside it is just a html page that says login success.

But I now want to do the same thing using a Java console application...but I havent got any success yet. Executing this Java code results in error. I guess it is because I am not giving username and password in a correct way.

This is my code:

URL url = new URL("http://ift.tt/1jbM0iA");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestProperty("Cookie",  "username=" + email + "; password=" + pwd);
conn.connect();

So the question is how to convert the above curl command to Java code?



via Chebli Mohamed

add class on html tag

I am try to apply a class on HTML tag, if the tag exists.

i try this code...

<!DOCTYPE html>
<html xmlns="http://ift.tt/lH0Osb">
<head>
    <title>index</title>

    <style>
        .black
        {
            background:#000;
            color:white;
        }

    </style>
    <script type="text/javascript">
        $(window).load(function () {
            $('textarea').addClass('black');
        });
    </script>
</head>
<body>

    <div>


        <textarea>content</textarea>


    </div>

    <script src="jquery.js"></script>

</body>
</html>

What i want: If the html body contain textarea tag the the .black class will apply on it automaticly.



via Chebli Mohamed

PortAudio: Playback lag at default frames-per-buffer

I'm trying to play audio in Go, asynchronously, using PortAudio. As far as I'm aware PortAudio handles its own threading, so I don't need to use any of Go's build-in concurrency stuff. I'm using libsndfile to load the file (also Go bindings). Here is my code:

type Track struct {
    stream   *portaudio.Stream
    playhead int
    buffer   []int32
}

func LoadTrackFilesize(filename string, loop bool, bytes int) *Track {
    // Load file
    var info sndfile.Info
    soundFile, err := sndfile.Open(filename, sndfile.Read, &info)
    if err != nil {
        fmt.Printf("Could not open file: %s\n", filename)
        panic(err)
    }
    buffer := make([]int32, bytes)
    numRead, err := soundFile.ReadItems(buffer)
    if err != nil {
        fmt.Printf("Error reading from file: %s\n", filename)
        panic(err)
    }
    defer soundFile.Close()

    // Create track
    track := Track{
        buffer: buffer[:numRead],
    }

    // Create stream
    stream, err := portaudio.OpenDefaultStream(
        0, 2, float64(44100), portaudio.FramesPerBufferUnspecified, track.playCallback,
    )
    if err != nil {
        fmt.Printf("Couldn't get stream for file: %s\n", filename)
    }
    track.stream = stream

    return &track
}

func (t *Track) playCallback(out []int32) {
    for i := range out {
        out[i] = t.buffer[(t.playhead+i)%len(t.buffer)]
    }
    t.playhead += len(out) % len(t.buffer)
}

func (t *Track) Play() {
    t.stream.Start()
}

Using these functions, after initialising PortAudio and all the rest, plays the audio track I supply - just. It's very laggy, and slows down the rest of my application (a game loop).

However, if I change the frames per buffer value from FramesPerBufferUnspecified to something high, say, 1024, the audio plays fine and doesn't interfere with the rest of my application.

Why is this? The PortAudio documentation suggests that using the unspecified value will 'choose a value for optimum latency', but I'm definitely not seeing that.

Additionally, when playing with this very high value, I notice some tiny artefacts - little 'popping' noises - in the audio.

Is there something wrong with my callback function, or anything else, that could be causing one or both of these problems?

Thanks.



via Chebli Mohamed

DockerHub Private Repo Login. More secure way?

I've seen articles such as this one about pulling from private repos and the "best" way to do it. What I understand is, if I want to automate any infrastructure to pull my docker images from dockerhub I need to:

  • Have a user I can login with.
  • Save the users creds in some application that will spin up my infrastructure (be it EC2 User data, a config file for ansible, or ENV variables in some API).
  • When the machine spins up it uses this user's credentials to login and place a token on the machine. All is well.

I'm wondering if there is any functionality to use application keys / tokens instead of needing to tie this to a user. It seems like it would be more secure/convenient if I could manage application keys to do have access to my user/organization's DockerHub account. Then I could yank the keys or change my password and not worry about the sky falling.

Is something like this available, coming, or is there a solution I haven't come across yet?

Thanks!



via Chebli Mohamed

Android Studio. Can i use startLockTask() on app X from app Y knowing the packageName of X?

The titles says it all. I want to start the LockTask introduced in lollipop on an app from another app. Can i do such thing ? Ty.



via Chebli Mohamed

How to add placeholder text to yii inputfield?

iam using clevertech an extension for YII, dose anybody know how i can add my own custom placeholder text inside the input. Below is an example of the input filed:

<?php echo $form->textFieldGroup(
            $model,
            'textField',
            array(
                'wrapperHtmlOptions' => array(
                    'class' => 'col-sm-5',
                ),
                'hint' => 'In addition to freeform text, any HTML5 text-based input appears like so.'
            )
        ); ?>



via Chebli Mohamed

Object prototype and class in Javascript

I'am working with javascript but I've doubts with my code because the function does not work as I want. This is my code:

classDescuentos = function () {
};

classDescuentos.prototype = {
var cellsEditar = function (row, column, columnfield, value, defaulthtml, columnproperties) {
            var data = grid.jqxGrid('getrowdata', row);
            var style = "";

            if (data.editar == 't' && data.apr_ger == 'f') {
                style = "display:block";
            } else {
                style = "display:none";
            }

            var html = "";
            var activarBotEnv = actBtn;
            html = "<div id='activarEdicion_" + row + "' style='width:99%;text-align:center;" + style + "' ><a href='#' id='editarHora' name='editarHora' title='Editar Total horas descontar' onclick=classDescuentos.prototype.editarHora(" + row + ");><img style='padding-bottom: 0px' height='17px' width='17px' src=../../../media/img/edit.png></a></div>";
            return html;
        };

editarHora: function (row) {
        var grid = $(this.gridData);
        grid.jqxGrid('setcolumnproperty', 'des_hor_ger_format', 'editable', true);
        grid.jqxGrid('begincelledit', row, "des_hor_ger_format");

        grid.on('cellendedit', function () {
            grid.jqxGrid('setcolumnproperty', 'des_hor_ger_format', 'editable', false);
        });
    }
};

Should allow edit the data of a cell of a jqxGrid of JQWidget and take the data that is entered but still leaves the original data before modifying it.

What am I doing wrong does not work?



via Chebli Mohamed

How to find the source table rows used by a big complex query

We have a huge Oracle SQL query in our project which is using many views and tables for source data.

Is there any way to find the list of rows fetched from each source table by this big query when I run it?

Basically what we are trying to do is to create the bare minimum number of rows in the source tables so that the outer most big query returns at least a single record.

I have tried to run the smaller queries individually. But it is really time consuming and tedious. So I was wondering if there is a smarter way of doing this.



via Chebli Mohamed

Find all numbers in a integer list that add up to a number

I was asked this question on an interview. Given the following list:

[1,2,5,7,3,10,13]

Find the numbers that add up to 5.

My solution was the following:

#sort the list:
l.sort()
result = ()
for i in range(len(l)):
    for j in range(i, len(l)):
         if l[i] + l[j] > 5:
             break
         elif l[i] + l[j] == 5:
             result += (l[i], l[j])

The idea I presented was to sort the list, then loop and see if the sum is greater than 5. If so, then I can stop the loop. I got the sense the interviewer was dissatisfied with this answer. Can someone suggest a better one for my future reference?



via Chebli Mohamed

How do I use try, except?

I am currently making a program for the raspberry pi2 I just brought and with the help from some other members, have got it to work most of the time. however there are some case where it won't work because a field doesnt exist in the json if im correct. the code i have is:

import urllib.request
import json

r = urllib.request.urlopen("http://ift.tt/1NTgHGN").read()
rr = r.decode()

obj = json.loads(rr)

# filter only the b16 objects
b16_objs = filter(lambda a: a['routeName'] == 'B16',  obj['arrivals'])

if b16_objs:
# get the first item
b16 = next(b16_objs)
my_estimatedWait = b16['estimatedWait']

my_destination = b16['destination']
print(my_estimatedWait)

My problem is that when routeName B16 is not in the json, an error comes up. I've tried to use the try and catch feature but I could not get this to work. Is there another way of catching this error and displaying a message saying its not present?

The try and catch

try:
b16 = next(b16_objs)
except:
print("there are no records of this")



via Chebli Mohamed

Orchard 1.9.1 Duplicating Menu

I just upgraded an Orchard website from 1.7.1 to 1.9.1 and it seems like a number of things were broken in the process. I managed to fix all of them except for one - all of my navigation items in the menu lost the links to their associated content items, so when I started adding them back in for some reason the front-end start duplicating everything. I'm on a custom theme and the menu started showing up properly, but it's duplicating all menu items right in the root with <option /> tags. I can hide those through CSS easily enough, but it's also adding "undefined" in here too, something I can't seem to target and hide.

Bad Site Navigation

Any idea why this is happening?

Update I figured out the "undefined" part - it's more of the content menu items being blown out, but this time it was a custom link (just a #, since it didn't go anywhere) that didn't have a URL, so it was showing as undefined. The rogue <option /> values are still here, though I can hide them via CSS. I just don't like that they are in the markup at all.



via Chebli Mohamed

Can not get All Post from Json API to ionic

i have this steps to get posts of category from Json API WordPress, And my problem is cannot print post title and content in page but in console i get it.

My code:-

     myApp.factory('Allposts',['$http', '$q',function($http,$q){
        var allposts = [];
        var pages = null;
        return {

        GetAllposts: function (id) {
            return $http.get("http://localhost/khaliddev/azkarserv/?json=get_category_posts&id="+id+"&status=publish",{params: null}).then(function (response) {
               items = response.data.posts;
               console.log(items); 
                allposts = items;
                return items;
            });
        }
        }
}]);

The http://localhost/khaliddev/azkarserv/?json=get_category_posts&id=16&status=publish is like

{"status":"ok","count":1,"pages":1,"category":{"id":16,"slug":"%d8%a3%d8%b0%d9%83%d8%a7%d8%b1-%d8%a7%d9%84%d8%a7%d8%b3%d8%aa%d9%8a%d9%82%d8%a7%d8%b8","title":"\u0623\u0630\u0643\u0627\u0631 \u0627\u0644\u0627\u0633\u062a\u064a\u0642\u0627\u0638","description":"","parent":0,"post_count":1},"posts":[{"id":31,"type":"post","slug":"%d8%a3%d8%b0%d9%83%d8%a7%d8%b1-%d8%a7%d9%84%d8%a7%d8%b3%d8%aa%d9%8a%d9%82%d8%a7%d8%b8","url":"http:\/\/localhost\/khaliddev\/azkarserv\/2015\/08\/28\/%d8%a3%d8%b0%d9%83%d8%a7%d8%b1-%d8%a7%d9%84%d8%a7%d8%b3%d8%aa%d9%8a%d9%82%d8%a7%d8%b8\/","status":"publish","title":"\u0623\u0630\u0643\u0627\u0631 \u0627\u0644\u0627\u0633\u062a\u064a\u0642\u0627\u0638","title_plain":"\u0623\u0630\u0643\u0627\u0631 \u0627\u0644\u0627\u0633\u062a\u064a\u0642\u0627\u0638","content":"<p>\u0627\u0644\u062d\u0645\u0640\u062f \u0644\u0644\u0647 \u0627\u0644\u0630\u064a \u0623\u062d\u0640\u064a\u0627\u0646\u0627 \u0628\u0639\u0640\u062f \u0645\u0627 \u0623\u0645\u0627\u062a\u0640\u0646\u0627 \u0648\u0625\u0644\u064a\u0647 \u0627\u0644\u0646\u0640\u0634\u0648\u0631.<\/p>\n","excerpt":"<p>\u0627\u0644\u062d\u0645\u0640\u062f \u0644\u0644\u0647 \u0627\u0644\u0630\u064a \u0623\u062d\u0640\u064a\u0627\u0646\u0627 \u0628\u0639\u0640\u062f \u0645\u0627 \u0623\u0645\u0627\u062a\u0640\u0646\u0627 \u0648\u0625\u0644\u064a\u0647 \u0627\u0644\u0646\u0640\u0634\u0648\u0631.<\/p>\n","date":"2015-08-28 23:14:11","modified":"2015-08-28 23:14:11","categories":[{"id":16,"slug":"%d8%a3%d8%b0%d9%83%d8%a7%d8%b1-%d8%a7%d9%84%d8%a7%d8%b3%d8%aa%d9%8a%d9%82%d8%a7%d8%b8","title":"\u0623\u0630\u0643\u0627\u0631 \u0627\u0644\u0627\u0633\u062a\u064a\u0642\u0627\u0638","description":"","parent":0,"post_count":1}],"tags":[],"author":{"id":1,"slug":"azkarserv","name":"azkarserv","first_name":"","last_name":"","nickname":"azkarserv","url":"","description":""},"comments":[],"attachments":[],"comment_count":0,"comment_status":"open","custom_fields":{}}]}

and view is

<ion-view view-title="">

<ion-nav-title>
  <img class="logo" src="img/logo.png">
</ion-nav-title>


<ion-content class="padding" lazy-scroll>
<div class="row no-padding HomeRowsList">

<dive class="item itemfull" ng-repeat="post in allposts">

<div class="item item-body">
<div>
{{ post.title }}
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
</div>
</div>
</div>
</div>
</div>
</ion-content>

</ion-view>



via Chebli Mohamed

How to dynamically traverse a global array without creating any copy of it?

For example something like this:

function POSTTraverse($key0 [, $key1 [, $key2 ...]]) {
    ...
    return $value;
}

The usage would be for example:

POSTTraverse('document', 'item', 'quantity', 5);



via Chebli Mohamed

Javascript Math.pow() returning Uncaught TypeError: Cannot read property '0' of undefined

I can't seem to figure out why this:

Populations[0] = Math.round(Math.pow((Populations[0] * Math.E), (popGrowth * 5)));
Populations[1] = Math.round(Math.pow((Populations[1] * Math.E), (popGrowth * 5)));
Populations[2] = Math.round(Math.pow((Populations[2] * Math.E), (popGrowth * 5)));

returns this:

Uncaught TypeError: Cannot read property '0' of undefined

JSFiddle:http://ift.tt/1MYsAut

window.addEventListener('load', function () {
    document.getElementById("buttonEndTurn").addEventListener('click', endTurn());
});
var Populations = [100, 100, 100];
var popGrowth = [0.1797];
var resourceGold = [1000, 1000, 1000];
var resourceWood = [500, 500, 500];
var minerPercent1 = 0.5;
var minerPercent2 = 0.75;
var minerPercent3 = 0.1;
var Miners = [0, 0, 0];
var Loggers = [0, 0, 0];
var endTurn = function (Populations,popGrowth,resourceGold,resourceWood,minerPercent1,minerPercent2,minerPercent3,Minners,Loggers) {
    popGrowth += Math.random;

    Populations[0] = Math.round(Math.pow((Populations[0] * Math.E), (popGrowth * 5)));
    Populations[1] = Math.round(Math.pow((Populations[1] * Math.E), (popGrowth * 5)));
    Populations[2] = Math.round(Math.pow((Populations[2] * Math.E), (popGrowth * 5)));
        
 for (var m = 0; m < 3;m++) {console.log(Populations[m])};
    
    Miners = [Math.round(Populations[0] * minerPercent1),
    Math.round(Populations[1] * minerPercent2),
    Math.round(Populations[2] * minerPercent3)];

    Loggers = [Populations[0] - Miners[0],
    Populations[1] - Miners[1],
    Populations[2] - Miners[2]];
    for (var i = 0; i < 3; i++) {
        console.log(Miners[i]);
    }
    for (var j = 0; j < 3; j++) {
        console.log(Loggers[j]);
    }

    resourceGold[0] += Miners[0] * 100;
    resourceGold[1] += Miners[1] * 100;
    resourceGold[2] += Miners[2] * 100;

    resourceWood[0] += Loggers[0] * 100;
    resourceWood[1] += Loggers[1] * 100;
    resourceWood[2] += Loggers[2] * 100;

    for (var k = 0; k < 3; k++) {
        console.log(resourceGold[k]);
    }

    for (var l = 0; l < 3; l++) {
        console.log(resourceWood[l]);
    }
};
<script src="http://ift.tt/1oMJErh"></script>
<button id="buttonEndTurn">End Turn</button>
<canvas id="hexCanvas" width="800" height="600" style="width:800px;height:600px" />


via Chebli Mohamed

How to save user preferences in Core Data?

I am using Core Data to save my data. I preloaded the data from a .csv file. I have an entity named places, with an attribute isFavorite. I am populating the data in UITableViewController. TableViewCell consists of some labels and a button. When the user taps the button the value of isFavorite changes from false to true and vice-versa. I want to show the list of favorite places of the user in a separate tableView. Only those places are shown in favorite tab whose isFavorite value is true.

The problem I am facing is, when the value of isFavorite changes on the click of the button say from false to true and the user closes the app. Upon relaunch the isFavorite value changes back to the one that is saved in the .csv file. How can I save the user changes? So that the favorite places remain in the favorite list.

I read a few articles about NSUserDefaults but couldn't understand properly. If anyone can help me considering my app's scenario, would be appreciated.



via Chebli Mohamed

How can I tell if IPython is running?

I have an IPython notebook. I have a long-running loop that produces no output in one of the code blocks. It's not this, but imagine it was this:

for i in range(100):
    time.sleep(2)

I started the code block running a while ago, and now I can't tell whether it's finished, or whether it's still running.

All the IPython status bar says at the top is Last Checkpoint: 23 minutes ago (autosaved). There's nothing in the browser tab to show whether it's running code, either.

I don't want to start the next block because I don't know if this block has finished.

And I don't want to stop the kernel and add print statements to this block, because if it's 80% of the way through, I don't want to kill it and restart it!

Is there anything in IPython - either the browser window or the console - that indicates what code is running right now?



via Chebli Mohamed

unit testing angularjs app with ocLazyLoad

What is the setup I need to run unit tests for an AngularJS app using ocLazyLoad?

What should karma.conf.js look like? I assume I need test-main.js like examples using Karma, Jasmine, and RequireJS, but maybe I'm wrong.

I'm using Webstorm to run the tests, or command line.

I'm starting with testing my services, but eventually I want to run end-to-end tests with Protractor to test the DOM.



via Chebli Mohamed

Recursive call in the try-catch statement without StackOverflowError exception

I have the following snippet of code:

public static void main(String[] args) {
    foo();
}
public static void foo() {
    try {
        foo();
    } catch (Throwable t) {
        foo();
    }
}

Can anyone explain me what's going on here? In details, please.


I have changed this piece and added println methods to show something:

...
try {
    System.out.println("+");
    foo();
} catch (Throwable t) {
    System.out.println("-");
    foo();
}
...

I'm getting something like this (the process hasn't stopped):

+
+
+
+
+--
+--
+
+--
+--
+
+
+--
+--
+
+--
+--
+
+
+
+--
+--

I haven't had any exception (like StackOverflowError).



via Chebli Mohamed

HSQL DB SQL function calculation gives different results between HSQLDB and Oracle

I am getting different results between HSQLDB and Oracle. Am I missing anything in the query?

      SELECT   (-300 / (24*60)) AS resultVal FROM DUAL;
      ---0.2083333333333333333333333333333333333333 oracle
      --0 hsqldb

Thanks Jugunu



via Chebli Mohamed

Fetch data from multiple tables in django views

In Django views, I want to fetch all details(Workeraccount.location,Workeravail.date, Workerprofile.*) for any particular wid=1.

SQL Query:

select * from Workeraccount,Workeravail,Workerprofile where Workerprofile.wid=1 and Workerprofile.wid=Workeravail.wid and Workeraccount.wid=Workerprofile.wid;

The corresponding models are as follows:

class Workeraccount(models.Model):
    wid = models.ForeignKey('Workerprofile', db_column='wid', unique=True)
    location = models.ForeignKey(Location, db_column='location')
    class Meta:
        managed = False
        db_table = 'workerAccount'

class Workeravail(models.Model):
    wid = models.ForeignKey('Workerprofile', db_column='wid')
    date = models.DateField()
    class Meta:
        managed = False
        db_table = 'workerAvail'

class Workerprofile(models.Model):
    wid = models.SmallIntegerField(primary_key=True)
    fname = models.CharField(max_length=30)
    mname = models.CharField(max_length=30, blank=True, null=True)
    lname = models.CharField(max_length=30)
    gender = models.CharField(max_length=1)
    age = models.IntegerField()
    class Meta:
        managed = False
        db_table = 'workerProfile'`



via Chebli Mohamed

cronjob to remove file where the name contains the date of 7 days ago

I have created a cronjob to backup a database into a sql file with a date in the file name:

5 0,10,15,20 * * * /usr/syno/mysql/bin/mysqldump -u<user> -p<password> --opt DATABASE > "/volume5/DATABASE$(date +\%F).sql"`

I am trying to have an other cronjob to delete the file of 7 days ago

0 0 * * * rm /volume5/DATABASE$(/bin/date -D "%s" -d $(( $(/bin/date +\%s ) - 604800 )) +\%F).sql

for example, if the actual date is 2015-08-31, the file of 7 days ago is DATABASE2015-08-24.sql, which should be deleted.

the removal does not work by cron, but does by manual command, so I guess it is only a missing "escape", but I can't figure out where.

Does anybody know where is the problem ?

The "X days ago" option does not work with this date bin.



via Chebli Mohamed

SPARQL-Query doesn't yield expected results

I have a Virtuoso Server and run a SPAQRL-Query against it, which doesn't yield the expected results. I'm not quiet sure, what the problem might be, so I hope some of you have an idea where to look.

This is my SPARQL-Endpoint

The query

select * where {?s ?p
   &lt;http://ift.tt/1KzV6lR;. }

yields one result:

http://ift.tt/1JxDF3j    http://ift.tt/1KzV5ON

When I use the result for ?p in the query like:

select * where {?s &lt;http://ift.tt/1JxDF3l; &lt;http://ift.tt/1KzV6lR;. }

I don't get any result.

For other objects, it works perfectly, like:

select * where {?s &lt;http://ift.tt/1JxDF3l; &lt;http://ift.tt/1KzV6lW;. }

I have no idea, why it works for one Uri but not for the other. Any help pointing me towards the answer is appreciated!



via Chebli Mohamed

For will not iterate through entire list in Python

so I'm learning Python and having trouble with this small program I've designed to try and take my Codecademy skills further.

car_models = ["Ferrari", "Lamborghini", "Aston Martin", "BMW"]
bad_cars = ["Toyota", "Mazda", "Ford", "Hyundai"]

for gcar, bcar in zip(car_models, bad_cars):
    ask = input("What is your favorite car brand? ")
    if ask == gcar:
        print("Yes!")
    elif ask == bcar:
        print("Ew!")
    else:
        print("The model is not listed")
    break

When I run this, it will only pop up with an answer if the model is the first one on the list, otherwise, it just tells you that the model is not listed even though it is.

Thanks!



via Chebli Mohamed

What can I do so that the program is not starting to draw from the last point added?

I am trying to create a program such that there is a square going inside another square (slightly rotated), and another square going inside and so on. I've managed to create a program that does that. But I want the program to make several boxes like that. Take a look at the illustration to get a better idea:

My problem is that after drawing the first box, and then trying to draw the second, the "cursor" drawing the lines is kind of stuck at the last point, so it's drawing the line from the last point of my first square to the first point in the second square, like this:

So as you can see inside pointPanel-constructor I've tried clearing the list, and resetting the counter and i-variable, but no luck. Is there any modifications I can do such that I don't have this problem? I've tried placing the clear()-instruction other places. But maybe I'm missing something.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;




public class Art {
    ArrayList<Point> points = new ArrayList<>();
    int i =0;
    public static void main(String[] args) {
        new Art();
    }

    public Art() {
        JFrame frame = new JFrame("Art");
        frame.add(new pointPanel());

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);


    }

    public class pointPanel extends JPanel{
        //Constructor
        public pointPanel(){
            points(0, 100);
            //points.clear();
            points(500, 200);

        }

        @Override
        //Dimension
        public Dimension getPreferredSize() {
            return new Dimension(800, 600);
        }



        public void points(double x, double y){
            double t=0.1;   //constant
            final int side = 100;
            int counter=0;

            while (counter<20){
                 //Init the first points-->
                Point p  = new Point((int)(x),      (int) (y)           );
                Point p1 = new Point((int)(x+side), (int)(y)            );
                Point p2 = new Point((int)(x+side), (int) (y-side)      );
                Point p3 = new Point((int)(x),      (int)(y-side)       );
                Point p4 = new Point((int)(x),      (int)(y)            );
                //-->and adding them to the list
                if (counter == 0) {
                    points.add(p);
                    points.add(p1);
                    points.add(p2);
                    points.add(p3);
                    points.add(p4);
                }


                //Dynamic part: 
                //If the method has been run earlier - place points making it possible to draw lines
                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i+1).x;
                    y=(1-t)*points.get(i).y + t * points.get(i+1).y;
                    points.add(  new Point( (int) x, (int) y)  );
                    i++;    
                }

                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i+1).x;
                    y=(1-t)*points.get(i).y + t * points.get(i+1).y;
                    points.add(  new Point( (int) x, (int) y)  );
                    i++;
                }

                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i+1).x;
                    y=(1-t)*points.get(i).y + t * points.get(i+1).y;
                    points.add(  new Point( (int) x, (int) y)  );
                    i++;
                }

                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i+1).x;
                    y=(1-t)*points.get(i).y + t * points.get(i+1).y;
                    points.add(  new Point( (int) x, (int) y)  );
                    i++;
                }

                if (counter>0){
                    x=(1-t)*points.get(i).x + t * points.get(i-3).x;
                    y=(1-t)*points.get(i).y + t * points.get(i-3).y;    
                    points.add(  new Point( (int) x, (int) y)  );       
                    i++;
                }



                counter++;

            }//while
        //counter=0;
        //i=0;
        x=0;
        y=0;

        }//metode

        //Paint-method
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;

            g2d.setColor(Color.RED);
            for (int i = 0; i < points.size()-1; i++) {
                g2d.drawLine(points.get(i).x, points.get(i).y, points.get(i+1).x, points.get(i+1).y);
            }

           g2d.dispose();
        }   
    }
}



via Chebli Mohamed

Find distinct values based upon multiple columns

I have a spreadsheet of sales with (to keep the example simple) 3 columns

NAME -- STATE -- COUNTRY 

It's easy to find how many sales. (sum all the lines) I can find out how many customers I have but how about finding out how many customers from a particular state (and country)

NAME -- STATE -- COUNTRY
p1----- CA------ USA
p2----- CA------ USA
p1----- CA------ USA
p1----- CA------ USA
p3----- NY------ USA
p3----- NY------ USA

The above example would give 2 unique customers from CA and 1 unique customer from NY and 3 from the USA

EDIT:

The desired result from the above table would be

STATE - UNIQUE CUSTOMERS 
CA ----  2
NY ----  1

COUNTRY - UNIQUE CUSTOMERS
USA ---- 3



via Chebli Mohamed

How do I push a view controller onto the nav stack from search results when presenting them modally?

I want to recreate the search UI shown in the iOS 7/8 calendar app. Presenting the search UI modally isn't a problem. I use UISearchController and modally present it just like the UICatalog sample code shows which gives me a nice drop down animation. The issue comes when trying to push a view controller from the results view controller. It isn't wrapped in a navigation controller so I can't push onto it. If I do wrap it in a navigation controller then I don't get the default drop down animation when I present the UISearchController. Any ideas?

EDIT: I got it to push by wrapping my results view controller in a nav controller. However the search bar is still present after pushing the new VC onto the stack.



via Chebli Mohamed