Q:

Android SQLite wont add values to the db

I'm just trying to figure out how to work with android SQLite and I've followed many different tutorials. But for some reason i cannot get anything to work.
Here is the code im using:
DBHandler.java
package com.example.deathtrackkevin;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHandler extends SQLiteOpenHelper  {

    // All static variables
    //Database Version
    private static final int DATABASE_VERSION = 1;

    //Database Name
    private static final String DATABASE_NAME = "DeathTrackDB";

    //DeathTrack Table Name
    private static final String TABLE_DEATHTRACK = "DeathTrack";

    //Deathtrack Table Column Names
    private static final String COL_GAME_ID = "Game_ID";
    private static final String COL_GAME_NAME = "Game_Name";
    private static final String COL_KILLS = "kills";
    private static final String COL_DEATHS = "Deaths";
    private static final String COL_DATE = "date";
    private static final String COL_MATCH = "Match";

    public DbHandler(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_DEATHTRACK_TABLE =
                "CREATE TABLE" + TABLE_DEATHTRACK + "("
                + COL_GAME_ID + "INTEGER PRIMARY KEY,"
                + COL_GAME_NAME + "TEXT,"
                + COL_KILLS + "TEXT,"
                + COL_DEATHS + "TEXT,"
                + COL_DATE + "TEXT,"
                + COL_MATCH + "TEXT" + ")";
        db.execSQL(CREATE_DEATHTRACK_TABLE);
    }

    //Upgrading Database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop Older Table If Exists
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_DEATHTRACK);
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    //Adding New Deathtrack TODO Create array for deathtrack
    void addDeathtrack(DeathTrack deathtrack) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COL_GAME_ID, deathtrack.get_game_id());
        values.put(COL_GAME_NAME, deathtrack.get_game_name());
        values.put(COL_KILLS, deathtrack.get_kills());
        values.put(COL_DEATHS, deathtrack.get_Deaths());
        values.put(COL_DATE, deathtrack.get_Date());
        values.put(COL_MATCH, deathtrack.get_match());

        //Inserting Row
        db.insert(TABLE_DEATHTRACK, null, values);
        db.close();
    }
    //TODO Getting Single Deathtrack
    DeathTrack getDeathtrack(int id){
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_DEATHTRACK, new String[] {COL_GAME_ID, COL_GAME_NAME, COL_KILLS, COL_DEATHS, COL_DATE, COL_MATCH}, COL_GAME_ID + "=?", new String[] {String.valueOf(id)}, null, null, null, null);
        if(cursor != null)
            cursor.moveToFirst();

        DeathTrack deathtrack = new DeathTrack(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1),
                cursor.getString(2),
                cursor.getString(3),
                cursor.getString(4),
                cursor.getString(5));

        return deathtrack;
    }

    //TODO Get all deathtrack values
    public List<DeathTrack> getAllDeathtrack(){
        List<DeathTrack> deathtrackList = new ArrayList<DeathTrack>();
        //Select all Query
        String selectWhere = "SELECT * FROM" + TABLE_DEATHTRACK;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectWhere, null);

        //Looping through all rows and adding to list
        if(cursor.moveToFirst()){
            do{
                DeathTrack deathtrack = new DeathTrack();
                deathtrack.set_game_name(cursor.getString(0));
                deathtrack.set_kills(cursor.getString(1));
                deathtrack.set_Deaths(cursor.getString(2));
                deathtrack.set_Date(cursor.getString(3));
                deathtrack.set_match(cursor.getString(4));
                //Add deathtrack to list
                deathtrackList.add(deathtrack);
            } while (cursor.moveToNext());
        }
        return deathtrackList;
    }
    //TODO Delete deathtrack value by game name
    public void deleteDeathtrack(DeathTrack deathtrack){
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_DEATHTRACK, COL_GAME_NAME + "= ?", new String[]{            String.valueOf(deathtrack.get_game_name())});
        db.close();
    }

}

SQLTester.java
package com.example.deathtrackkevin;

    import java.util.List;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;

    public class SQLTester extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.sqltester_layout);

            DbHandler db = new DbHandler(this);

            /**
             * CRUD Operations
             * */
            // Inserting Contacts
            Log.d("Insert: ", "Inserting ..");
            db.addDeathtrack(new DeathTrack(1, "cod2", "4", "2", "02-02-12", "1"));
            db.addDeathtrack(new DeathTrack(2, "cod3", "4", "2", "02-02-12", "1"));
            db.addDeathtrack(new DeathTrack(3, "cod4", "4", "2", "02-02-12", "1"));
            db.addDeathtrack(new DeathTrack(4, "cod5", "4", "2", "02-02-12", "1"));

            // Reading all contacts
            Log.d("Reading: ", "Reading all contacts..");
            List<DeathTrack> contacts = db.getAllDeathtrack();

            for (DeathTrack cn : contacts) {
                String log = "Game_Id: "+cn.get_game_id()+" ,Game_Name: " + cn.get_game_name() + " ,Kills: " + cn.get_kills()+ " ,Deaths: " + cn.get_Deaths()+ " ,Date: " + cn.get_Date()+ " ,Match: " + cn.get_match();
                    // Writing Contacts to log
            Log.v("dt", "name "+log);
        }
        }
    }

Question
Basically all i need is someone to tell me if there is something wrong..Im not getting any logcat errors or any other type of errors so i cannot use those to figure out whats going on
Regards
Joe

A:

It seems like your spacebar is broken...
    String CREATE_DEATHTRACK_TABLE =
            "CREATE TABLE" + TABLE_DEATHTRACK + "("
            + COL_GAME_ID + "INTEGER PRIMARY KEY,"
            + COL_GAME_NAME + "TEXT,"
            + COL_KILLS + "TEXT,"
            + COL_DEATHS + "TEXT,"
            + COL_DATE + "TEXT,"
            + COL_MATCH + "TEXT" + ")";

And
String selectWhere = "SELECT * FROM" + TABLE_DEATHTRACK;

Won't work.
Instead, you need to write
    String CREATE_DEATHTRACK_TABLE =
            "CREATE TABLE " + TABLE_DEATHTRACK + " ("
            + COL_GAME_ID + " INTEGER PRIMARY KEY, "
            + COL_GAME_NAME + " TEXT, "
            + COL_KILLS + " TEXT, "
            + COL_DEATHS + " TEXT, "
            + COL_DATE + " TEXT, "
            + COL_MATCH + " TEXT)";

And
String selectWhere = "SELECT * FROM " + TABLE_DEATHTRACK;

[EDIT]
You are using the reserved KeyWord MATCH.
You better change it to something like Round or Challenge.
For your reference: https://www.sqlite.org/lang_keywords.html


Q:

What is dereferenced error?

I executed the following code and I got the following errors.
I make some edit for last part in order to make it in code format.
RunUnitConvert.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;

/**
*
*  This is a test driver for the UnitConverter class
*  Write a unit conversion program that asks users to
*  identify the unit from which they want to convert and
*  the unit to which they want to convert. Legal units
*  are in, ft, mi, mm, cm, m, and km. Define two
*  objects of a class UnitConverter that convert
*  between meters and a given unit.
*
*/
public class RunUnitConverter
{
  public static void main(String[] args)
   {
           BufferedReader br;
           char fromUnit = '\0';
           char toUnit = '\0';
           double value = 0;

    //  prompt the user to enter unit to convert from
        System.out.print("Convert from: ");
    //  open up standard input
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            fromUnit = (char)br.read();
        } catch (IOException ioe) {
            System.exit(1);
        }
    // prompt user to enter unit to convert to
        System.out.print("Convert to: ");
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            toUnit = (char)br.read();
        } catch (IOException ioe) {
            System.exit(1);
    }

    // create new UnitConvert objects
         UnitConverter from = new UnitConverter(fromUnit);
        UnitConverter to = new UnitConverter(toUnit);

    // prompt user to enter initial value to convert
        System.out.print("Value: ");
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            value = Double.parseDouble(br.readLine());
        } catch (IOException ioe) {
        System.exit(1);
        }

        double metric = from.toMetric(value);
        double converted = to.fromMetric(metric);

        if (converted < 0) {
            System.out.println("ERROR: Bad Input");
        }
        else {
            System.out.println(value + " " + fromUnit + " = " + converted +    " " + toUnit);
        }
    }
}

UnitConvert.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;

/**
*
 *  This is a test driver for the UnitConverter class
*  Write a unit conversion program that asks users to
*  identify the unit from which they want to convert and
*  the unit to which they want to convert. Legal units
*  are in, ft, mi, mm, cm, m, and km. Define two
*  objects of a class UnitConverter that convert
*  between meters and a given unit.
*
*/
public class RunUnitConverter
{
    public static void main(String[] args)
    {
        BufferedReader br;
        char fromUnit = '\0';
        char toUnit = '\0';
    double value = 0;

    //  prompt the user to enter unit to convert from
        System.out.print("Convert from: ");
    //  open up standard input
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            fromUnit = (char)br.read();
        } catch (IOException ioe) {
            System.exit(1);
        }
    // prompt user to enter unit to convert to
        System.out.print("Convert to: ");
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            toUnit = (char)br.read();
        } catch (IOException ioe) {
            System.exit(1);
        }

    // create new UnitConvert objects
        UnitConverter from = new UnitConverter(fromUnit);
        UnitConverter to = new UnitConverter(toUnit);

    // prompt user to enter initial value to convert
        System.out.print("Value: ");
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            value = Double.parseDouble(br.readLine());
        } catch (IOException ioe) {
        System.exit(1);
       }

        double metric = from.toMetric(value);
       double converted = to.fromMetric(metric);

        if (converted < 0) {
            System.out.println("ERROR: Bad Input");
        }
        else {
        System.out.println(value + " " + fromUnit + " = " + converted + " " + toUnit);
     }
    }
}

This is the errors that I have
The output and error were the following:
javac RunUnitConverter.java
 char cannot be dereferenced
switch (strUnit.charAt(0)){
                           ^
char cannot be dereferenced
 switch (strUnit.charAt(0)){
                           ^
2 errors

A:

Your problem is exactly as the error message says. "strUnit" is of type char, it is not an Object, and thus has no methods.


Q:

JSON parsing on server vs. parsing client side

I'm writing a node app and need to server a bunch of JSON map data. In order for the data to properly show up, it must be parsed.
Now I'm wondering if it's better to parse on the server (and send this parsed data object to the client) or send pure json and have it be parsed on the client side after the ajax call.
My biggest concern with doing it on the server is that many simultaneous queries could slow everything down for a whole bunch of people.
Server side code option:
var data = [];
db.simple_query([{ask: COMPLEX QUERY TO RETURN DATA AS JSON }], function(err, geo_data){
                        if (err) {
                            callback(err);
                        }
                        else{
                            data.push(JSON.parse(geo_data.rows[0].row_to_json));
                            callback();
                        }
                    });

Client side code option:
$.ajax({
                    type: 'GET',
                    url: url,
                    success: function(data){
                        if (data){
                            $.each(data, function(i, geo){
                                L.geoJson(JSON.parse(geo)).addTo(map);
                            });
                        }
                    },
                    error: function(data){
                        //Error Handling
                    }
                });

A:

It really doesn't matter. Compared to a database access (or basically anything that involves network or disk activity) serializing/deserializing JSON is blazingly fast. Don't over-optimize things that do not need optimization.
However, if you want to pass the data to the client without any server-side processing and already get a JSON string it would be pointless to deserialize it on the server and then serialize it again to transmit it to the client which will again have to deserialize it.


Q:

why __init__ is called before object created?

class Point(object):

    def __init__(self, x=0, y=0):
        self.__x = x
        self.__y = y
        print 'point ({x},{y}) created.'.format( x=self.__x, y=self.__y )

class Line(object):

    def __init__(self, start_point=Point(), end_point=Point()):
        print 'Line.__init__ called.'
        self.start = start_point
        self.end = end_point

def test_line():
    p1 = Point(1,1)
    p2 = Point(2,2)
    line1 = Line(p1, p2)

if __name__=='__main__':
    test_line()

When I run this script, it gives the result:
point (0,0) created.
point (0,0) created.
point (1,1) created.
point (2,2) created.
Line.__init__ called.

I don't know why Point.__init() is called before line1 is created.

A:

def __init__(self, start_point=Point(), end_point=Point())

Default function parameters are members of the function itself and are created when the function is defined, not at runtime. So each instance of Line uses the same start and end
The common way to work around this is set them by default to None:
def __init__(self, start_point=None, end_point=None):
    if start_point is None:
        self.start = Point()
    if end_point is None:
        self.end = Point()


Q:

Tab bar and Mapview issues

I'm really confused about this issue. I have recently been having issues with my mapview tab in my application. Even to the point of starting over again. I'm just wondering if I am the only one having this issue or am I doing something wrong here.
I am fairly new to iOS but I know how to define a mapview's center and span in order to center on the user's location.
I've built this in its own view and it seems to work but when I put it in a tab controller...I have an issue. The map stays zoomed out while showing the user's location.  It's supposed to show the user's location zoomed in.
My MapViewController:
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.mapView.delegate self];
    [self.mapView setShowsUserLocation:YES];
    // Do any additional setup after loading the view from its nib.
}

-(void)mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
    CLLocationCoordinate2D loc = [userLocation coordinate];
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 500, 500);
    [self.mapView setRegion:region animated:YES];
}

I also thought it could have something to do with the way I created the tab controller in the delegate.
My app delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController *viewController1 = [[NWSWelcomeViewController alloc] initWithNibName:@"NWSWelcomeViewController" bundle:nil];
    UIViewController *viewController2 = [[NWSMapViewViewController alloc] initWithNibName:@"NWSMapViewViewController" bundle:nil];
  //  UIViewController *viewController3 = [[NWSSettingsViewController alloc] initWithNibName:@"NWSSettingsViewController" bundle:nil];
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.viewControllers = @[viewController1, viewController2, /* viewController3 */];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

I am writing for iOS 5.1 and I am using the latest Xcode.
Yes, I have the settings for zooming enabled on the mapView.
I just want to get the user location to zoom in the mapview to the user's location.

A:

This line in viewDidLoad:
[self.mapView.delegate self];

does nothing (it is trying to send the message self to self.mapView.delegate).
It doesn't actually set the map view's delegate and so the didUpdateUserLocation never gets called.
What you probably meant was:
[self.mapView setDelegate:self];

or this:
self.mapView.delegate = self;


Q:

Student's t-test with a covariate?

I am testing the different between some variables $X$ and $Y$ using the Student's t-test. I suspect that there might be a latent variable $Z$ that has an effect on both $X$ and $Y$. How could I control $Z$?
I am using Python for the data analysis.

A:

One common means of controlling for some other covariate would be via regression. Put the X and Y values into the response (DV), and a Y-group indicator (0 if in X, 1 if in Y) as a DV, along with your covariate (or some suitable proxy for it if the variable can't be measured directly) as another DV.
You regress on your covariate and the group-indicator. If there's a difference between X and Y based on the covariate, this will be "adjusted" for by the regession, and significance of the coefficient of the group-indicator will then be a test of a mean-shift between the two groups after accounting for the covariate.

This is sometimes called ANCOVA (unless Z is a factor, in which case it would usually be called ANOVA; you can still do it using regression).
Some people would formally test parallelism of the two group-lines (by including an interaction between covariate and group-indicator). I think that's wrong-headed (do we believe the hypothesis of no-interaction is exactly true? I don't -- in which case the hypothesis test is a noisy answer to a question we already know the answer to -- surely they're never going to be exactly parallel) ... but don't especially care about. The better question here is "are they close enough to parallel that it doesn't badly impact the properties of the inferences we wish to make?'. Answering that is nearer to measuring an effect size, so a residual display - e.g. residuals vs covariate that distinguishes the groups with symbols or colors - might come closer to addressing that.

However, depending on what you mean by 'latent' in your question, it's possible that you may actually be after something more like an instrumental variable. (There are numerous questions on site on the topic.)

A:

By means of t-test you are assessing whether there is a significant difference between two sets of data --- e.g. the realizations of two random variables $X$ and $Y$. When using t-test you are doing a hypothesis test, and you can't control for any variable. To be more specific, when doing hypothesis tests you are not establishing any causal relationship between random variables.
If you want to investigate the effect of a latent variable $Z$ on both $X$ and $Y$, you should rely on a regression analysis. For a deeper analysis on the role and effects of some variables (which can cause a bias in your analysis), you can apply some methods of graphical models.
Here you find a nice IPython Notebook on regression.


Q:

ModelMapper flatten array property (get(0)) to String?

Src object has a property:
private List<Pojo> goals;

Dest object has a property
private String goal;

I want to map Src.goals.get(0).getName() -> Dest.goal. goals will always contain one item, but it has to be pulled in as a list because its coming from Neo4j.
I tried doing:
    userTypeMap.addMappings(mapper -> {
        mapper.map(src -> src.getGoals().get(0).getName(), UserDto::setGoal);
    });

But modelmapper didn't like the parameter. Then I tried:
    userTypeMap.addMappings(mapper -> {
        mapper.map(src -> src.getGoals(), UserDto::setGoal);
    });

And that gave me:
"goal": "[org.xxx.models.Goal@5e0b5bd8]",

I then tried to add a converter for List -> String, but that didn't get called. If I add a converter for the entire pojo to dto then I have to map the whole pojo which I don't want to do, I just want to override this one property.

A:

You can wrap the List access in a Converter and use this in a PropertyMap like follows:
ModelMapper mm = new ModelMapper();
Converter<List<Pojo>, String> goalsToName =
    ctx -> ctx.getSource() == null ? null : ctx.getSource().get(0).getName();
PropertyMap<Src, Dest> propertyMap = new PropertyMap<>() {
    @Override
    protected void configure() {
        using(goalsToName).map(source.getGoals()).setGoal(null);
    }
};
mm.addMappings(propertyMap);


Q:

How to read required values from a list and store it in csv using python?

I have a response in the list format. I have to read the list and store only required values in CSV file in ';' separated values.
 row = "[('Employee', 'Shift', 'IT', '5:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'IT', '6:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'CALL CENTER', '7:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'CALL CENTER', '8:15AM', 'Server', 'Manager', 'empemail@cmp.com')]"

Now I need to store the list in CSV file in the below expected  format.
param_Name,Param_Value
p_Name,Employee
p_operationType,IT;IT;CALL CENTER;CALL CENTER
p_Time,5:15 AM;6:15 AM;7:15 AM;8:15 AM
p_avaiablity,Daily
p_email,empemail@cmp.com

I am trying in pandas.
 import csv
 import pandas as pd
 df = pd.DataFrame(data=row).T
 df.to_csv('csvfile.csv',sep=';',index=False,header=False)
 print(df)
 for item in df:
    print(item)
    #Stuck on how to proceed further...

With this code I am geting a csv file as
param_Name,Param_Value
p_name,Employee;Employee;Employee;Employee
p_avaiablity,Daily;Daily;Daily;Daily

How can I iterate into the list and get only required values and store as expected format?

A:

Hope this helps
import pandas as pd

row = [('Employee', 'Shift', 'IT', '5:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'IT', '6:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'CALL CENTER', '7:15AM', 'Server', 'Manager', 'empemail@cmp.com'),('Employee', 'Shift', 'CALL CENTER', '8:15AM', 'Server', 'Manager', 'empemail@cmp.com')]

# use dataframe constructor properly and name your columns
cols = ['Employee', 'Dont_know_what_this_is', 'department', 'time', 'location', 'status', 'email']
df = pd.DataFrame.from_records(row, columns=cols)

for index, row in df.iterrows():
    # do what you want with your data
    print(row)

# or use 'loc' function to get specific columns
df = df.loc[df.department == 'IT']
print(df)
# then export your csv
df.to_csv('csvfile.csv',sep=';',index=False,header=False)

Outputs:
    Employee Dont_know_what_this_is   department    time location   status             email
0  Employee                  Shift           IT  5:15AM   Server  Manager  empemail@cmp.com
1  Employee                  Shift           IT  6:15AM   Server  Manager  empemail@cmp.com
2  Employee                  Shift  CALL CENTER  7:15AM   Server  Manager  empemail@cmp.com
3  Employee                  Shift  CALL CENTER  8:15AM   Server  Manager  empemail@cmp.com

After loc:
Employee Dont_know_what_this_is department    time location   status             email
0  Employee                  Shift         IT  5:15AM   Server  Manager  empemail@cmp.com
1  Employee                  Shift         IT  6:15AM   Server  Manager  empemail@cmp.com


Q:

uml-include or extend

I am trying to make a use case diagram for library management system. I have two actors admin and user.
Now, the admin has three functions manageCategories (of books like history, geography etc.) manageUser and manageBooks..
What I am doing is considering these 3 functions in a single function manage i.e manage is a single use case.
How should I consider the three functions managerUser, manageBooks, manageCategories in the diagrams?
Should I use include or extend the three functions in a single use case manage, or use anything else?

A:

Edited after the corrects comments of @vainolo about the included use case confusion in my answer:
If the manage use case needs the callable use cases (managerUser, manageBooks, manageCategories) in order to make sense (produce value) for the main actor, then you should use the include relationship.
If the actor can complete the manage use case executing zero or all three of the callable use cases (managerUser, manageBooks, manageCategories) then you should use the extend relationship and you may specify the extension point conditional statements for them.
If the manage use case is a container used to organize the three callable use cases which can be executed independently, then I'd modelize manage as a  Use Case Package containing the three use cases rather than a use case per se.

Please find the following excerpt from that post about the NOT mandatory execution of an included use case (as correctly pointed out by @vainolo):

Point 5: Inclusion use cases may be optional
A UML superstructurestatement Section 16.3.5 of 2 states:
“Note that the [inclusion] use case is not optional, and is always
required for the [base] use case to execute correctly.”
Cause for confusion
Some seem to interpret this to mean that an inclusion use
case must be performed during each and every execution of a base use
case.
Nothing is further from the truth and the truth is simple.
The simple truth
Whether an inclusion use case is mandatory or
optional to a base use case depends on where in the base use case the
fragment was defined that is now replaced with an include statement
for the inclusion use case.
If that fragment was part of the base use case’s unconditional flow
(steps that always get executed), the inclusion use case is mandatory.
If that fragment was part of a conditional flow (steps that get
executed optionally), the inclusion use case is optional.
So what does the UML statement mean?
The purpose of the UML statement seems to
be to contrast the include relationship with the extend relationship,
as follows.
At an extension point (not for the entire base use case), the
extension use case’s execution is optional.
When the execution of a base use case reaches an extension point, an
extension use case may or may not be inserted, because there may be a
condition attached to the extend relationship. However, at an
“inclusion point” (not for the entire base use case), the inclusion
use case’s execution is mandatory.
When the execution of a base use case reaches an inclusion point
(i.e., an include statement in the base use case), the inclusion use
case will always be performed, because there is no provision for
attaching a condition to the include relationship.


Q:

How to loop json format array variable in javascript

This is my code, using for marking all places that I fetched from my database in google map.
 $.ajax({
        url:"http://localhost/church_finder/index.php/MapController/search_church",
                type:'POST',
                data:{coordinates:coordinates}
                 success: receiver
               });

Here I call the function receiver with the result I got from the database.
function receiver(data, textStatus, XMLHttpRequest) {

var json = JSON.parse(data);

var features = [
            for( var i=0; i<json.length; i++) {
            var lat=json[0]["lat"];
            var lng=json[0]["lng"];
                {
                    position: new google.maps.LatLng(lat,lng),
                },
            }
            ];

     features.forEach(function(feature) {
                var marker1 = new google.maps.Marker({
                    position: feature.position,
                    map: map
                });
            });
}

This is the result data I getting from ajax

[{"lat":"10.526800731337735","lng":"76.20941162109375"},
  {"lat":"10.622100079463674","lng":"76.1424207687378"},{"lat":"10.604004340704408","lng":"76.14100456237793"},{"lat":"10.608644375798574","lng":"76.13735675811768"},{"lat":"10.624419968495433","lng":"76.13675594329834"},{"lat":"10.62436724394038","lng":"76.13685250282288"},{"lat":"10.624377788852131","lng":"76.13693833351135"},{"lat":"10.615815200680679","lng":"76.1367130279541"},{"lat":"10.601726479547619","lng":"76.13688468933105"},{"lat":"10.610500370131295","lng":"76.13244295120239"},{"lat":"10.631991120088175","lng":"76.13566160202026"}]

but when am using forloop inside var feature I got error like this "Uncaught SyntaxError: Unexpected token for". How can i loop and mark all this coordinate in google map.

A:

This is your approach
var json = JSON.parse(data);

var features = [
    for( var i=0; i<json.length; i++) {
    var lat=json[0]["lat"];
    var lng=json[0]["lng"];
        {
            position: new google.maps.LatLng(lat,lng),
        },
    }
    ];

features.forEach(function(feature) {
        var marker1 = new google.maps.Marker({
            position: feature.position,
            map: map
        });
    });
}

There are some issues in your code
You're trying to execute a for-loop within both brackets []
var features = [
    for( var i=0; i<json.length; i++) { <- Here
    var lat=json[0]["lat"];
    var lng=json[0]["lng"];
        {
            position: new google.maps.LatLng(lat,lng),
        },
    }
    ];
    ^

You're always itetaring with position 0
var lat=json[0]["lat"];
var lng=json[0]["lng"];
             ^

You have an expression that never was assigned to a variable:
{
    position: new google.maps.LatLng(lat,lng),
},
^

Look this code snippet with those fixes
var json = [{"lat":"10.526800731337735","lng":"76.20941162109375"}, {"lat":"10.622100079463674","lng":"76.1424207687378"},{"lat":"10.604004340704408","lng":"76.14100456237793"},{"lat":"10.608644375798574","lng":"76.13735675811768"},{"lat":"10.624419968495433","lng":"76.13675594329834"},{"lat":"10.62436724394038","lng":"76.13685250282288"},{"lat":"10.624377788852131","lng":"76.13693833351135"},{"lat":"10.615815200680679","lng":"76.1367130279541"},{"lat":"10.601726479547619","lng":"76.13688468933105"},{"lat":"10.610500370131295","lng":"76.13244295120239"},{"lat":"10.631991120088175","lng":"76.13566160202026"}];

var features = [];

for (var i = 0; i < json.length; i++) {
  var lat = json[i]["lat"];
  var lng = json[i]["lng"];

  features.push({
    position: new google.maps.LatLng(lat, lng),
  });
}

features.forEach(function(feature) {
  var marker1 = new google.maps.Marker({
    position: feature.position,
    map: map
  });
});

Resources

Loops and iteration


Q:

Altium pin error

I'm a beginner with Altium Designer 17.1 and I'm facing difficulties. I'm designing a PCB but when I compile the project this error is shown.

I'm using ports, they are set on global.
Also, I'm having another problem. I made a NMOS Schematic and this error is shown :

I made the pins and everything worked fine (this error isn't shown in the compilation, only the error above) but when it comes to the PCB, they are implemented on the PCB but aren't linked to other components.
Thank you for your help.

A:

First and foremost: Always make sure to hit Project -> Recompile instead of Project -> Compile (Recompile will take all sheets into account, not only the one you're working on). The first error should disappear. If not, make sure that the pins are actually connected (can be an issue when you're designing in a metric system for the schematic as Altium will usually use DXP units (which are imperial). Also let us know your settings in the project properties (Hierarchical, Automatic, ...).
As for the second issue. You need to match the Pin designator. Your schematic symbol probably has Pin Designators 1,2,3; your PCB symbol probably has Pin Designators (well, actually Pads) labeled G,S,D ... you need to choose one over the other. Those must match.


Q:

EF Code first Eager loading problem

I have two entities in 1:n relationship: Category and Product.
public class Category
{
   public int CategoryID { get; set; }
   public string CategoryName { get; set; }

   public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
   public int ProductID { get; set; }
   public string ProductName { get; set; }

  public virtual Product { get; set; }
}

public class context : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

I want to load products in every category by Eager loading.
context.Categories.Include(c=>c.Products)

but Include do not load any navigation property. it accept only one parameter called "path" typed string.

A:

Are you missing a using? VS 2010 is a bit dumb on this one and you often have to explicitly put in:
using System.Data.Entity

..to get the lambda include option available.
It won't prompt you to add it as it already has a string based definition for Include available under
System.Linq

.Include(x => x.MyObject) is actually a new extension method for the existing linq method.


Q:

Dynamically loaded Masonry images are overlapping

I'm using the jQuery plugin Masonry to load images on my site, but the majority of the time a lot of them are overlapping. I have found this to be a popular problem with the plugin and have tried various solutions, but still haven't gotten it working properly. This is what I have so far.
HTML

  {% for article in blog.articles %}

      {{ article.content }}

  {% endfor %}

JS
$(window).load(function(){
  var $container = $('#container');
  $container.imagesLoaded(function(){
    $container.masonry({
       itemSelector: '.item',
       isAnimated: true,
    });
  });
});

CSS
#container {
  position: relative;
}

.item {
   margin: 10px;
   width: 25%;
}

EDIT

A:

Replacing the jQuery above with this fixed the problem:
$(window).load(function(){
  var $container = $('#container').masonry();
  // layout Masonry again after all images have loaded
  $container.imagesLoaded( function() {
    $container.masonry();
  });
});


Q:

PHP Post Array Not Working (JSON)

I'm attempting to POST a JSON string that I grab from a MySql database to another php page. Here's my code for the parent page:
$ResultLists = array();
$counter = 0;
echo "<form target=\"_blank\" enctype=\"multipart/form-data\" method=\"post\" action=\"_popup.php\" name=\"compare\">";

while($data != NULL and $info = mysql_fetch_array( $data ))
{
Print "
";
//..
//I printed some data here, but not relevant to problem
//..
$ResultLists[$counter] = $info['ResultList']; //gets JSON string
echo gettype($ResultLists[$counter]); //prints "string"
//echo $ResultLists[$counter]; //prints the whole list (it is a list of lists <--from python)
$var = json_decode($ResultLists[$counter]); //decode JSON string
echo $var[1][0]; //prints wonderfully (I am only printing one value in "array", but it works).

Print '<input type="checkbox" name="data[]" value="'.$ResultLists[$counter].'" />	';
Print '
';
$counter++;
}
echo '
<input type="hidden" name="index" value="'.$counter.'" />';
echo '<input type="submit" value ="Compare Data"> </input>
';

On the child page, I try to get the data:
<?php

$index = $_POST['index'];
echo 'Number of rows: '.$index.'
';
$array = $_POST['data'];

$x = 0;

//echo gettype($array);

echo 'Type: '.gettype($array[$x]).'  Length: '.strlen($array[$x]).'  Data: '.$array[$x].'
';
$var = json_decode($array[$x]);
echo gettype($var).strlen($var);
echo $var[1][0];

?>

Which produces (for example)
Number of rows: 8
Type: string Length: 2 Data: [[
NULL0

So, it doesn't work. (It does this for every row of data I have submitted, so varying $x results in same output as long as its in the range of number of checkboxes I selected, if that makes sense.) Any ideas? Why does it show up as "[[" instead of the entire list? I can print the whole list on parent page and it works fine.
I have a suspicion its due to the presence of single quote " ' " characters, or something. Any ideas?
Edit:
So disabling magic quotes seems to have helped me post.
However, I'm having a strange issue, where it somehow submits all my data.
So when I get back data[] via POST, the length is the correct number of checkboxes that were checked, but the data it holds starts from the first row that is printed. Any ideas?

A:

You may probably want to escape the HTML characters in the json-ized string using htmlspecialchars. I.e.,
Print '<input type="checkbox" name="data[]" value="'.htmlspecialchars($ResultLists[$counter]).'" />	';


Q:

Kubernetes Readiness Probe in multi-tenant system

I am designing a system with a single kubernetes deployment for multiple tenants, but there are multiple databases, queues etc. per customer. Anything stateless is shared, and anything with state is separate for each tenant. Based on the request host (tenant1.company.com or tenant2.company.com), the code will connect to the corresponding databases and queues.
How should readiness probes be designed in this case, where my pod is designed to work for multiple tenants?
I can think of the following options, none of which seem correct:

Connect to all databases and queues and see if they are ready:
Disadvantage: this will cause pod to be not ready even if one
resource is down.
Connect to any one database and queue: Disadvantage: doesn't really check the readiness for all probes.
Do not have any readiness probe at all.

It feels like if I have separation at resources level to support multiple tenants (this is a B2B multi-tenant, takes time and effort to onboard new tenant), I also need to have separation at Kubernetes deployment level.
Is this the standard approach - either have complete separation at all levels, or have one single unified system with same shared resources? If not, how do I design the readiness probes?

A:

As per my understanding, you are trying to extend Kubernetes Pod's readiness probe to reflect Application health for specific tenant. Unfortunately, Readiness probe is not designed for that.
The only purpose of Kubernetes readiness probe (even the new feature Pod Ready++) is to reflect the certain Pod ability to serve the traffic. Deployment and StatefulSet controllers take into account Pod readiness state during the rolling-update process.
You can brake the whole update mechanics if you set the readiness probe to depend on external to the Pod components or a network endpoints connectivity.
 The correct way of using Readiness probe is to check only the Pod's internal components' conditions.
Kubernetes documentation pages:

Define readiness probes
Pod conditions and Container probes
Pod Ready++

For certain simple application or microservices that only contains one Pod, it may reflect also the state of the application. But usually, application architecture is much more complex and contains many parts, each of which may have dependencies.
Sometimes it's cheaper and simpler to create your own health check loop in the frontend app (www.example.com/healthz) that reflects the whole App health, taking to account all its components statuses and their dependencies, or collect and aggregate JSON statuses from other components.
In Kubernetes world, components/apps are usually Services that balance the traffic to one or more Pods. Thus, a component is healthy if at least one Pod behind the corresponding Service is in Ready state. The number of Ready Pods behind the Service tells more about App Performance, than about the App Health.
As per my ability to imagine your App design:

I would use several Ingress objects that make the traffic to be forwarded to the dedicated for each tenant frontend, in the tenant's Namespace. All other tenant's resources are also deployed there.
All shared components I would put in the additional Namespace, let's say "shared/static/commmon/stateless" and create ExternalName service in each tenant's Namespace to access them (or Ingress if I would serve this content on a specific URL path).
I would also deploy some solution for Application+cluster monitoring.

This way you can easily scale application parts if some tenant needs more resources.
To manage deployments I would use Helm charts. This way I can easily deploy one more tenant or remove/update the existing one.
There are many different solutions to monitor an Application Health, Performance, collect metrics and logs and take actions if certain conditions are met. It's just a brief list of most popular solutions:

Metrics Framework (Java)
Prometheus
EFK stack
Jaeger
Istio
Weave Scope
Datadog Realtime Kubernetes Monitoring
Cloud specific tools like Google Cloud's operations suite (formerly Stackdriver)
many more...

PS: In case you want to implement a circuit breaker for the tenants, Istio has built-in functionality.


Q:

How can I clear remote repository in git?

I want to clear the remote repository and push the new files.
I' am getting
git commit -m "fix"
# HEAD detached from 0027561
nothing to commit, working directory clean

and nothing is pushed to the remote.
I tried to git init, but it didn't work.
How can I do that?

A:

You can make a new branch
git checkout -b newBranch
git push -u origin newBranch

If you want to update an existing branch like master, you can rebase that new branch on top of master:
git rebase master
git checkout master
git merge newBranch
git push heroku master

I prefer that to directly checkout master, or to force master to the new branch (git branch -f master newBranch), because it takes into account the case where new commits were done on master concurrently (meaning "while commits where done with the detached HEAD")


Q:

sorting alphabetically after stripping "the, a, an" only working partially

Trying to hack apart an annoying bug here.
We have a regex which correctly strips off leading articles like "a", "the", etc.   It also sorts alphabetically fine for some of the entries, but not for the rest.   What happens is we get a list where some of the listings with these articles are embedded properly within the output, and then it gets to the end and starts over, with those entries correctly sorted among themselves.
Here's an example of how it's appearing

Apple
Banana
The Carrot
The Grapefruit
Kiwi
The aardvark
The emu
A zebra

As you can see, it does fine at first, but then gets to the end and starts over with only those items with articles.  I've looked at the data, and can't find any consistencies that would explain the variation.
Here's the regex comparison (in an entity called Bibliography)
    public static function compareTitles(Bibliography $a, Bibliography $b)
{
    $ignored_word_regex = '/^(the|a|an)\s/i';
    $tag_quote_regex = '/"?(\<\/?[a-zA-Z]+\>)?/';
    $a_test = preg_replace($ignored_word_regex ,'', $a->getTitle());
    $a_test = preg_replace($tag_quote_regex, '', $a_test);
    $b_test = preg_replace($ignored_word_regex ,'', $b->getTitle());
    $b_test = preg_replace($tag_quote_regex, '', $b_test);
    return strcmp( $a_test,
                   $b_test);
}

This is being pulled in from an entity called Review
    /**
 * @param Review $a
 * @param Review $b
 *
 * @return boolean
 */
public static function compareTitles($a, $b)
{
    return \Entity\Bibliographies\Bibliography::compareTitles($a->getBiblio(), $b->getBiblio());
}

This is then sorted in the controller using these two methods:
    public function exportIndexTitleAction( Request $request ){
    $response = $this->renderExportXMLSorted(
        'Review:Export/index_title.xml.twig',
        $request,
        array('Entity\Reviews\Review', 'compareTitles'));
    return $this->setExportHeaders($response, date("o-m-d-")."index_title.txt");
}

and using a uasort:
    protected function renderExportXMLSorted($template, Request $request, $sort_method, $filter_method = null){
    $reviews = $this->getReviewsFromRequest($request);
    if ($filter_method != null)
        $reviews = array_filter($reviews, $filter_method);
    uasort($reviews, $sort_method);

    return $this->renderExportXML($template, $reviews);
}

I've been digging through this and cannot figure what causes it to stop and start over again. I can get it to sort fine if it treats "the" and "a" as they are, but they really need to be stripped, but also be displayed.  (yes, it would be easier to simply remove them, but they need to remain).
I'm thinking there's something in the regex that I'm missing...

A:

Obviously the problem is case.  You need to use strcasecmp to treat both cases the same.  You could also strtolower or strtoupper both before the compare.
 Also, that is a lot of code that can be boiled down to something simpler:
uasort($array, function($a, $b) {
                     $p = '/^(the|a|an)\s/i';
                     $a = preg_replace($p, '', $a);
                     $b = preg_replace($p, '', $b);
                     return strcasecmp($a, $b);
               });


Q:

How can I set a conditional function argument value here?

I want to automatically set the value of an argument in a function based on another argument's value.
More specifically, I want to set a timezone value (offset) to automatically adjust time values given the region.
However, my implementation doesn't seem to work (as in the offset is never applied unless I specifically pass it as an argument to the function).
Part of the function (is supposed to) set the offset value based on region's value, and also connect to the corresponding Elasticsearch server.
This is what I have:
if (region == "EU") {
    offset = "+00:00:00"
    # Code to connect to EU ElasticSearch server
  } else if (region == "US") {
    offset = "-06:00:00"
    # Code to connect to US ElasticSearch server
  } else {
  paste0(stop("Incorrect region supplied: ", region))
}

The function:
time_function <- function(region, retailer, start_date, end_date, offset = "+00:00:00"){
    # Function body
}

(Note that I have set the default value of offset to "+00", otherwise it will throw an error that the argument is missing.)
Clearly I have gone wrong somewhere because the offset is never applied unless I explicitly specify in the argument list.
This is what I want to do:
If region == "US", then set offset to "-06:00:00",
Else if region == "EU", then set offset to "+00:00:00"
Else Error message: "supply valid region"
In short, I am looking to set a conditional argument value.
How can I achieve this?

A:

It turns out I made an oversight in the order of assignment implementations and have just now spotted it.
For those who might be experiencing similar problems, it might be worth highlighting where I went wrong: I set the offset value after it was used, meaning that it was used/processed (using the previous iteration's value) and then it was assigned the new value.
In short, my implementation was completely correct but the order of events was incorrect.
Therefore, make sure that you set the required values before they are processed.


Q:

Filter node by custom_field in admin panel

I'm using Drupal 7, Views and Panels. Created a content type and custom field (field_list) And showing contents by list on my site. Thanks Views :) But when i click find content in admin panel, many many contents in my area.
Can i add filter option by field_list in my admin panel? Is it possible?

A:

You need to install Admin views module. It will replace administrative overview/listing pages with actual views for superior usability. Now, you can override your views for admin panel for filter content by field_list.


Q:

How can I upload a file via php?

I try to make a simple file uploader in php, but I fail already at the beginning.
This is the tutorial:
https://www.youtube.com/watch?v=PRCobMXhnyw
So at the beginning I should make a file index.html:
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>File upload</title>
    </head>
    <body>
        <from action="upload.php" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="upload">
        </form>
    </body>
</html>

and an upload.php:
<?php
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];
    print_r($file);
}

When I upload the file I should see on my screen:
Array ([name] => uploadme.txt [type/plain [tmp_name] =>
/Applications/MAMP/tmp/php/phpXkZIVD [error] => 0 [size] => 9)

But it is not working. If i click on "upload" there is just nothing happen. What am I doing wrong?

A:

Mistake :
You are having typo in the <form
<from action="upload.php" method="post" enctype="multipart/form-data">
It should be as
<form action="upload.php" method="post" enctype="multipart/form-data">
It prevents you to submit the form
What you should do :
You're just printing the uploaded file, but you should move it to some folder like this.
$target_file = 'upload/'.basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);

Note :
You should create a folder named as upload and it should have read/write permission.
So, Your code should look something like this
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>File upload</title>
    </head>
    <body>
        <form action="upload.php" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="upload">
        </form>
    </body>
</html>
<?php
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];
    print_r($file);
    $target_file = 'upload/'.basename($_FILES["file"]["name"]);
    move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
}
?>


Q:

Relational Database MYSQL/PHP

I am building a classified ads website, similar to craigslist.
The site is divided in to several sections; i.e. Forums, For Sale, Services Offered, etc.
Under each Section there are several [categories], i.e.Forums[pets], Forums[Books], For Sale[barter], Services[Barter], etc. (Notice that some categories are only uniquely identified by their section, such as in the case with barter and barter from two sections "For Sale" and "Services".)
Users will post to the categories from post links within each section. Users can upload photos and select certain amenities for their products, if applicable. A forum post will not need an amenity attribute whereas a Vehicle Ad might. Amenities include: auto transmission for vehicle ads, or furnished for housing rentals.
I am trying to figure the best logical setup for the database schema.
Currently I have this type of logical structure for basic input/query:
SECTIONS TABLE- section_id, section
CATEGORIES TABLE- cat-id, category, section_id(foreign key)
AMENITIES TABLE- amen_id, amenity
PHOTOS TABLE- photos-id, file

POST TABLE- post_id, category, timestamp, description

SECTION_POST TABLE- section_id, post_id
POST_AMENITY TABLE- post_id, amenity_id
POST_PHOTO TABLE- post_id, photo_id

I made the [SECTION_POST] my main many-to-many because the category in the [POST] must be related to the section. I related CATEGORY to SECTION in the categories table, which looks to me like a M-to-M with the addition of category attribute. Is this ok?
Also, do you have any other suggestions as to how i should be thinking on this schema? I think the problem I am having is mostly related to ignorance not lack of organizational skills.  Maybe one of you can educate me or refer me to a decent link that tackles my general problem.

A:

Your design is fairly standard.  Here's a couple of comments, and some things to consider:

For your keys where you have an implied dependent relationship
(SECTION_POST for example) many ORM libraries have issues with
dependent relationships and the resultant concatenated keys.  There's
also the issue of key allocation.  For both of those reasons, many
people will instead give that table its own independent key (which
can conveniently be made AUTO_INCREMENT) and move the original PK to
foreign keys.
In terms of SECTION/CATEGORY, only you can say how important of a concept/entity SECTION is, however the obvious questions would
be,    how is a SECTION in any way different from a CATEGORY.  You
could    have the same structure, with even more flexibility by
having only    CATEGORY with a self referencing "PARENT_CATEGORY_ID"
column.  This    would allow you to define a tree structure of
categories, while at    the same time, it's simple to get the top
level categories using IS    NULL on the PARENT_CATEGORY_ID.
I'm not clear on how you plan to relate photos to a POST, but it would be nice from a design standpoint to support a M-M
relationship    so that you can have multiple photos for a single
post.

Otherwise, you seem to have a good handle on relational design basics.  I do a lot of database design, and prefer to use a commercial erd design tool, but there are some free options like Mysql workbench (assuming you're designing for mysql) that can help you visualize your design, and insure that all the SQL DDL is correct.  It's also nice to have documentation for the development phase of your project.


Q:

Maven Dependency's dependency

In my project I have slf4j-log4j12

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
    <scope>test</scope>
</dependency>

This version uses log4j 1.2.17. The log4j latest update is 2.11.1.
How can I make my maven project to force use the latest log4j i.e. 2.11.1 version?

A:

Be aware that log4j version 2 is completely incompatible with log4j version 1. You cannot replace like that those version.
To use log4j-2 as backend for slf4j, you will need to replace this dependency by another.
From the page in log4j 2 site, the dependency is linked to the version of slf4j
In your use case, (sf4j 1.7) it is this one:
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.11.1</version>
    <scope>test</scope>
</dependency>

for slf4j 1.8+ it will be this one:
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j18-impl</artifactId>
    <version>2.11.1</version>
    <scope>test</scope>
</dependency>


Q:

Ruby Variation with repeating buggy method

I need a method written in Ruby, which computes Variations. I have already written it in Java, but as I'm new to Ruby, there's just something I'm missing about the Ruby implementation.
The method is suposed to do this:
method(1, "01") => ["0", "1"]
method(2, "01") => ["00", "01", "10", "11"] ...so you get the idea.
note: in the Ruby impl, i give paralms like this : method(2, ["0", 1"]), but that's not an issue.
My Java impl :
public static List<String> Variations(int strength, String usableChars) {
    List<String> list =
        new ArrayList<String>((int) Math.pow(usableChars.length(), strength));

    if (strength == 0) {
        list.add("");
    } else {
        List<String> l = Variations(strength - 1, usableChars);
        for (char c : usableChars.toCharArray()) {
            for (String s : l) {
                list.add(c + s);
            }
        }
    }
    return list;
}

And it's working fine. But this is my Ruby implementation:
def Variation (strength, arrayOfString)
    array = Array.new(arrayOfString.size**strength)

    if strength == 0
        array << ""
    else
        a = Variation(strength-1, arrayOfString)
        for i in arrayOfString do
            for j in a do
                array << (i + j)
            end
        end
    end
    return array
end

In this i keep getting error message test.rb:10:in `Variation': can't convert nil into String (TypeError).

A:

In Ruby, arrays grow automatically as needed.  So change your array initialization from:
array = Array.new(arrayOfString.size**strength)

to
array = []

To enumerate over each character in a string, instead of
for i in arrayOfString do

do this:
arrayOfString.each_char do |i|

The final result:
#!/usr/bin/ruby1.8

def Variation (strength, arrayOfString)
  array = []
  if strength == 0
    array << ""
  else
    a = Variation(strength - 1, arrayOfString)
    arrayOfString.each_char do |i|
      for j in a do
        array << (i + j)
      end
    end
  end
  return array
end

p Variation(2, '01')    # => ["00", "01", "10", "11"]

each_char is in Ruby >= 1.8.7, or you can get it from the backports gem.


Q:

Link two Scatter charts in Bokeh

Based on the Bokeh docs, it is possible to link two scatter plots created using the plotting interface:
s1 = figure(plot_width=400, plot_height=400, title=None, tools=TOOLS)
s1.circle(x='Elevation', y='Aspect', source=src)

s2 = figure(plot_width=400, plot_height=400, title=None, tools=TOOLS)
s2.circle(x='Elevation', y='Slope', source=src)

However, I'd like to do this with the Scatter chart, so that I can take advantage of automatic styling (e.g. colouring by a 3rd column). Is this possible? What I have right now, which doesn't work, is:
s1 = Scatter(df_samp, x='Elevation', y='Horizontal_Distance_To_Roadways', color='Cover_Type', plot_height=400, plot_width=400, source=src, tools=TOOLS)
s2 = Scatter(df_samp, x='Elevation', y='Aspect', color='Cover_Type', plot_height=400, plot_width=400, source=src, tools=TOOLS)

A:

The bokeh.charts API, including Scatter has been deprecated and removed. The first code above, using the stable and supported bokeh.plotting API is the correct way to proceed in all cases now and in the future.
If you want to colormap based on additional columns, this is possible using various transforms:
https://docs.bokeh.org/en/latest/docs/user_guide/data.html#transforming-data


Q:

cut-off line of asp.net treeview

I have an ASP.NET TreeView and need set ShowLine "true" when I define its style.
However, the treeview's lines will be cut-off.
I tried this tutorial, but it didn't help.
.tree
{
      font-size: 40px;
      height: 40px !important;
 }

<asp:TreeView ID="TreeView1" runat="server" ShowLines="True" CssClass="tree">
    <Nodes>
            <asp:TreeNode Text="test1" Value="1">
                <asp:TreeNode Text="test1.1" Value="11"></asp:TreeNode>
            </asp:TreeNode>
            <asp:TreeNode Text="test2" Value="2">
                <asp:TreeNode Text="test2.1" Value="21"></asp:TreeNode>
            </asp:TreeNode>
        </Nodes>
    </asp:TreeView>

A:

Did you try the styles mentioned in the example itself? you are missing td div in the style
.tree td div {
   height: 20px !important
}

That will work. Note that setting 40px is not going to work directly as it seems the vertical line image used within the div is of 20px height; hence you will need to implement your own ways if you want to change that. This would also affect the expand/collapse icon on the tree nodes.
.tree td div {
       height: 40px !important
    }

EDIT
The default images used are 20 x 20 pixels in size. to set your own set of images, you need to set LineImagesFolder property of the tree view (by doing this you will be providing your own set of images). Have a look at this MSDN Link


Q:

How to assign an incremental column name for a pandas.core.series.TimeSeries?

I have pandas.core.series.TimeSeries with the random number column name, how can I assign an incremental name to it? (starting from 1 and end with len(pandas.core.series.TimeSeries))
I have find s.rename function for it but how to assign an incremental name for using lambda?
Here is the pandas.core.series.TimeSeries:
3125    1474
3126    1474
3127    1474
3128    1474
3129    1474
3130    1474
3131    1474
3132    1255
3168    1090
3169    1474
3170    1474
3171    1206

and I want to rename it as follow:
    1    1474
    2    1474
    3    1474
    4    1474
    5    1474
    6    1474
    7    1474
    8    1255
    9    1090
    10    1474
    11    1474
    12    1206

A:

You can assign range to Series:
s.index = range(1,len(s) + 1)
print (s)
1     1474
2     1474
3     1474
4     1474
5     1474
6     1474
7     1474
8     1255
9     1090
10    1474
11    1474
12    1206
Name: a, dtype: int64

But if need assign columns names - TimeSeries are rows in DataFrame:
df.columns = range(1,df.shape[1] + 1)


Q:

how to change single li element in a menu using lists?

I created a navigation bar at for my website using an in-line list and then it has been styled. Each
 is exactly the same but I want the last one to have a different size as i wish to change the width and padding of it.
I have no idea how I am able to do this, I've tried multiple ways but experienced lots of problems along the way. I tried adding styling in the
 tag on the HTML page, but it changed absolutely nothing, I then tried using the last-child selector which worked to an extent. It allowed me to change the padding of it but not width. But it didn't just change it for the last one but also the first one.
CSS:
.dropdown{
position: relative;
margin: 0 auto;
float: right;
top: 20px;
font-size: 13px;
}

.dropdown li {
float: left;
width: 155px;
background-color:#373737;
position: relative;
border-bottom:1px solid #575757;
border-top:1px solid #797979;
}

.dropdown li a {
display: block;
padding: 10px 8px;
color: #fff;
position: relative;
z-index: 2000;
text-align:center;
}

.dropdown li a:hover,
.dropdown li a.hover{
background: #CF5C3F;
position: relative;
}

.dropdown :last-child  li a{
padding: 0px;
width: 40px;
}

HTML

Home

Internet Architecture

Item Two

Item Three

Item Four

Item Four

Internet Security

Laws

Security Risks

Internet Security

Laws

Security Risks

Item One

Item Two

Item Three

Item Four

Does anyone have any idea on how to fix this?

A:

I want the last one to have a different size as i wish to change the width and padding of it.
So if you meant last child of level 1 than use
ul.dropdown > li:last-child {
   /* Target */
}

And if you meant each last child of li on 2nd level ul, than use
ul.dropdown > li > ul > li:last-child {
   /* Target */
}

Demo
Demo (Just more elements, nothing fancy)


Q:

Merging/extend javascript object arrays based on join of a key property in each

I am wanting to merge the following object arrays, by first joining on the id property
var arr1 = [{
    id: 1,
    name: 'fred',
    title: 'boss'
},{
    id: 2,
    name: 'jim',
    title: 'nobody'
},{
    id: 3,
    name: 'bob',
    title: 'dancer'
}];

var arr2 = [{
    id: 1,
    wage: '300',
    rate: 'day'
},{
    id: 2,
    wage: '10',
    rate: 'hour'
},{
    id: 3,
    wage: '500',
    rate: 'week'
}];

So the result would be
[{
    id: 1,
    name: 'fred',
    title: 'boss',
    wage: '300',
    rate: 'day'
},{
    id: 2,
    name: 'jim',
    title: 'nobody',
    wage: '10',
    rate: 'hour'
},{
    id: 3,
    name: 'bob',
    title: 'dancer',
    wage: '500',
    rate: 'week'
}]

I would like to avoid using js frameworks (if possible), although ExtJs is already part of the project.
AT the moment I have a loop with an inner loop that if the keys match it copies the properties and breaks out of the inner loop to start the next outer loop.
Any better suggestions?

A:

Like this?
var combined = [];
function findSecond(id,second){
    for (var i=0;i<second.length;i++){
        if(second[i].id === id){
            return second[i];
        }
    }
    return null
}

while (el = arr1.pop()){
    var getSec = findSecond(el.id,arr2);
    if (getSec){
        for (var l in getSec){
            if (!(l in el)) {
                el[l] = getSec[l];
            }
        }
        combined.push(el);
    }
}

If the arrays have the same length, and the id's are equal, a simpler merge will do:
function merge(a1,a2) {
    var i = -1;
    while ((i = i+1)<a1.length)  {
     for (var l in a2[i]) {
            if (!(l in a1[i] )) {
                a1[i][l] = a2[i][l];
            }
     }
    }
   return a1;
}

Here's a working example
[Edit 2016/07/30] Added a snippet using more functional approach and, based on @djangos comment, an extra method to combine both arrays.

(function() {
    var alert = function(str) {document.querySelector('#result').textContent += str + '\n';};
    var arrays = getArrays();

    alert('Combine on id (shared id\'s):')
    alert(JSON.stringify(combineById(arrays.arr1, arrays.arr2), null, ' '));

    alert('\nCombine on id (all id\'s):')
    alert(JSON.stringify(combineBothById(arrays.arr1, arrays.arr2), null, ' '));

    // for combineBothById the parameter order isn't relevant
    alert('\nCombine on id (all id\'s, demo parameter order not relevant):')
    alert(JSON.stringify(combineBothById(arrays.arr2, arrays.arr1), null, ' '));

    // combine first array with second on common id's
    function combineById(arr1, arr2) {
      return arr1.map(
          function (el) {
                var findInB = this.filter(function (x) {return x.id === el.id;});
                if (findInB.length) {
                    var current = findInB[0];
                    for (var l in current) {
                        if (!el[l]) {el[l] = current[l];}
                    }
                }
                return el;
          }, arr2);
    }

    // combine first array with second on all id's
    function combineBothById(arr1, arr2) {
        var combined = arr1.map(
            function (el) {
                var findInB = this.filter(function (x) {return x.id === el.id;});
                if (findInB.length) {
                    var current = findInB[0];
                    for (var l in current) {
                        if (!el[l]) {el[l] = current[l];}
                    }
                }
                return el;
            }, arr2);
        combined = combined.concat(arr2.filter(
            function (el) {
                return !this.filter(function (x) {return x.id === el.id;}).length;
            }, combined));
        return combined;
    }

    function getArrays() {
        return {
            arr1: [{
                id: 1,
                name: 'fred',
                title: 'boss'
            }, {
                id: 2,
                name: 'jim',
                title: 'nobody'
            }, {
                id: 3,
                name: 'bob',
                title: 'dancer'
            }],
            arr2: [{
                id: 1,
                wage: '300',
                rate: 'day'
            }, {
                id: 2,
                wage: '10',
                rate: 'hour'
            }, {
                id: 4,
                wage: '500',
                rate: 'week'
            }]
        };
    }
}());


Q:

Merge two sets, list and tree

We are given two sets $S_1$ and $S_2$.
We consider that $S_1$ is implemented, using a sorted list, and $S_2$ is implemented, using a pre-order sorted tree.
I have to write a pseudocode, that implements the operation Merge() of the sets $S_1$ and $S_2$.
The time complexity of the algorithm should be $O(n_1+n_2)$, where $n_1$ is the number of elements of $S_1$ and $n_2$ is the number of elements of $S_2$.
That's what I have tried:
SetMerge(LNODE *S1, TNODE *S2)
      LNODE *p1=S1
      TNODE *p2=S2
      LNODE *S, slast, new
      while(p1 != NULL p2 != NULL)
           new=newcell(NODE)
           if(p2->data < p1->data)
                 new->data=p2->data
                 if(p2 != NULL)
                     p2=p2->LC
                 else
                     p2=p2->RC
           else
                 new->data=p1->data
                 p1=p1->next
      new->next=NULL
      if(S==NULL)
         S=new
         slast=new
      else
         slast->next=new
         slast=new
      while(p1 != NULL)
         new=newcell(NODE)
         new->data=p1->data
         new->next=NULL
         if(S==NULL)
            S=new
            slast=new
         else
            slast->next=new
            slast=new

Could you tell me if it is right or if I have done something wrong?

A:

Unfortunately your code is far from perfect, or I am misunderstanding it. If I do understand your intentions, there are multiple places where it could be improved, to name some issues

In the following code
\begin{align}
  &\verb`if(p2 != NULL)`\\
  &\verb`    p2=p2->LC`\\
  &\verb`else`\\
  &\verb`    p2=p2->RC`
  \end{align}
the else branch looks up NULL->RC which would cause an error.
In the first loop you never set new->next.
In general, either you need to use some additional data structure (like stack or list to remember tree pointers), more loops (to recreate the tree pointers) or recursion; otherwise you won't be able to access all the elements of the tree.

To approach this problem I suggest you should divide it into two parts: making the tree into a list and then merging two list. Some may call such solution suboptimal, but it is simple, natural, and its asymptotic are just as good (even if the constants are a bit worse). To give you a start, the following function appends at the front the contents of a tree tree to a list tail (I'm trying to write in similar style of pseudocode you use, sorry if I got it wrong):
tree_to_list(tree, tail) =
  if (tree == NULL) return tail
  else
    middle = tree_to_list(tree->RC, tail)
    new_tail = tree_to_list(tree->LC, middle)
    head = newcell(NODE)
    head->data = tree->data
    head->next = new_tail
    return head

Now you only need to write a function that would merge two lists, one given and one obtained from tree_to_list.
On the other hand, if you would insist on doing this without some additional lists, you can make it using a function which takes a list, a tree and returns a pair (first element of a list, an element of the list that corresponds to the last element of the tree). If you would like to follow this approach, to give you a start, consider the following code. It's not complete (some special cases marked by ...) and it has some issues (what would happen if middle in the last branch would be NULL?), but it should give you some general idea.
merge_subprocedure(list, tree)
  if (list == NULL) ...
  else if (tree == NULL) ...
  else
    if (list->data <= tree->data)
      (first, middle) = merge(list->next, tree)
      head = newcell(NODE)
      head->data = list->data
      head->next = first
      return (head, middle)
    else
      head = newcell(NODE)
      head->data = tree->data
      (first, middle) = merge(list, tree->LC)
      head->next = first
      (first2, middle2) = merge(middle->next, tree->RC)
      middle->next = first2
      return (head, middle2)

Finally, I think that stackoverflow would be much better for this question. Nevertheless, I hope this helps $\ddot\smile$


Q:

If you plant deer resistant plants with plants that deer like, will the deer resistance work?

Is there a "bubble" created by plants that are deer resistant to protect deer prone plants from being attacked?

A:

No. Deer resistance is based on taste, not smell. You are confusing mammal pests with insect pests. If you look at the odor-based deer repellents they are super strong, and sometimes don't work.
"Deer resistant" plants are plants the deer do not prefer, but they still still eat them if it's a harsh winter and there is no other food. We've had deer eat hosta and daffodils, which are supposed to be deer resistant.
Now thorny plants will be even more deer resistant.
The harshest time of the year is the spring before many shoots and berries are available. So that's when the deer are the hungriest.
If you value your plants, put hot pepper powder on them and replace after every rain. Mammals can taste the hot pepper juice.
But your best protection is a 6 foot high fence. But even then SOME occasional desperate/stupid deer have been known to jump those and get trapped in the garden. lol.


Q:

Where should the CSS transition property go?

When creating a CSS Transition for an element, should the transition property be applied to the element's existing class (or id or selector) or to the new class that causes the transition? It works either way I believe, but is one way better than the other and why?
JSFiddle

.box {
    height: 100px;
    width: 100px;
    background: blue;
}

/* background-change class to be added to the element with the box class */
.background-change {
    background: red;
    /* Should this be under .background-change or .box? */
    transition: background 2s;
}

A:

You can use both of these variants, they're both OK. But you should understand the difference between them.
If you set transition property to new/separate class, your transition will be applied only when you set this class:
JSFiddle

$('.box').hover(function() {
    $(this).toggleClass('background-change');
});
.box {
    height: 200px;
    width: 200px;
    background: green;
}

.background-change {
    background: red;
    transition: background 2s;
}

Hover it to change background

But if you set transition property to main/existing class, your transition will be applied also when you remove class:
JSFiddle

$('.box').hover(function() {
    $(this).toggleClass('background-change');
});
.box {
    height: 200px;
    width: 200px;
    background: green;
    transition: background 2s;
}

.background-change {
    background: red;
}

Hover it to change background

I prefer to use the last variant because it looks better and consistently.


Q:

Ruby - Passing instance variables to a class from another

I have 3 classes: Invoice, Address and Customer (but for this problem, only the Invoice and Address class are relevant)
This is my Invoice class:
class Invoice
  attr_reader :billing_address, :shipping_address, :order

  def initialize(attributes = {})
    @billing_address = attributes.values_at(:billing_address)
    @shipping_address = attributes.values_at(:shipping_address)
    @order = attributes.values_at(:order)
  end
end

and this is my Address class:
class Address
  attr_reader :zipcode, :full_address

  def initialize(zipcode:)
    @zipcode = zipcode

    url = 'https://viacep.com.br/ws/' + zipcode.to_s + '/json/'
    uri = URI(url)
    status = Net::HTTP.get_response(uri)
    if (status.code == "200")
      response = Net::HTTP.get(uri)
      full_address = JSON.parse(response)
      @full_address = full_address
    else
      p "Houve um erro. API indisponível. Favor tentar novamente mais tarde."
      @full_adress = nil
    end
  end
end

And this is my Customer class (not much relevant, but i'm showing for better explanation of the problem)
class Customer
  attr_reader :name, :age, :email, :gender

  def initialize(attributes = {})
    @name = attributes.values_at(:name)
    @age = attributes.values_at(:age)
    @email = attributes.values_at(:email)
    @gender = attributes.values_at(:gender)
  end

end

As you can see, my Invoice class has 3 instance variables and my Address class has 2 instance variables.
So, if i test something like that:
cliente = Customer.new(name: "Lucas", age: 28, email: "abc@gmail.com", gender: "masculino")
endereco = Address.new(zipcode: 41701035)
entrega = Invoice.new(billing_address: endereco, shipping_address: endereco)

p endereco.instance_variables

[:@zipcode, :@full_address]

p entrega.shipping_address.instance_variables

[]

My instance variables can be acessed through the variable "endereco", that is an Address object, but can't be acessed through entrega.shipping_address that is also an Address object.
To be more precise, if a try this:
p entrega.shipping_address

I get this return:
[#<Address:0x00000001323d58 @zipcode=41701035, @full_address={"cep"=>"41701-035", "logradouro"=>"Rua Parati", "complemento"=>"", "bairro"=>"Alphaville I", "localidade"=>"Salvador", "uf"=>"BA", "unidade"=>"", "ibge"=>"2927408", "gia"=>""}>]

My full object are being returned, but i can't access the content of my @full_address instance variable.
If a do this:
p entrega.shipping_address.full_address

I get a NoMethodError:
solucao.rb:8:in `<main>': undefined method `full_address' for #<Array:0x000000012d25e8> (NoMethodError)

I'm trying to understand why i can't access the content inside my object if i have the full object. Maybe i'm trying to access in the wrong way, i don't know.
Can someone help ?

A:

If you take a look at the error, it says
undefined method `full_address' for #<Array:0x000000012d25e8>

You're trying to call full_address on an array. So this means that entrega.shipping_address returns you an array (which it does, of course, take a closer look at the output).
If I were you, I'd look into how shipping_address is implemented. It's a simple attr_reader, so it's backed by an instance variable. Must be you initialize that instance variable to a wrong value (it gets an array instead of an address). Look closely at that initialization code and try to run it in IRB session. You should see the problem.

A:

values_at returns an array of values (see https://apidock.com/ruby/Hash/values_at
for explanation)
Change
@shipping_address = attributes.values_at(:shipping_address)

into
@shipping_address = attributes[:shipping_address]

And that way @shipping_address will contain an Address object, not an array that contains an Address object


Q:

OSSEC | How to add an exception rule

I have the standard syslog_rules.xml (OSSEC 2.6.0).
This is the standard rule for bad words in the /var/log/messages file:
<var name="BAD_WORDS">core_dumped|failure|error|attack|bad |illegal |denied|refused|unauthorized|fatal|failed|Segmentation Fault|Corrupted</var>
.....
<rule id="1002" level="2">
<match>$BAD_WORDS</match>
<options>alert_by_email</options>
<description>Unknown problem somewhere in the system.</description>
</rule>
.....

How can I add or modify this rule that uses $BAD_WORDS, but excludes the auxpropfunc error phrase? That is, something like this:
<match>$BAD_WORDS</match>
<match>!auxpropfunc error</match>
<options>alert_by_email</options>

Any ideas?

A:

Your best option is probably to write a rule to ignore that phrase. You could add something like the following to /var/ossec/rules/local_rules.xml:
<rule id="SOMETHING" level="0">
  <if_sid>1002</if_sid>
  <match>auxpropfunc error</match>
  <description>Ignore auxpropfunc error.</description>
</rule>

You could then run the entire log message through ossec-logtest to see how OSSEC will analyze it. You may need to add another option into this rule, or you may not.

A:

If you have more than one word, you could add something like the following to /var/ossec/rules/local_rules.xml
<var name="GOOD_WORDS">error_reporting|auxpropfunc error</var>

<rule id="100002" level="0">
  <if_sid>1002</if_sid>
  <match>$GOOD_WORDS</match>
  <description>Ignore good_words.</description>
</rule>


Q:

How to show the value for edit in a window in time format from grid in extjs 4

I am using extjs 4.1 .I have a grid that is showing date in desired time format. But when I want to show the date and intime and outtime in a window for edit then only date is displaying. but intime and outtime is not displaying. All the fields in database are datetime. Can anyone please help me on this. Here is my code below :
my grid is like below :
Ext.define('Ext4Example.view.attendence.Datagrid' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.datagrid',
    layout: 'fit',
    border: true,
    viewConfig: {
        stripeRows: true,
        forceFit:true,
        emptyText:'No Records to display'
    },

    hideHeaders: false,
    initComponent: function() {

        this.store = 'Attendences';
        //this.width = 400;
        this.columns = [
        {
            text: 'Date',
            dataIndex: 'id',
            renderer: function(value, metaData){
                return Ext.Date.format(value, 'M d, Y');
            }
        },{
            text: 'Day',
            dataIndex : 'id',
            renderer: function(value, metaData){
                return Ext.Date.format(value, ' l');
            }
        },
        {
            text: 'In-Time',
            dataIndex: 'intime',
            renderer: function(value, metaData){
                return Ext.Date.format(value, 'h:i A');
            }
        },
        {
            text: 'Out-Time',
            dataIndex: 'outtime',
            renderer: function(value, metaData){
                return Ext.Date.format(value, 'h:i A');
            }
        }

        ];

        this.callParent(arguments);
    }
});

And the window is given below where i want the values for edit :
    Ext.define('Ext4Example.view.attendence.Editattendence' ,{
    extend: 'Ext.window.Window',
    alias : 'widget.editattendence',
    title: 'Edit Attendence',
    layout: 'fit',
    autoShow: true,
    initComponent: function () {
        this.items = [
        {
            xtype: 'form',

            bodyStyle: {
                background: 'none',
                padding: '10px',
                border: '0'
            },
            items: [
            {
                xtype: 'datefield',
                name: 'id',
                allowBlank: false,
                fieldLabel: 'Attendene ID'
            },
            {
                xtype: 'numberfield',
                name: 'intime',
                allowBlank: false,
                fieldLabel: 'IN TIME',
                renderer: function(value, metaData){
                return Ext.Date.format(value, 'h:i A');
            }
            },{
                xtype: 'numberfield',
                fieldLabel: 'OUT TIME',
                name: 'outtime',
                renderer: function(value, metaData){
                return Ext.Date.format(value, 'h:i A');
            }
            }
            ]
        }
        ];
        this.buttons = [
        {
            text: 'Save',
            action: 'save'
        },
        {
            text: 'Cancel',
            scope: this,
            handler: this.close
        }
        ];
        this.callParent(arguments);
    }
});

And the controller where I am calling this window on double click in grid row is given below :
Ext.define('Ext4Example.controller.Attendences', {
    extend: 'Ext.app.Controller',
    stores: [
    'Attendences','Months'
    ],
    models: [
    'Attendence','Month'
    ],
    views: [
    'attendence.Timeperiod','attendence.Details','attendence.Attendencewindow','attendence.Editattendence','attendence.Datagrid'  //'attendence.Months'
    ],

    refs: [{
        ref: 'stockaddForm',
        selector: 'form'
    }],

    init: function () {
        this.control({
            'datagrid': {
                itemdblclick: this.editUser,
                viewready: this.attnready
            },
            'attendencewindow button[action=save]': {
                click: this.save
            }
        });
    },

    editUser: function(grid, record){
        var view = Ext.widget('editattendence');
        view.down('form').loadRecord(record);
    },
    save: function(){
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();     //+1
        Ext.Msg.alert("Today is - ",dd+" - "+mm+" - "+yyyy);
    },
    attnready: function(grid, eOpts) {
        console.log('hello');
        var store = grid.getStore(),
        selModel = grid.getSelectionModel();
          if (store.getAt(0)) {
            selModel.select(0);
        }
    }
});

A:

Hey I have solve this problem. Just a little bit of change in the editAttendence form as follows :
Ext.define('Ext4Example.view.attendence.Editattendence' ,{
    extend: 'Ext.window.Window',
    alias : 'widget.editattendence',
    title: 'Edit Attendence',
    layout: 'fit',
    autoShow: true,
    initComponent: function () {
        this.items = [
        {
            xtype: 'form',

            bodyStyle: {
                background: 'none',
                padding: '10px',
                border: '0'
            },
            items: [
            {
                xtype: 'datefield',
                name: 'id',
                allowBlank: false,
                fieldLabel: 'Attendene ID'
            },
            {
                xtype: 'datefield',
                format:'h:i A',
                name: 'intime',
                allowBlank: false,
                fieldLabel: 'IN TIME'

            },{
                xtype: 'datefield',
                format:'h:i A',
                fieldLabel: 'OUT TIME',
                allowBlank: false,
                name: 'outtime'

            }
            ]
        }
        ];
        this.buttons = [
        {
            text: 'Save',
            action: 'save'
        },
        {
            text: 'Cancel',
            scope: this,
            handler: this.close
        }
        ];
        this.callParent(arguments);
    }
});


Q:

java gui help actionlistener

I'm trying to set a combobox in my GUI to print the the information about a student in a JLabel.
private void studentComboBoxMouseClicked(java.awt.event.MouseEvent evt) {

    if combobox1="student1"{
        println.jlabel."name:a";
        println.jlabel.""age:12";
        println.jlabel."course:english";
    }

    if combobox1="student2"{
        println.jlabel."name:b";
        println.jlabel.""age:11";
        println.jlabel."course:maths";
    }

    if combobox1="student3"{
        println.jlabel."name:c";
        println.jlabel.""age:10";
        println.jlabel."course:science";
    }
}

A:

You have to listen for itemstatechange on your combobox,
Upon selecting your student , fetch the selected item and operate on to display appropriate messages.
Have a look at this example


Q:

I want to find a relation between $X(l,t)$ and $Y(l,t)$

Let $X(l,t)=4t \sum_{n=0}^{l-1} \binom{2n}{n}t^n \ $ and $ \ Y(l,t)=\sum_{n=0}^{l-1}n \binom{2n}{n}t^n$, where $l \in \mathbb{N}$.
I want find an explicit relation between $X(l,t)$ and $Y(l,t)$.
My approach:
Multiplying $Y(l,t)$ by $4t$, we get
$$ 4tY(l,t)=4t \sum_{n=0}^{l-1} n\binom{2n}{n}t^n.$$
But still it is not equal to $X(l,t)$ because of the absence of the factor $n$ in $X(l,t)$.
I could not find a relation between $X(l,t)$ and $Y(l,t)$.
Can someone help me please ?

A:

$$\begin{array}{rcl}Y(l,t)&=&t\sum_{n=0}^{l-1}n\binom{2n}{n}t^{n-1}\\&=&t\cfrac{d\left(\sum_{n=0}^{l-1}\binom{2n}{n}t^n\right)}{dt}\\&=&t\cfrac{d\left(\frac{X(l,t)}{4t}\right)}{dt}\\&=&\cfrac{1}{4}t\cfrac{d\left(\frac{X(l,t)}{t}\right)}{dt}\\&=&\cfrac{1}{4}t\cfrac{\cfrac{dX(l,t)}{dt}\cdot t-X(l,t)}{t^2}\\&=&\cfrac{1}{4}\left[\cfrac{dX(l,t)}{dt}-\cfrac{X(l,t)}{t}\right]\end{array}$$


Q:

Scala 2.11: get Class (result of classOf) for type parameters in collections

Say I have an instance of a Map[K, V], val m = Map[String, Int]("asdf" -> 1)
and I have a function defined as def getType[T : TypeTag](t: T) = typeOf[T]
I can use getType(m).typeArgs to get a List[Type](String, Int)
How do I get a List[Class] for String and Int? In other words, I want List(classOf[String], classOf[Int]) as collected from a Map[String, Int], or from any other combination of Map.
My ultimate goal is to write a RichRow for a Cassandra Row, wherein I can do (r: Row).getAs[Map[String, Int]]("mymap"), and under the hood can call r.getMap("mymap", classOf[String], classOf[Int]).
Thanks, and good luck.

A:

You can get a Class from a Type as follows:
scala.reflect.runtime.currentMirror.runtimeClass(tpe)


Q:

Display Table output as a grid of points

I want to create a Grid or Plot (or equivalent) from the following Table:
Module[{size = 10}, Table[If[PrimeQ[a + b], True], {a, 1, size}, {b, 1, size}]]

(*
{{True, True, Null, True, Null, True, Null, Null, Null, True},
{True, Null, True, Null, True, Null, Null, Null, True, Null},
{Null, True, Null, True, Null, Null, Null, True, Null, True},
{True, Null, True, Null, Null, Null, True, Null, True, Null},
{Null, True, Null, Null, Null, True, Null, True, Null, Null},
{True, Null, Null, Null, True, Null, True, Null, Null, Null},
{Null, Null, Null, True, Null, True, Null, Null, Null, True},
{Null, Null, True, Null, True, Null, Null, Null, True, Null},
{Null, True, Null, True, Null, Null, Null, True, Null, True},
{True, Null, True, Null, Null, Null, True, Null, True, Null}}
*)

I want the output to have the following properties:

The two 'axes' a and b are marked, and have ticks at integer values;
There is a grid of lines showing integer intervals from both axes;
At each intersection with Cartesian coordinates (a,b) where the Table output is True, there should be a Point; at Null points there should be nothing.

This seems like it should be really simple, but for some reason I can't quite get my head around the syntax...
How do I do it?

A:

Visualized as squares rather than points
ArrayPlot[data,
 Frame -> True,
 FrameTicks -> {{Range@10, Range@10}, {Range@10, Range@10}},
 DataReversed -> True,
 PlotRangePadding -> None,
 Mesh -> All]

A:

Inspired by @kglr and extending to arbitrary dimensions on the data, this may do what you want:
data = Module[{size = 11},
  Table[If[PrimeQ[a + b], True], {a, 1, size}, {b, 1, size}]];
With[{elements = Max[Dimensions[data]]},
 ListPlot[Position[data, True],
  PlotStyle -> Directive[Black, PointSize[Large]], Frame -> True,
  AspectRatio -> 1,
  FrameTicks -> {{Range[elements],
     Thread[{Range[elements], ""}]}, {Range@elements,
     Thread[{Range[elements], ""}]}},
  GridLines -> {Range[elements], Range[elements]},
  PlotRange -> {{1, elements}, {1, elements}},
  PlotRangeClipping -> False]]

Shown with size set to 11 to show that it fits the generality.


Q:

Delete item from array without returning it

I'm trying to write a method that will cause a rspec test like this to pass:
it "starts the thing and move on" do
  class.method_1("Name One")
  class.method_1("Name Two")
  expect(class.method_2).to eq "Some string Name One"
  expect(class.method_3).to eq ["Name Two"]
end

method_1 just adds a name to an array, and method_3 returns the array (defined in initialize method):
def method_1(name)
  @array << name
end

def method_3
  @array
end

I figured it would be pretty simple to interpolate @array[0] into the string and use @array.delete_at(0) to modify the array. Like so:
def method_2
  p "Some string #{@array[0]}"
  @array.delete_at(0)
end

But that method returns "Name One" instead of the string. If I comment out the delete code, the string returns properly but my array hasn't been modified. I've been in Ruby docs for a long time but #shift has the same issue about returning the removed item.
I'm almost certain I've over complicated this -- what am I missing?

A:

You can collapse all this down to more conventional Ruby like this:
class MyTestClass
  attr_reader :array

  def initialize
    @array = [ ]
  end

  def push(s)
    @array << s
  end

  def special_shift
    "Some string #{@array.shift}"
  end
end

Then in terms of usage:
it "starts the thing and move on" do
  my_thing.push("Name One")
  my_thing.push("Name Two")
  expect(my_thing.special_shift).to eq "Some string Name One"
  expect(my_thing.array).to eq ["Name Two"]
end

Using names like push and shift which are consistent with Ruby conventions make the purpose and action of a method a lot easier to understand.
When it comes to your implementation of method_3 you forget that you can inline whatever you want inside a #{...} block, even methods that modify things. The p method is used for display, it won't return anything. To return something you need to have it either as the last thing evaluated (implicit) or by using return (explicit).


Q:

WHM / cPanel : Manage Wheel Group Users and SSK Keys access

I want to disable direct root logins to my server, which runs WHM with Centos 6.5 and add specific user to the wheel group in order to be able to perform tasks with root privileges.
I've done the following - while logged in via ssh as root, I've created new user:
newuser newsuperuser

and I've set the password for it
passwd newuserpassword

I then went ahead and added that user to the wheelgroup, by going to:
Security Center > Manage Wheel Group Users

and added newsuperuser to it.
I then went to:
Security Center > Manage root's SSH Keys

and generated new key with newpassword - then authorised it.
Next I've copied the private key to my local (Mac OSX) .ssh directory, run chmod 600 and added file to ssh session:
ssh-add newsuperuser_key

typed password when prompted.
Now if I try to connect to the server via ssh using:
ssh newsuperuser@800.800.800.800

(using the correct IP address :) - I get:
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

Any idea what I'm doing wrong?

A:

You've done everything right, but in order to make it work you need a few extra steps. Full instructions can be found here: SSH with Root Login disabled.
Once you've created the additional user, you need to copy the authorized_keys to your new user's root directory and the .ssh directory within it, which you'll have to add manually:
cp /root/authorized_keys /home/newsshuser/.ssh/

Then change the ownership of the newly copied file:
chown newsshuser:newsshuser authorized_keys

Edit sshd_config file:
nano /etc/ssh/sshd_config

and uncomment and set:
PermitRootLogin no

Restart the ssh:
/etc/init.d/sshd restart

Logout and log in with new username.


Q:

Chi Square test to measure degree of association

I have a categorical variable with binary outcomes 0,1 (say Y), I want to study the association with other variables X1,X2,X3,X4,X5..... most of Xi's are categorical and few of them are continuous. I used Chisquare test to study the same, which tell wheather I can consider two variables independent or not.
Further to rank the Xi's in order of association with Y . Now my question is can I use the pvalue from the ChiSquare test or standardized residual of the chi Square Test to measure the degree of association between the variables ?
As far as I could understand chi sqaure test can be used just to tell whether the variable are independent or not but not the degree of association. Is there any other test to do so or chi square can do that?

A:

There are several statistics related to the chi-square that measure association in contingency tables.
For example, there's Cramer's $\phi$ (also $\phi_C$ or Cramer's $V$), which in 2x2 tables is also called the phi coefficient.
For a $r\times c$ table,
$V = \sqrt{ \frac{\chi^2/n}{\min(c - 1,r-1)}}$
In your case, if one of your variables is Y, which you state to be 0-1, then that will reduce to:
$V = \sqrt{ \chi^2/n}$
where $n$ is the total number of observations.
Wikipedia:
Cramer's Phi/Cramer's V
Phi coefficient
There are a number of other ways of measuring association in contingency tables.


Q:

Wht is wrong with my regex?

My regex code doesnt work I am getting result like below.Any Idea
Errors on my code:
Getting the sentences without values like this one: CREATE SEQUENCE "" MINVALUE  MAXVALUE INCREMENT BY START WITH  CACHE  NOORDER NOCYCLE;

Conditions for changing the sentence

if MINVALUE has plus value inside the sentence than make start with value same as
MINVALUE...
if MINVALUE has minus value inside the sentence than make start with value same as
MAXVALUE

Inside my database I have 3 sentence that needs to be change...
CREATE SEQUENCE "MY_SEQUENCE" MINVALUE -8 MAXVALUE 999 INCREMENT BY 1 START WITH 250  CACHE 50 NOORDER NOCYCLE;

CREATE SEQUENCE "_SEQUENCE" MINVALUE 151 MAXVALUE 500 INCREMENT BY 4 START WITH 160  CACHE 30 NOORDER NOCYCLE;

Result should be like below
CREATE SEQUENCE "MY_SEQUENCE" MINVALUE -8 MAXVALUE 999 INCREMENT BY 1 START WITH 999 CACHE 50 NOORDER NOCYCLE;

CREATE SEQUENCE "_SEQUENCE" MINVALUE 151 MAXVALUE 500 INCREMENT BY 4 START WITH 151 CACHE 30 NOORDER NOCYCLE;

My Code:
            string sentence = "";
            string formatprototype = "";
            string output = "";

                using (OracleConnection conn1 = MyConnection.GetSourceConnection())
                {
                    conn1.Open();
                    using (OracleCommand crtCommand = new OracleCommand(@"MyCommand", conn1))
                    {
                        sentence = crtCommand.ExecuteScalar().ToString();
                        string pattern = @".*[ ]+?[\""]{1}(?<String>[a-zA-Z0-9_]*)[\""]{1}[ ]+?MINVALUE[ ]*(?<MinValue>[-?\d]*)[ ]*MAXVALUE[ ]*(?<MaxValue>[\d]*)[ ]+?[INCREMENT]*[ ]+?[BY]*[ ]+?(?<IncrementBy>[\d]*)[ ]+?[START]*[ ]+?[WITH]*[ ]+?(?<StartWith>[\d]*)[ ]+?[CACHE]*[ ]+?(?<Cache>[\d]*)\s+?";
                        Regex regex = new Regex(pattern);
                        Match match = regex.Match(sentence);
                        Group @string = match.Groups[1];
                        Group minvalue = match.Groups[2];
                        Group maxvalue = match.Groups[3];
                        Group incrementby = match.Groups[4];
                        Group startswith = match.Groups[5];
                        Group cache = match.Groups[6];
                        formatprototype = @"CREATE SEQUENCE ""{0}"" MINVALUE {1} MAXVALUE {2} INCREMENT BY {3} START WITH {4} CACHE {5} NOORDER NOCYCLE";
                        if (minvalue.Value.StartsWith("-"))
                        {
                            output = string.Format(formatprototype, @string, minvalue, maxvalue, incrementby, maxvalue, cache);
                        }
                        else if (!minvalue.Value.StartsWith("-"))
                        {
                            output = string.Format(formatprototype, @string, minvalue, maxvalue, incrementby, minvalue, cache);
                        }
                        MessageBox.Show(output);
                    }
                }
            }

A:

use this RegEx pattern
(.*?MINVALUE )(-)?(?(2)(.*?MAXVALUE ))(\d+)(.*START WITH )(\d+)(.*)

and replace with this pattern
$1$2$3$4$5$4$7

live Demo