Q:

How to get range from a string in jquery

I have a string like SL45NU2154-60
Now I want an array from this string like
SL45NU2154
SL45NU2155
SL45NU2156
SL45NU2157
SL45NU2158
SL45NU2159
SL45NU2160

How can I do this using jquery or javascript.
What I have tried.
first I split this string with '-' and found an array with SL45NU2154 and 60. Now I don't know how to make an array by looping or anyway.
Here is my code
var str = 'SL45NU2154-60';
var str_arr = str.split("-");
alert(str_arr);

A:

your jquery
  var main="SL45NU2154-60";
var arr=main.split('-');
var fnal=parseInt(arr[1]);
var last2=parseInt(arr[0].substr('-2'));
var firstval=arr[0].slice(0,-2);
for(var i=last2;i <= fnal;i++)
{
 alert(firstval+""+i);
}

DEMO


Q:

Updating the jump in game

I am making a Java game and I want my game to run the same on any FPS so I'm using time delta between each update. This is the update method of the Player:
    public void update(long timeDelta) {

        //speed is the movement speed of a player on X axis
        //timeDelta is expressed in nano seconds so I'm dividing it with 1000000000 to express it in seconds

        if (Input.keyDown(37))
            this.velocityX -= speed * (timeDelta / 1000000000.0);

        if (Input.keyDown(39))
            this.velocityX += speed * (timeDelta / 1000000000.0);

        if(Input.keyPressed(38)) {
            this.velocityY -= 6;
        }

        velocityY += g * (timeDelta/1000000000.0); //applying gravity
        move(velocityX, velocityY); /*this is method which moves a player
                                        according to velocityX and velocityY,
                                        and checking the collision
                                    */

        this.velocityX = 0.0;
    }

The strange thing is that when I have unlimited FPS (and update number) my player is jumping about 10 blocks. It jumps even higher when the FPS is increasing. If I limit FPS it is jumping 4 blocks. (BLOCK: 32x32) I have just realized that the problem is this:
if(Input.keyPressed(38)) {
    this.velocityY -= 6;
}

I add -6 to velocityY which increases player's Y proportionally to the update number and not to the time.
But I don't know how to fix this.

A:

You should add a jumpAcceleration. When the player press key(38) you should do
this.velocityY -= jumpAcceleration * dt;

where dt is timeDelta / 1000000000.0 .
What you do in your code is, you add 6 to the velocityY at every update. So at high FPS (e.x. 300 ) you will subtract 6 * 300 = 1800 from your velocityY, but at a low FPS (e.x. 10 ) you will subtract 60 from your velocityY, at every second. If you want to make your game independent of the FPS you have to add timeDelta there too.

Also search at google for game loops. There is information on how to create a solid and FPS independent game loop for your game.


Q:

Apply rules to growing window

I want to loop through the dataframe Out using a window that:

Grows one increment at a time (so the rear of the window is fixed and the front of the window grows - window gets bigger)
At each increment, the following rules should be run over the window:
if (mean(Speed_out) <= 0.152682)
Behaviour <- Lying
else if (Movement_Out == “left”) <= 20.8 && (mean(Speed_Out) >=
0.200921)
Behaviour <- Grazing

If no rules are met then the window should grow one increment at a time until a rule is met.
Once a rule is met, all of the previous increments should be labelled with the Behaviour assigned to that rule above.
The next window should then start at the next element after where the last window terminated.
The initial window size should be adjustable (the window size at the start and after each terminated window).

Notes:
The units (Movement_Out == “left”) <= 20.8 mean that if "left" occupies less than 20.8% of the window.
Example:
Here's a short example of the output I'd like from the data provided below where the starting window size was set to 4:
    Speed_Out Movement_Out  Behaviour
1      0.220         left    Lying
2      0.155         left    Lying
3      0.120      forward    Lying
4      0.090   non-moving    Lying   <== window terminates here
5      0.125   non-moving    Grazing <== new window starts here
6      0.125   non-moving    Grazing
7      0.155   non-moving    Grazing
8      0.340      forward    Grazing
9      0.370      forward    Grazing <== window terminates here
10     0.185      forward    Grazing <== new window starts here
11     0.155        right    Grazing
12     0.220   non-moving    Grazing
13     0.220   non-moving    Grazing
14     0.280   non-moving    Grazing <== window terminates here
15     0.215   non-moving    Grazing <== new window starts here
16     0.060        right    Grazing
17     0.340   non-moving    Grazing
18     0.555      forward    Grazing <== window terminates here
19     0.275        right    And so on..
20     0.215      forward

Dataframe for your use
Out <- structure(list(Speed_Out = c(0.22, 0.155, 0.12, 0.09, 0.125,
0.125, 0.155, 0.34, 0.37, 0.185, 0.155, 0.22, 0.22, 0.28, 0.215,
0.06, 0.34, 0.555, 0.275, 0.215, 0.185, 0.06, 0.245, 0.31, 0.345,
0.375, 0.375, 0.87, 1.025, 0.405, 0, 0.185, 0.31, 0.155, 0.125,
0.22, 0.375, 0.345, 0.345, 0.405, 0.31, 0.34, 0.245, 0.155, 0.19,
0.22, 0.185, 0.12, 0.185, 0.155, 0.245, 0.31, 0.155, 0.155, 0.25,
0.215, 0.09, 0.06, 0.245, 0.495, 0.495, 0.34, 0.28, 0.31, 0.28,
0.25, 0.25, 0.185, 0.155, 0.25, 0.28, 0.28, 0.34, 0.215, 0.125,
0.155, 0.34, 0.34, 0.09, 0.59, 1.71, 1.18, 0.185, 0.215, 0.185,
0.185, 0.155, 0.19, 0.19, 0.19, 0.87, 2.045, 2.73, 1.585, 0.22,
0.25, 0.435, 0.405, 0.405, 0.405, 0.715, 0.62, 0.37, 0.4, 0.185,
0.375, 0.59, 0.525, 0.245, 0.495, 0.495, 0.68, 0.775, 0.25, 0.31,
0.34, 0.28, 0.28, 0.25, 1.55, 2.695, 1.705, 1.21, 0.87, 0.25,
1.52, 1.52, 0.405, 0.81, 2.08, 2.915, 1.705, 0.435, 0.22, 0.78,
1.215, 0.84, 0.495, 0.495, 0.56, 0.375, 0.28, 0.715, 1.025, 0.495,
0.65, 1.18, 1.09, 0.995, 0.87, 0.435, 0.125, 0.435, 0.555, 0.775,
1.12, 1.555, 1.15, 0.25, 0.87, 0.93, 0.28, 0.31, 0.31, 0.375,
0.78, 0.655, 0.53, 0.62, 0.525, 0.37, 0.555, 1.025, 0.655, 1.12,
1.585, 0.715, 0.155, 0.28, 1.12, 2.11, 1.645, 0.715, 0.465, 0.84,
0.81, 0.655, 0.84, 0.435, 0.28, 0.215, 0.93, 1.335, 0.65, 0.185,
0.155, 0.34, 0.4, 0.37, 0.435, 0.405, 0.28, 0.28, 0.25, 0.25,
0.745, 1.24, 0.805, 1.055, 1.085, 0.465, 0.375, 0.5, 0.59, 0.37,
0.185, 0.34, 0.37, 0.435, 0.405, 0.06, 0.125, 0.25, 0.31, 0.405,
0.78, 0.56, 0.215, 0.495, 0.87, 1.025, 0.62, 0.405, 0.405, 0.405,
0.31, 0.215, 0.465, 0.435, 0.34, 0.275, 0.215, 0.25, 0.22, 0.22,
0.125, 0.245, 0.34, 0.31, 0.37, 0.31, 0.31, 0.245, 0.185, 0.25,
0.22, 0.22, 0.31, 0.28, 0.22, 0.28, 0.53, 0.655, 0.375, 0.19,
0.405, 0.435, 0.28, 0.215, 0.77, 0.96, 1.865, 1.83, 0.495, 0.655,
1.615, 1.395, 0.31, 0.31, 0.25, 0.28, 0.34, 0.34), Movement_Out = structure(c(2L,
2L, 1L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 4L, 3L, 3L, 3L, 3L, 4L, 3L,
1L, 4L, 1L, 1L, 2L, 2L, 3L, 4L, 3L, 2L, 4L, 1L, 2L, 1L, 3L, 3L,
1L, 3L, 2L, 4L, 3L, 1L, 3L, 1L, 1L, 1L, 4L, 3L, 3L, 3L, 3L, 1L,
3L, 3L, 3L, 2L, 4L, 3L, 3L, 4L, 2L, 3L, 1L, 1L, 2L, 4L, 1L, 2L,
4L, 3L, 3L, 4L, 3L, 3L, 2L, 4L, 2L, 1L, 2L, 4L, 4L, 2L, 4L, 2L,
1L, 2L, 3L, 1L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 1L, 3L, 3L,
2L, 2L, 3L, 1L, 2L, 4L, 3L, 4L, 2L, 3L, 1L, 4L, 4L, 3L, 1L, 2L,
1L, 1L, 4L, 1L, 2L, 4L, 2L, 1L, 1L, 2L, 4L, 2L, 2L, 4L, 1L, 1L,
2L, 4L, 2L, 4L, 2L, 1L, 2L, 2L, 4L, 2L, 4L, 2L, 4L, 3L, 1L, 4L,
2L, 1L, 1L, 2L, 4L, 2L, 4L, 2L, 4L, 4L, 2L, 4L, 1L, 1L, 4L, 2L,
4L, 4L, 3L, 4L, 4L, 2L, 1L, 1L, 1L, 4L, 1L, 1L, 4L, 4L, 2L, 2L,
4L, 1L, 2L, 2L, 4L, 4L, 4L, 2L, 2L, 1L, 4L, 4L, 2L, 3L, 1L, 2L,
2L, 4L, 4L, 1L, 2L, 4L, 4L, 2L, 2L, 4L, 2L, 4L, 2L, 4L, 1L, 1L,
2L, 1L, 4L, 4L, 3L, 4L, 2L, 4L, 3L, 1L, 1L, 2L, 1L, 1L, 4L, 2L,
4L, 2L, 4L, 3L, 1L, 4L, 1L, 1L, 2L, 4L, 2L, 1L, 4L, 1L, 4L, 3L,
2L, 3L, 2L, 4L, 3L, 3L, 2L, 1L, 3L, 1L, 1L, 3L, 2L, 3L, 3L, 3L,
1L, 2L, 4L, 2L, 3L, 2L, 1L, 4L, 3L, 2L, 4L, 4L, 2L, 4L, 1L, 1L,
2L, 2L, 4L, 1L, 2L, 4L, 2L, 4L, 3L, 4L), .Label = c("forward",
"left", "non-moving", "right"), class = "factor")), .Names = c("Speed_Out",
"Movement_Out"), row.names = c(NA, 283L), class = "data.frame")

A:

Ok, I have to say that this has been less trivial than I expected. My answer is ugly and most likely not optimal, but it seems to work.
There seem to be a few spots where even when the rest of the data was taken into account, none of the conditions were met, so the behaviour for those stayed at NA.
library(dplyr)

# Create id variable used to join results later
Out <- Out %>%
  mutate(id=row_number())

# Initial window size
window_size <- 4

# Initialize variables used in loop
w <- window_size
i<-1
window_cnt<-1
out_behaviour <- data.frame(id=as.numeric(), Behaviour=as.character(), stringsAsFactors = FALSE)

while (i <= NROW(Out)){

  print(paste0("Row: ", i, ", Window Size: ", w))

  df <- Out[i:(i+w-1),] %>%
    mutate(mean_sp=mean(Speed_Out),
           mvmt=sum(ifelse(Movement_Out=="left",1 ,0))/NROW(.)) %>%
    mutate(Behaviour=case_when(mean_sp <= 0.152682 ~ "Lying",
                               mvmt <= 0.208 & mean_sp >= 0.200921 ~ "Grazing",
                               TRUE ~ as.character(NA)),
           window_nr=window_cnt)

  if (!all(is.na(df$Behaviour))){
    i<-w+i
    w<-window_size
    out_behaviour <- rbind(out_behaviour, df %>% select(id, Behaviour, window_nr))
    window_cnt<-window_cnt+1
  } else {
    if (w<=NROW(Out)-i){
      w<-w+1
    } else {
      w<-window_size
      i<-i+1
    }
  }

  rm(df)
}

# Join Behaviour column bacl to original data frame
Out <- left_join(Out, out_behaviour, by="id") %>% select(-id)

# Clean up workspace
rm(i, w, window_size, window_cnt, out_behaviour)

And the first 20 outputs
   Speed_Out Movement_Out Behaviour window_nr
1      0.220         left     Lying         1
2      0.155         left     Lying         1
3      0.120      forward     Lying         1
4      0.090   non-moving     Lying         1
5      0.125   non-moving   Grazing         2
6      0.125   non-moving   Grazing         2
7      0.155   non-moving   Grazing         2
8      0.340      forward   Grazing         2
9      0.370      forward   Grazing         2
10     0.185      forward   Grazing         3
11     0.155        right   Grazing         3
12     0.220   non-moving   Grazing         3
13     0.220   non-moving   Grazing         3
14     0.280   non-moving   Grazing         3
15     0.215   non-moving   Grazing         4
16     0.060        right   Grazing         4
17     0.340   non-moving   Grazing         4
18     0.555      forward   Grazing         4
19     0.275        right   Grazing         5
20     0.215      forward   Grazing         5

I know the code is a mess, so let me know if it needs some extra commenting.


Q:

Xcode UI Tests can't find views that are added programmatically

I'm adding a child view to my view programmatically, and when I do I attach all accessibility params to it:
  [labelView setAccessibilityLabel:@"label"];
  [labelView setIsAccessibilityElement:YES];
  [labelView setUserInteractionEnabled:YES];

But when I query the UI like this:
 let app = XCUIApplication()
 app.staticTexts["label"]

The test fails because it couldn't find the view.
How do I deal with this, how to make dynamically added views available for UI Testing?

A:

You need to make sure that the container view of your label view (UIEditText?) doesn't have isAccessibilityElement set to YES. If it does it will hide the accessibility of its subviews (your label).
Check Make the Contents of Custom Container Views Accessible in the Accessibility Programming Guide


Q:

C++ Method chaining causes destructor to be called twice

I have simple c++ program which uses method chaining and I noticed that destructor is called twice when used in chain call only. This happens only if chain call contain constructor as well. If called separately destructor is called only once.
Code is below:

class Foo {
public:
    Foo()   { cout << "-- constructor " << this << endl; }
    ~Foo () { cout << "-- destructor  " << this << endl; };

    Foo& bar() {
        cout << "---- bar call  " << this << endl;
        return *this;
    }
};

int main() {
    cout << "starting test 1" << endl;
    {
        Foo f = Foo();
    }
    cout << "ending test 1"   << endl << endl;
    cout << "starting test 2" << endl;
    {
        Foo f = Foo().bar();
    }
    cout << "ending test 2"   << endl;
    return 0;
}

Result of this application is following:
starting test 1
-- constructor 0x7ffd008e005f
-- destructor  0x7ffd008e005f
ending test 1

starting test 2
-- constructor 0x7ffd008e005f
---- bar call  0x7ffd008e005f
-- destructor  0x7ffd008e005f
-- destructor  0x7ffd008e005f
ending test 2

Is this standard behavior (if so, why is that?) or did I make some mistake? Can I prevent this?

A:

Foo f = Foo().bar(); also calls the copy constructor of Foo, which is currently the one the compiler generates and so doesn't output anything to the console. That's why it looks like you're calling more destructors than constructors.
You could write const Foo& f = Foo().bar(); to obviate a copy. Using a const also extends the lifetime of the anonymous temporary, which is nice.

A:

Note that there are two objects of type Foo involved in the line:
Foo f = Foo().bar();
    ^----------------this one
        ^------------and this one

however, one is created via the constructor and the other one via the copy constructor. And thats why you get only one line printed for construction and two for destruction. Everything is fine with the code, you just have to implement the copy constructor to see consistent output.

A:

There is another constructor that you have not implemented by yourself. The copy constructor.
Your call Foo f = Foo().bar(); could be written as Foo tmp = Foo(); Foo f = tmp.bar();
Only the instantiation of your tmp object will call your constructor. The constructor called for f is the automatically genererated copy-constructor.
This should give you some better output:
#include <iostream>
using std::cout;
using std::endl;

class Foo {
public:
    Foo() { cout << "-- constructor " << this << endl; }
    Foo(const Foo& f) { cout << "-- copy-constructor " << this << endl; }
    ~Foo() { cout << "-- destructor  " << this << endl; };

    Foo& bar() {
        cout << "---- bar call  " << this << endl;
        return *this;
    }
};

int main() {
    cout << "starting test 1" << endl;
    {
        Foo f = Foo();
    }
    cout << "ending test 1" << endl << endl;
    cout << "starting test 2" << endl;
    {
        Foo f = Foo().bar();
    }
    cout << "ending test 2" << endl;
    return 0;
}

--
starting test 1
-- constructor 000000EC09CFF944
-- destructor  000000EC09CFF944
ending test 1

starting test 2
-- constructor 000000EC09CFFA44
---- bar call  000000EC09CFFA44
-- copy-constructor 000000EC09CFF964
-- destructor  000000EC09CFFA44
-- destructor  000000EC09CFF964
ending test 2


Q:

CSS - Using :hover pseudoclass isn't working at the bottom of an anchor tag

I'm currently modifying the stylesheet on http://onverse.wikia.com/wiki/Onverse_Wiki. I'm having difficulties with the orange "Onverse Wiki" button at the left top of the page. What's happening is when your put your mouse over the bottom part of the anchor, it doesn't register the :hover pseudoclass. I've tried so many different things like changing the z-index, the display property, changing the line-height property, and nothing works. I've gone as far as removing all margins (which is necessary of course), borders, and paddings, so that the object itself is covering the whole area that it appears to be without any success.
However any place below the text you hover over with your mouse (even if it's within the anchor tag), your cursor won't turn into the pointer cursor. Clicking there does nothing. It isn't actually dependent on the text is because... 1. The top, left, and right sides of the anchor tag still recognize when they're being hovered over. 2. Changing height to 41px, padding to 0, display to table-cell, vertical-align to bottom, brings the text to the bottom of that area and you can clearly see the pointer cursor doesn't appear when hovering over the bottom part of the text.
I'm thinking it has to do with its layout in relation to other elements maybe? I couldn't figure out what would be interfering if anything was... And I already did change the z-index to like 100000, so the anchor would've been on top of everything. I had a similar problem before, with the blue buttons to the right, but all I had to do there was change the z-index to 1.
So I'm lost here. Any help? It would be much appreciated!

A:

If you remove the height 8px from the following line of code it fixes it I think:
.WikiHeader h1::before, .WikiHeader .WikiaRail .module h2::before, .WikiaRail .module    .WikiHeader h2::before, .WikiHeader .WikiaRail #RIGHT_SKYSCRAPER h2::before, .WikiaRail #RIGHT_SKYSCRAPER .WikiHeader h2::before, .WikiHeader .shadow-mask {
  bottom: 0;
  height: 8px;
  position: absolute;
  right: 0;
  width: 1000px;
}


Q:

Button to call a php function?

I am new to javascript world.
I wrote a function in PHP. How do I call it when I click a button or image in html?

A:

If you want to call serverside functions you should use AJAX.
Goto http://www.w3schools.com, and take the AJAX tutorials.


Q:

Where to put hibernate annotations?

Where do i put my hibernate annotations?
Is it the line above my instance variable? Or before the getter? Or before the setter? Or doesn't it really matter?
Thanks a lot

A:

You place them either on the field or on the getter. From the Hibernate Annotations Reference Guide:

2.2.1. Marking a POJO as persistent entity
(...)
Depending on whether you annotate
  fields or methods, the access type
  used by Hibernate will be field or
  property. The EJB3 spec requires that
  you declare annotations on the element
  type that will be accessed, i.e. the
  getter method if you use property
  access, the field if you use field
  access. Mixing annotations in both
  fields and methods should be avoided.
  Hibernate will guess the access type
  from the position of @Id or
  @EmbeddedId.

You might also want to read about the @Access annotation that allows to force/override the access type (prior to Hibernate Annotations 3.5 and JPA 2.0, it was part of Hibernate Annotation Extensions):

2.2.2.2. Access type
By default the access type of a class
  hierarchy is defined by the position
  of the @Id or @EmbeddedId annotations.
  If these annotations are on a field,
  then only fields are considered for
  persistence and the state is accessed
  via the field. If there annotations
  are on a getter, then only the getters
  are considered for persistence and the
  state is accessed via the
  getter/setter. That works well in
  practice and is the recommended
  approach.

Note
The placement of annotations within a class hierarchy has to be consistent
    (either field or on property) to be
    able to determine the default access
    type. It is recommended to stick to
    one single annotation placement
    strategy throughout your whole
    application.

However in some situations, you need
  to:

force the access type of the entity hierarchy
override the access type of a specific entity in the class hierarchy
override the access type of an embeddable type

The best use case is an embeddable
  class used by several entities that
  might not use the same access type. In
  this case it is better to force the
  access type at the embeddable class
  level.
(...)

Regarding the pros and cons of both styles, I suggest to read the following questions:

Hibernate/JPA - annotating bean methods vs fields
Hibernate Annotations - Which is better, field or property access?
Performance difference between annotating fields or getter methods in Hibernate / JPA


Q:

UITableViewCell image changes when scrolling

I have a UITableView with a title and an image on each cell. Some cells will have a default image and others will not. When I scroll the table, the image of some rows is not the expected and the image of another row gets displayed instead of the expected one. If I don't use dequeuereuseidentifier everything works fine, but I want to use it because I have lots of cells.
Any suggestion?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];

        CGRect titleRect = CGRectMake(60, 6, 200, 24);
        UILabel *title = [[UILabel alloc] initWithFrame: titleRect];
        title.tag = 1;
        title.backgroundColor = [UIColor clearColor];
        title.font = [UIFont fontWithName:@"AdelleBasic-Bold" size:15.5];
        [cell.contentView addSubview:title];

        UIImageView *defaultCellImage = [[UIImageView alloc] initWithFrame:CGRectMake(8, 10, 42, 42)];
        defaultCellImage.tag = 2;
        [defaultCellImage setImage:[UIImage imageNamed: @"Default_Row_Image"]];
        [cell.contentView addSubview:defaultCellImage];
    }

    NSUInteger row = [indexPath row];
    Movie *movie = [_movies objectAtIndex: row];

    UILabel *titleRowLabel = (UILabel *) [cell.contentView viewWithTag:1];
    titleRowLabel.text = [movie title];

    UIImageView *cellImage = (UIImageView *) [cell.contentView viewWithTag:2];
    if (![movie.imageName isEqualToString:@""])
        [cellImage setImage:[UIImage imageNamed: [movie imageName]]];

    return cell;
}

A:

The first cells to be used in your table view will be properly loaded. Since there is no cell to dequeue, the if (cell == nil) will return YES and your cell will have its image set to be the default. Then, if your condition for setting a different image is satisfied later in the method, a different image will be shown. So far, so good.
However, when a reusable cell is dequeued, it already has an image set, which might not be the default. Since cell == nil will now return NO, this cell will never have its image reset to the default one, even if it is the image that should be shown.


Q:

MySQL ilike performance on OR using index is better than %%?

Is better use this SQL code suppose the right index in apply on the column!!
Suppose constant is a input from a textfield!!
select ...
from .....
where lower(column) like 'Constant%' or lower(column) like '%Constant%'

Is better than?
select ...
from .....
where lower(column) like '%Constant%'

In the first code i try to match a "constant" using like but using a index trying being lucky to find a match and later i try to do a full match!!
All i want is my performance is not decreased! I mean if both queries runs in the same time or if the query can sometimes get a performance upgrade is OK with me
I use lower because we use DEFAULT CHARSET=utf8 COLLATE=utf8_bin

A:

I created a little table:
create table dotdotdot (
  col varchar(20),
  othercol int,
  key(col)
);

I did an EXPLAIN on a query similar to the one you showed:
explain select * from dotdotdot where lower(col) = 'value'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: dotdotdot
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: Using where

Notice the type: ALL which means it can't use the index on col. By using the lower() function, we spoil the ability for MySQL to use the index, and it has to resort to a table-scan, evaluating the expression for every row. As your table gets larger, this will get more and more expensive.
And it's unnecessary anyway! String comparisons are case-insensitive in the default collations. So unless you deliberately declared your table with a case-sensitive collation or binary collation, it's just as good to skip the lower() function call, so you can use an index.
Example:
explain select * from dotdotdot where col = 'value'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: dotdotdot
   partitions: NULL
         type: ref
possible_keys: col
          key: col
      key_len: 23
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL

The type: ref indicates the use of a non-unique index.
Also compare to using wildcards for pattern-matching. This also defeats the use of an index, and it has to do a table-scan.
explain select * from dotdotdot where col like '%value%'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: dotdotdot
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: Using where

Using wildcards like this for pattern-matching is terribly inefficient!
Instead, you need to use a fulltext index.
You might like my presentation Full Text Search Throwdown and the video here: https://www.youtube.com/watch?v=-Sa7TvXnQwY

In the other answer you ask if using OR helps. It doesn't.
explain select * from dotdotdot where col like 'value%' or col like '%value%'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: dotdotdot
   partitions: NULL
         type: ALL
possible_keys: col
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: Using where

Notice the optimizer identifies the col index as a possible key, but then ultimately decides not to use it (key: NULL).


Q:

LSTM state-of-art

Can you advice me a good paper which talks about the LSTM's state-of-art?
I have already searched on google but I have not found anything interesting
Thank you very much

A:

You can have a look at the paper "LSTM: A Search Space Odyssey" by Klaus Greff, Rupesh Kumar Srivastava, Jan Koutník, Bas R. Steunebrink, Jürgen Schmidhuber.
It is not a super new paper (it's from 2015), but it compares 8 variants of LSTMs on 3 tasks (speech recognition, handwriting recognition, and polyphonic music modeling), and the authors conclude that none of the analysed variants can significantly outperform the standard LSTM architecture.


Q:

ZF2 User group specific layouts

I have a project with 3 different Layouts. 1 Layout for the Login page, 1 Layout for the administrators and editors and a 3rd Layout for general users where also the administrators have access to (its a layout for 3 different pages where you can fill out surveys which is possible for the 3 mentioned user groups).
At the moment I am using EdpModuleLayouts for this purpose, which did fine until now. Because now I need to adapt the 3rd layout depending on which usergroup accesses it.
Do you have any idea how to get this done?
Thanks in advance.

A:

you can listen you to the zf2 mvc events and change your layout based on your criterias.
this is an example how your application Module.php can look like.
public function onBootstrap(MvcEvent $e)
{
    $application =  $e->getApplication();
    $serviceManager = $application->getServiceManager();
    $eventManager = $application->getEventManager();
    $sharedManager = $eventManager->getSharedManager();

    // DISPATCH EVENT
    $sharedManager->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function( MvcEvent $e) use ($serviceManager) {

        // get your instance to locate current user group or something else
        $auth = $serviceManager->get('Some/Auth/Service');
        $userGroup = $auth->getUserGroupFromCurrentUser();

        $controller      = $e->getTarget();

        if( $userGroup == 'someGroup' )
        {
            $controller->layout('layout/somelayoutname');
        } else {
            $controller->layout('layout/someotherlayoutname');
        }
    }, 50 );
}


Q:

PHP if and statement

I'm trying to add an 'if and' statement, but can't get it working.
else if($iamonly == 'Other - ' && trim($othertype == '')) {
    echo '
Error! You selected "Other"
';

If $iamonly field is 'Other' and I enter data in the $othertype field, I still get the error message. Please can someone tell me what the heck I'm doing wrong here.

A:

trim only the variable:
if($iamonly == 'Other - ' && trim($othertype) == '') {


Q:

Add custom marker icon to angular-google-maps when markers are from external JSON

I'm new to Angular (so probably am making some silly mistakes) and I'm trying to add some markers to a map instance with a custom image icon.
I understand that the best way to do this is to add this into the items as suggested by Fedaykin but is there a way to do this if you can't change the JSON file?
I was able to add the custom icon for a single marker, so I wondered if I could do the same for several markers using 'forEach', but although this shows all my markers it doesn't add the icon.
$scope.marker = Mapdata.query(function() {

    var image = "https://maps.google.com/mapfiles/kml/shapes/info-i_maps.png";

    $scope.$watch('data', function(data) {
        angular.forEach($scope.marker, function(markerList, id, coords, icon) {
            $scope.markerList = [{

                id: data.id,
                coords: {
                    latitude: data.latitude,
                    longitude: data.longitude
                },

                icon: image

            }];
        });
    });

});

The html is just the usual angular-google-maps stuff
 <ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="true">
  <ui-gmap-markers models="marker.boards" coords="'self'" fit="'true'" icon="markerList.icon" click="'onClick'"></ui-gmap-markers>
</ui-gmap-google-map>

I have a plunker here to put it all in context.
Thanks for any help or advice :)

A:

Made a few changes:
index.html

icon="markerList.icon" --> icon="'icon'"

script.js
I didn't quite understand what you  were trying to to with the $watch - I ended up just setting the image attribute of each marker when the data is initially fetched.

Mapdata.query(function() { --> Mapdata.query(function(data) {
$scope.$watch thing -->
angular.forEach(data.boards, function(board) {
    board.icon = image;
});

Here's the updated plunker.


Q:

JWT 401: Unauthorized in Slim 3 framework

It's my first using slim 3 framework skeleton project, they say

There is also a skeleton project which will give you a quick-start for a sample application, so use that if you’d rather just have
  something working rather than exploring how all the moving parts
  work.

In real life it so hard to integrate JSON Web Token Authentication Middleware
I try to following step by step in tutorial but still not working.
Please help me ?
this is my code

middleware.php

$app->add(new \Slim\Middleware\JwtAuthentication([
  "path" => "/",
  "passthrough" => "/test",
  "secret" => "thisissecret"
]));

and my / route

routes.php

$app->get('/',App\MemberController::class);

but the result is like this image below, 401: Unauthorized

A:

You are misunderstanding the parameter secret. It is not the the token. It is the secret key you use to sign the token.
It is up to you how you generate the token. There is for example an online tool. You can also generate token with PHP.
use Firebase\JWT\JWT;

$payload = [
    "sub" => "user@example.com"
];
$token = JWT::encode($payload, "thisissecret", "HS256");

Before using JWT is is good idea to read this introduction.


Q:

spacing between UITableViewCells

I am creating a ios app in swift and want to add spacing between cells like Facebook (pic bellow).
I am using a custom nib for the posts. I know to use UITableViewController. I figure I would use a separator style but it does not achieve the effect. I goggled around for hours and can't find a single tutorial in swift that makes sense! could some one explain how they did it in there app using swift? thanks!

A:

This is my solution with result: (based on Jorge Casariego's answer)
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomApplicationCell

    cell.contentView.backgroundColor = UIColor.clear

    let whiteRoundedView : UIView = UIView(frame: CGRectMake(10, 8, self.view.frame.size.width - 20, 149))

    whiteRoundedView.layer.backgroundColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [1.0, 1.0, 1.0, 0.8])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSizeMake(-1, 1)
    whiteRoundedView.layer.shadowOpacity = 0.2

    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubviewToBack(whiteRoundedView)

    return cell
}

table row height: 165 point
header section height, footer section height: 10 point

and result

Edit For Swift 3 Syntax:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomApplicationCell

    cell.contentView.backgroundColor = UIColor.clear

    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 120))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.2

    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    return cell
}

Simplest way for creating material card view:

github.com/SwiftCardView
Create CardView.swift
@IBDesignable
class CardView: UIView {

    @IBInspectable var cornerRadius: CGFloat = 2

    @IBInspectable var shadowOffsetWidth: Int = 0
    @IBInspectable var shadowOffsetHeight: Int = 3
    @IBInspectable var shadowColor: UIColor? = .black
    @IBInspectable var shadowOpacity: Float = 0.5

    override func layoutSubviews() {
        layer.cornerRadius = cornerRadius
        let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)

        layer.masksToBounds = false
        layer.shadowColor = shadowColor?.cgColor
        layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight)
        layer.shadowOpacity = shadowOpacity
        layer.shadowPath = shadowPath.cgPath
    }
}

Now just add CardView class to your UIView.

A:

With Swift 2 you can do spacing between UITableViewCells in this way:
In your TableViewController copy this:
    // In this case I returning 140.0. You can change this value depending of your cell
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 140.0
    }

    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

        cell.contentView.backgroundColor = UIColor.clearColor()

        let whiteRoundedView : UIView = UIView(frame: CGRectMake(0, 10, self.view.frame.size.width, 120))

        whiteRoundedView.layer.backgroundColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [1.0, 1.0, 1.0, 1.0])
        whiteRoundedView.layer.masksToBounds = false
        whiteRoundedView.layer.cornerRadius = 2.0
        whiteRoundedView.layer.shadowOffset = CGSizeMake(-1, 1)
        whiteRoundedView.layer.shadowOpacity = 0.2

        cell.contentView.addSubview(whiteRoundedView)
        cell.contentView.sendSubviewToBack(whiteRoundedView)
    }

This is the result:

A:

I spent at least an hour researching the topic. Finally, I came up win an idea to use a transparent border:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "faqCell", for: indexPath)

    // ...

    cell.layer.borderWidth = CGFloat(TABLE_CELLSPACING)
    cell.layer.borderColor = tableView.backgroundColor?.cgColor

    return cell
}

This works perfectly in Swift 3/Xcode 8.
Image: This is how it looks like on my side


Q:

How should I structure my database to stop having so many tables?

Ok so i have a website in progress that will allow users to build routines using a set list of exercises provided. They can add a number of exercises to a routine which they will create and title themselves.
So i'm thinking i should have a user table.
Each user will have a number of routines.
Each routine will have a number of exercises.
Therefore I will have 3 tables: user, routines, and exercises
BUT
How can i link the 'routines' and 'exercises', because 'routines' is going to have to be more than one table, because if you imagine a user creates "biceps" routine and fills it with exercises. Then he creates "triceps" and fills it with exercises. He will then have to have two routine tables called 'biceps' and 'triceps'.
So how can I structure my database to accommodate this?
bearing in mind each user has a unique ID
Every exercise has a unique ID
and Every Routine has a unique ID.

A:

You don't want to have two routines tables.
You want one routines table, plus an exercises table that references the routines table.
Depending on whether one routine is the same for all users, or whether each user can have his own version of the "biceps" routine, maybe you need one more table.
Take a look at the examples below!

Example 1 (each user can have his own "biceps" routine):
Users table:
UserId  Name
----------------
1       Joe
2       Bill

Routines table:
RoutineId   Name     UserId
-------------------------------
1           biceps   1
2           biceps   2

Exercises table:
ExerciseId    RoutineId  Name
--------------------------------------------------------
1             1          first exercise of routine 1
2             1          second exercise of routine 1
3             2          first exercise of routine 2
4             2          second exercise of routine 2

Example 2 (there is only one "biceps" routine, and it's the same for all users):
Users table:
UserId  Name
----------------
1       Joe
2       Bill

Routines table:
RoutineId   Name
------------------
1           biceps

Users <--> Routines link table:
UserId   RoutineId
--------------------
1        1
2        1

Exercises table:
ExerciseId    RoutineId  Name
--------------------------------------------------------
1             1          first exercise of routine 1
2             1          second exercise of routine 1

EDIT:
You said:

And yes, routines are private to each user because they create them. They are not shared

and:

Each exercise should be able to be used more than once. I.e i might have a 'pull ups' exercise in my "back workout" routine, and my "arm workout" routine

Final Solution:
Users table:
UserId  Name
----------------
1       Joe
2       Bill

Routines table:
RoutineId   Name                    UserId
-----------------------------------------------------
1           Joe's back workout      1
2           Joe's arm workout       1
3           Bills's back workout    2

"global" Exercises table:
ExerciseId    Name
--------------------------------------------------------
1             pull up
2             whatever

Routines <--> Exercises link table:
RoutineId  ExerciseId
----------------------------------
1          2
2          1
3          1

That way, the "pull up" exercise is in Joe's arm workout (routine 2) and Bills's back workout (routine 3), but not in Joe's back workout (routine 1).
The "whatever" routine is in Joe's back workout (routine 1) only.
Is this what you wanted?

A:

create table users(
userid int not null AUTO_INCREMENT PRIMARY KEY,
firstname char(30) not null,
lastname char(30) not null
);

create table routines(
rid int not null AUTO_INCREMENT PRIMARY KEY,
userid int not null,
rname char(30) not null
);

create table execises(
eid int not null AUTO_INCREMENT PRIMARY KEY,
rid int not null,
ename char(30) not null
);


Q:

Wifi works in local, no internet connection. Debian 7

I installed Debian on an old PC, the KDE version.
I have internet over wired.
I can connect to my router, and I can ping it over wifi -- ping 192.168.1.1 is successful. I can ssh into other machines, connected to the same network.
I cannot access external web sites via wifi though, cannot ping successfully any IP; ping 8.8.8.8 results in a timeout.
Here are
root@debian:/home/deckoff# ifconfig

eth0  Link encap:Ethernet  HWaddr 00:0a:e4:2d:4a:a0
      inet addr:192.168.1.124  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: fe80::20a:e4ff:fe2d:4aa0/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:1419 errors:0 dropped:0 overruns:0 frame:0
      TX packets:759 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:563318 (550.1 KiB)  TX bytes:179940 (175.7 KiB)

eth1  Link encap:Ethernet  HWaddr 00:0e:35:b4:04:64
      inet addr:192.168.1.123  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: fe80::20e:35ff:feb4:464/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:944 errors:1 dropped:1 overruns:0 frame:0
      TX packets:52 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:137654 (134.4 KiB)  TX bytes:8203 (8.0 KiB)
      Interrupt:21 Base address:0x8000 Memory:d0220000-d0220fff

lo        Link encap:Local Loopback
      inet addr:127.0.0.1  Mask:255.0.0.0
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING  MTU:16436  Metric:1
      RX packets:120 errors:0 dropped:0 overruns:0 frame:0
      TX packets:120 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0
      RX bytes:9264 (9.0 KiB)  TX bytes:9264 (9.0 KiB)

etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

root@debian:/home/deckoff# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG    0      0        0 eth1
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 eth1
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 eth1

root@debian:/home/deckoff# traceroute 8.8.8.8
traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 60 byte packets
 1  192.168.1.1 (192.168.1.1)  5.144 ms  8.733 ms  10.349 ms
 2  * * *
 3  * * *

27  * * *
28  * * *
29  * * *
30  * * *

The adapter is eth1. It uses the ipw2200-bss.fw firmware, which I installed during system installation, if this info is of any help for solving my problem.
Yes, the name of the interface is eth1, an it's been that way on every Linux distro I installed on this PC?!?!?

A:

Your settings are correct: all your external packets are being routed to the gateway. So there are only two things that can go wrong: either your firewall is blocking external connections, or the gateway is configured in such a way as not to let you connect to outside sites.
Run iptables -nvL; iptables -nvL -t nat; iptables -nvL -t mangle as root to list your firewall settings. Check if you aren't rejecting certain outgoing or incoming packets that you shouldn't be rejecting.
If the gateway (your router) is the culprit, how to solve the problem depends entirely on what it is. Check that it's configured to allow NAT. Most home routers are set up properly by default.
There is something weird in your configuration: the IP address for eth0 is in the address range for the eth1 link. This isn't directly the cause of your problem, but it could cause trouble at some point, and it might indirectly be the reason for bad firewall settings if that turns out to be the problem.


Q:

Bootstrap loader using java

Normally boot strap loaders are written using assembly languages.
Is it possible to dot it using java with native interface.

A:

There are some possible solutions:

It exists hardware, that is able to
execute Java-bytecode.
Also you can compile Java-code to
native code with different
compilers.
Finally you can have a mini-loader, that
starts the rest of the process in
Java.

Neither of this solutions is easy or does make too much sense. But possible - yes.
For completeness: JNode is a project targeting to create a PC-Operating-system in Java.
Also answers to this question may be helpful. It ask for device-drivers in Java, and that's not completely the same question, but some of the solutions presented in the answers may be helpful with your question too.


Q:

Electromagnetism in astrophysics

What is the most important electromagnetic phenomena involved in astrophysics?, I am working in a presentation of magnetars, pulsars and magnetic field of planets and I would like to know if there are more interesting phenomena that I should mention, I trying to find about electromagnetism in black holes but I only found about the no hair theorem and papers that do not say anything in concrete terms

A:

Probably the most direct example is synchrotron radiation. This is the case in which an electron is accelerating by moving in along a curved path (e.g., a helix). As it is accelerated, it emits photons in the radio spectrum:

(source)
Another big one would be bremsstrahlung in which an electron moving along a path is decelerated near the presence of a heavy nucleus. The emitted photon is typically in the X-ray regime.

(source)


Q:

How would you translate "Como en su día fueron..."

Hyperloop is a conceptual high-speed transportation system put forward by Elon Musk. A recent article begins with:

Como en su día fueron los dirigibles o incluso los aviones, Hyperloop empieza a ser conocido como el medio de transporte del futuro.

What is a good translation for the first part of this sentence?

A:

I'm Spanish, this is my suggestion:

Like on its day were the blimps or even the airplanes, Hyperloop starts to be known as the future's mode of transport.

I know you asked for the translation of just the first part, but just in case I also translated the rest.


Q:

Steps to assign static IP address in CentOS Linux via command line?

How to configure so the Linux CentOS v8 VM I have with static IP address?
I have already set the networking parameter during the GUI installation, but after the reboot, it still reverting back with DHCP IP addressing?
Do I have to create a new interface file rather than modifying the below:
 cat /etc/sysconfig/network-scripts/ifcfg-ens192

Note: I cannot even restart the network service as mentioned in the various blog:
[root@PRDSIEM01-VM etc]# systemctl restart network
Failed to restart network.service: Unit network.service not found.

A:

By default, networking on CentOS 7 and 8 is managed by NetworkManager.
It uses a plugin called ifcfg-rh to read the old network service configuration files (used in CentOS 6 and previous versions) such as the one you mentioned and translate them into the appropriate NetworkManager configuration.
What has probably happened here is that the interface name has changed from what it was during installation. This often happens with virtual machines running under VMware products. It looks like you had the interface name ens192 at install time. You can use ip link to see the current interface name.
If the name differs, you can edit the file and change the interface name within, then reload NetworkManager.
[root@PRDSIEM01-VM ~]# systemctl reload NetworkManager

While NetworkManager excels at managing networks for desktop/laptop systems, and certainly works for servers, it's quite heavy for that purpose. I've lately begun switching my CentOS 8 servers to the much lighter systemd-networkd, which is a bit better integrated into the system, but doesn't support desktop/laptop systems (particularly WiFi) as well. You might consider doing the same.

A:

I've managed to configure the IP networking using the text user interface tool:
nmtui


Q:

Mimicking a secondary tidy dots argument in an R function

I'm looking to create a function that accepts a list of (data frame) variables as one of its parameters. I've managed to get it working partially, but when I get to the group_by/count, things fall apart. How can I do this??
## Works
f1 <- function(dfr, ..., split = NULL) {
  dots <- rlang::enquos(...)
  split <- rlang::enquos(split)
  dfr %>%
    select(!!!dots, !!!split) %>%
    gather('type', 'score', -c(!!!split))
}

## does not work
f2 <- function(dfr, ..., split = NULL) {
  dots <- rlang::enquos(...)
  split <- rlang::enquos(split)
  dfr %>%
    select(!!!dots, !!!split) %>%
    gather('type', 'score', -c(!!!split))
    count(!!!split, type, score)
  }

I would want to do things like
mtcars %>% f2(drat:qsec)
mtcars %>% f2(drat:qsec, split = gear)
mtcars %>% f2(drat:qsec, split = c(gear, carb)) ## ??

These calls with f1() all work, but for f2 none of the commands work. They all end up with a Error in !split : invalid argument type. That f2(drat:qsec) doesn't (immediately) work without the split argument, I'm not too surprised about, but how to get the second and third comment working?

A:

The issue with the second function (the missing pipe notwithstanding) is that count() (or rather group_by() which is called by count()) doesn't support tidyselect syntax so you can't pass it a list to be spliced like you can with select(), gather() etc.  Instead, one option is to use group_by_at() and add_tally().  Here's a slightly modified version of the function:
library(dplyr)

f2 <- function(dfr, ..., split = NULL) {
  dfr %>%
    select(..., {{split}}) %>%
    gather('type', 'score', -{{split}}) %>%
    group_by_at(vars({{split}}, type, score)) %>% # could use `group_by_all()`
    add_tally()
}

mtcars %>% f2(drat:qsec)

# A tibble: 96 x 3
# Groups:   type, score [81]
   type  score     n
   <chr> <dbl> <int>
 1 drat   3.9      2
 2 drat   3.9      2
 3 drat   3.85     1
 4 drat   3.08     2
 5 drat   3.15     2
 6 drat   2.76     2
 7 drat   3.21     1
 8 drat   3.69     1
 9 drat   3.92     3
10 drat   3.92     3
# ... with 86 more rows

mtcars %>% f2(drat:qsec, split = c(gear, carb))

# A tibble: 96 x 5
# Groups:   gear, carb, type, score [89]
    gear  carb type  score     n
   <dbl> <dbl> <chr> <dbl> <int>
 1     4     4 drat   3.9      2
 2     4     4 drat   3.9      2
 3     4     1 drat   3.85     1
 4     3     1 drat   3.08     1
 5     3     2 drat   3.15     2
 6     3     1 drat   2.76     1
 7     3     4 drat   3.21     1
 8     4     2 drat   3.69     1
 9     4     2 drat   3.92     1
10     4     4 drat   3.92     2
# ... with 86 more rows


Q:

python: how can i create a list of integers,to a number?

I receive an input int that I don't previously know. How can I create a new list of integer from 0 to that int? An easy way please. Thank you in advance.
I mean that:
k = n
...
list = [0, ... , k]

A:

numbers = list(range(k+1))   # For Python 2, it is just range(k+1).

Given an integer k, which you can get with input.
The range creates an iterator (in Python 3) with those numbers (k+1 because it is not inclusive, but you need it to be), then we make it into a list.

Demo:
>>> k = int(input())
16
>>> numbers = list(range(k+1))
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]


Q:

Multiple classes that implement a generic interface in a single array

Say I have a generic interface that stores a value that is typed by the generic parameter:
public interface IFoo<TValue>
{
    TValue SomeValue { get; set; }
}

Then I have two classes, StringFoo and DoubleFoo whose SomeValues are strings and doubles respectively:
public class StringFoo : IFoo<string>
{
    string SomeValue { get; set; }
}

public class DoubleFoo : IFoo<double>
{
    double SomeValue { get; set; }
}

I now decide that I want an array that can contain both StringFoos and DoubleFoos:
var foos = IFoo<object>[] {
    new StringFoo { SomeValue = "a value" },
    new DoubleFoo { SomeValue = 123456789 }
}

I would think that, since both string and double are subclasses of object, they would both be allowed in this array. However, I thought wrong.
So, I tried using covariance:
public interface IFoo<out TValue>

But, since the interface contains both setters and getters, I can't do this.
So, can two classes that implement a generic interface in one array?

A:

The problem can be solved in the way Bar class is implemented (bad example provided as well). The issue is that whenever one tries to use generic interface or class implementing generic interface code may compile (providing right casts) but code will throw InvalidCastException during runtime.
public interface IFoo<TValue>
{
    TValue SomeValue { get; set; }
}

public class StringFoo : IFoo<string>
{
    public string SomeValue { get; set; }
}

public class DoubleFoo : IFoo<double>
{
    public double SomeValue { get; set; }
}

public class Foo<TValue> : IFoo<TValue>
{
    public TValue SomeValue { get; set; }
}

public abstract class Bar
{

}

public class Bar<TValue> : Bar, IFoo<TValue>
{
    public TValue SomeValue { get; set; }
}

public static class Verify
{
    public static void QuestionArray()
    {
        var foos = new IFoo<object>[]
        {
            (IFoo<object>) new StringFoo { SomeValue = "a value" },
            (IFoo<object>) new DoubleFoo { SomeValue = 123456789 }
        };
    }

    public static void BadAnswerArray()
    {
        var foo = new IFoo<object>[]
        {
            (IFoo<object>) new Foo<string>(),
            new Foo<object>(),
        };
    }

    public static void GoodAnswer()
    {
        var foo = new Bar[]
         {
            new Bar<string>(),
            new Bar<object>(),
            new Bar<double>()
         };
    }
}

And to verify solution one can run tests where only GoodAnswerTest will pass:
public class GenericsInArrayTests
{
    [Fact]
    public void QuestionArrayTest()
    {
        Verify.QuestionArray();
    }

    [Fact]
    public void BadAnswerTest()
    {
        Verify.BadAnswerArray();
    }

    [Fact]
    public void GoodAnswerTest()
    {
        Verify.GoodAnswer();
    }
}


Q:

How safe is a PGP private key that has “escaped”, but without its password?

Assuming your PGP private key is protected with a password, and it "escapes", but the password does not, how worried should you be?
Obviously in the real world, you would immediately revoke the key and generate a new one. But on a theoretical level, does having a private key, but not its associated password, get you any closer to decrypting messages encrypted with it?

A:

The point of a password is to prevent the key from immediately being compromised once it leaks.  It should be considered partially compromised though as the security is reduced from the keysize down to the password complexity.  If you have a high complexity password, it may still be an acceptable level of security for your needs, but generally it is advisable to work on replacing the key since security is reduced.
The urgency of the transition depends on your password though.  If your password was "password" then you should immediately stop using it and transition, but if it was something reasonably complex, then you should be able to keep using it for a bit and distribute your new public key to your contacts using it.  Don't use it for anything you need long term privacy on, but it should be fine for communicating out your new credentials with confidence that you still control the private key for the reasonable future.

A:

It's not that hard to brute force the password once you have the key, unless the password is very long.
So having the enrypted key does get the attacker closer to getting the real key. However, make your password 20 characters long (and don't use dictionary words), and  you ought to be fine as such long passwords will take a long time to bruteforce.


Q:

how to start intro.js tour only on first visit to website

I have implemented intro.js to my website. But I wanted to start the tour only on first visit. may be by using cookies.. website is made with html no php..

A:

JavaScript cookies are a solution although I should point out that it will only work for as long as the user keeps the cookie.
//set the cookie when they first hit the site
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

//check for the cookie when user first arrives, if cookie doesn't exist call the intro.
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
  {
  c_start = c_value.indexOf(c_name + "=");
  }
if (c_start == -1)
  {
  c_value = null;
  }
else
  {
  c_start = c_value.indexOf("=", c_start) + 1;
  var c_end = c_value.indexOf(";", c_start);
  if (c_end == -1)
  {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}

code is from http://www.w3schools.com/js/js_cookies.asp
obviously there's some blanks you'll have to fill in there, but it's a good starting point for working with cookies in javascript.
EDIT:
So you want to make a new function, put it in the head, inside script tags (if you have them already, just copy the function into there (you'll want to put the other two functions I provided within the script tag also)).  This function will check to see if you have a cookie.  If you do, just return.  If you don't, create the cookie and run the intro,
<head>
<script type="text/javascript">
function checkCookieIntro(){
   var cookie=getCookie("mySite");

   if (cookie==null || cookie=="") {
      setCookie("mySite", "1",90);
      runIntro();  //change this to whatever function you need to call to run the intro
      }
}

</script>
</head>

now change your body to be:
<body onload="checkCookieIntro()">

so when the body loads it will check to see if a cookie exists, if it doesn't, create a cookie with a value of one that will last for 90 days (unless the user deletes it) and then run the intro.  If the cookie does exist with a value then it does nothing.


Q:

ArangoDB: limit at 10 documents in graph

I have created a Graph in ArangoDB and I want to use it with 15 Collections, but the GUI tells me that:

You can only select 10 items

for each n-tuple (fromCollections, toCollections, EdgeDefinitions).
What can I do to go over the limit?
Thank you.
Daniele

A:

AQL currently has a limit of 32 collections useable in one query. You can create graphs like this in arangosh:
var Graph = require("org/arangodb/general-graph");

A graph with 15 edge collections:
var g = Graph._create("test1",
  [
    Graph._relation("edge_1", "test", "test"),
    ...
    Graph._relation("edge_15", "test", "test")
  ]
);

And another one with 34 edge collections (thats 35 collections combined with the one vertex collection):
var g = Graph._create("test2",
  [
    Graph._relation("edge_1", "test", "test"),
    ...
    Graph._relation("edge_34", "test", "test")
  ]
);

We save a dummy start node for a traversal:
db.test.save({_key: 'a'})

if you now query test1, you will get the expected empty result (we don't have any edges):
db._query("FOR v IN 1..1 ANY 'test/a' GRAPH 'test1' RETURN v")

But if you query test2, you will get:
ArangoError: too many collections (while parsing)

You may work on the test2 graph using the edgeCollectionRestriction option of the GRAPH_* functions to select a subset of the 34 collections configured.
While the webui may be a nice thing for simple tasks, I don't think its useable to achieve creation of tasks like presented above.


Q:

Is there excessive lubricant on my new rear derailleur?

I just received a new Shimano Deore rear derailleur, which has large gobs of lubricant in two locations (one clearly visible in photo). This seems excessive.
Do I leave it, or are they expecting you to wipe the excess away before installing?

A:

All of that goo is very typical of drivetrain components that are fresh from the factory. The factory uses a particularly thick lubricant to protect the parts until they're purchased or installed (lest they sit on a shelf and risk being exposed to moisture).
Basically, the factory is expecting whoever installs said drivetrain components to identify any excessive grease (some of it is there for good cause, such as protecting the inner spring from the elements), wipe it down, and re-lubricate with something lighter!

A:

I'd wipe it off a bit--it won't serve any purpose as it is, apart from collecting dirt.


Q:

Using the next button to replace content on my page, without redirecting me to a new page

I'm trying to make a quiz application that shows answers with radio buttons on the sides. When you press the next button a set of new answers will appear and replace the .
I've managed to make four questions pop up as intended and four new ones popup when I press the next button.
Right now theres one problem, my first set of four answers (with qid = 1) does not dissapear, which is weird since the other set of answers with qid = 2 and 3 does and replace eachother whenever I press the next button.
How do I make it so that the new answers appear and replace the old answers?
Here is my code so far PHP:
$qid1 = 1;

$sql1 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid1'");

while($row=mysqli_fetch_assoc($sql1))
{

echo "<input type='radio' name='answer1' value='".$row['Point']."'>"
        .$row['answer'] ."
";

}
echo "<input type='submit' name='forward1' value='next'>";
$qid2 = 2;

$sql2 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid2'");

while($row2=mysqli_fetch_assoc($sql2)){
if (isset($_POST['forward1'])) {

echo "<input type='radio' name='answer2' value='".$row2['Point']."'>"
        .$row2['answer'] ."
";

}
}

echo "<input type='submit' name='forward2' value='next'>";
$qid3 = 3;

$sql3 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid3'");

while($row3=mysqli_fetch_assoc($sql3)){
if (isset($_POST['forward2'])) {

echo "<input type='radio' name='answer3' value='".$row3['Point']."'>"
        .$row3['answer'] ."
";

}
}
echo "<input type='submit' name='forward3' value='next'>";

A:

You need to separate your inputs with form tags. For each of your loops do something like this..
echo "<form>";
$sql3 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid3'");
while($row3=mysqli_fetch_assoc($sql3)){
    if (isset($_POST['forward2'])) {
        echo "<input type='radio' name='answer3' value='".$row3['Point']."'>"
        .$row3['answer'] ."
";
    }
}
echo "<input type='submit' name='forward3' value='next'>";
echo "</form>";

Try this..
<?php

$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) || die("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');

// let's put the qid in a session var
session_start();
$qid = isset($_SESSION['qid']) ? $_SESSION['qid']+1 : 1;
$_SESSION['qid'] = $qid;

ob_start();

echo "<form>";
$sql1 = mysqli_query($connect,"SELECT * FROM question where qid ='$qid'");

while($row1=mysqli_fetch_assoc($sql1))
    echo "<input type='radio' name='answer1' value='{$row1['Point']}'>{$row1['answer']}
";

echo "<input type='submit' name='forward1' value='next'>";
echo "</form>";

$output = ob_get_clean();

?>

?><!DOCTYPE html>

        <meta charset="utf-8">

        <?php echo $output; ?>


Q:

Suddenly getting "Login timeout expired" error when connecting to SQL Server

Other people have asked this question, but I didn't find an answer that specifically addresses the problem I was getting nor that solved the issue. So I'm posting the question and answer.
A few days ago I had a couple automated scripts that connect to SQL Server and export some data, suddenly stop working. They've been running fine for like 7 years, so that this was odd. Both scripts use different methods to connect. One uses a Perl library, the other uses the bcp command. But both were getting the same error. I'll just show the bcp command for brevity. This is all running on Windows Server 2008, with SQL Server 2008 R2, v10.50. This is what I was running:
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp.exe" "<my query>" queryout "<output file name>" -T -S MYSERVER -c -k

This is the error I was getting:

SQLState = 08001, NativeError = 10061
  Error = [Microsoft][SQL Server Native Client 10.0]TCP Provider: No connection could be made because the target machine actively refused it.
SQLState = 08001, NativeError = 10061
  Error = [Microsoft][SQL Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.
SQLState = S1T00, NativeError = 0
  Error = [Microsoft][SQL Server Native Client 10.0]Login timeout expired

A:

The solution was pretty simple. I just added the port number to the server name (changed MYSERVER to MYSERVER,1433). So my final bcp command looked like:
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp.exe" "<my query>" queryout "<output file name>" -T -S MYSERVER,1433 -c -k

I'm not sure what changed to require including the port. But that's all it took.
It's kinda weird that this is the default port. You'd think bcp would use that without needing to explicitly set it. Though, this could just be some weird server configuration thing that suddenly requires the port.


Q:

Automatic two columns with CSS or JavaScript

I'm currently developing a website and my client wants the text of various articles to overflow into two columns. Kind of like in a newspaper? So it would look like:
Today in Wales, someone actually      Nobody was harmed in
did something interesting.            the incident, although one
Authorities are baffled by this       elderly victim is receiving
development and have arrested the     counselling.
perpetrator.

[my really bad attempt at coming up with something to write]
Is there a way I can do this with just CSS alone? I'd prefer not to have to use multiple divs. I'm open to using JavaScript too, but I'm -really- bad at that, so help would be appreciated. I was thinking maybe JavaScript could count how many <p>'s there are in the content div, and then move the second half of them to be floated right based on that? Maybe? Advices would be appreciated :D

A:

the good news is, there is a CSS only solution. the bad news is, there isn't any major support for it in existing browsers. if it was implemented, it would look like this:
div.multi {
  column-count: 3
  column-gap: 10px;
  column-rule: 1px solid black;
}

i think for now your best bet is probably server side as mentioned by monoxide

A:

I'd probably handle it in your backend, whatever that happens to be. An example in PHP might look like:
$content = "Today in Wales, someone actually did something...";
// Find the literal halfway point, should be close to the textual halfway point
$pos = int(strlen($content) / 2);
// Find the end of the nearest word
while ($content[$pos] != " ") { $pos++; }
// Split into columns based on the word ending.
$column1 = substr($content, 0, $pos);
$column2 = substr($content, $pos+1);

It should probably be possible to do something similar in JavaScript with InnerHTML, but personally I'd avoid that whole situation because more and more people are using plugins like NoScript that disables JavaScript till it's explicitly allowed for x site, and above anything else, div's and CSS were designed to degrade nicely. A JavaScript solution would degrade horribly in this case.

A:

Here's a JQuery plugin which does columns automatically, and can even vary number of columns based on screen size.
I haven't used this myself, but check it out.


Q:

PushAsync is not supported globally on Android, please use a NavigationPage

I'm doing a Master Detail Page as a menu and I'm getting this error:

PushAsync is not supported globally on Android, please use a NavigationPage.

When I try to instantiate another page. I believe my code already creates a navigation page when instantiate the page, but I'm not sure. Can someone help me?
App.xaml.cs:
public partial class App : Application
{
    static public MasterDetailPage MasterDetail { get; set; }

    public async static Task NavigateMasterDetail(Page page)
    {
        App.MasterDetail.IsPresented = false;
        await App.MasterDetail.Navigation.PushAsync(page);
    }

    public App ()
    {
        InitializeComponent();

        MainPage = new selectPage();
    }

Page that carry the menu, selectPage:
public partial class selectPage : MasterDetailPage
{
    public selectPage()
    {
        InitializeComponent();

        this.Master = new Master();
        this.Detail = new NavigationPage(new Detail());

        App.MasterDetail = this;
    }
}

Master.xaml.cs:
public Master ()
{
    InitializeComponent ();

    toDivPage.Clicked += async (sender, e) =>
    {
        await App.NavigateMasterDetail(new MainPage());
    };

    toBiqPage.Clicked += async (sender, e) =>
    {
        await App.NavigateMasterDetail(new MainPage());
    };
}

Detail.xaml.cs is empty.

A:

I believe you have to use NavigationPage in your App.xaml.cs.
In your App.xaml.cs make sure your constructor or App method looks like this
public App ()
    {
        InitializeComponent();
        MainPage = new NavigationPage(new selectPage());
    }

I hope this helps


Q:

Ie8 and below ODDLY ignoring all CSS

I've never run into this before, but upon checking my work
http://ryanspahn.com/avia8/
in ie8 and below I am noticing it completely ignores the css.  The css is being read in other browsers but not in ie8 and below.
I've never seen this before.  Anyone have a suggestion?

A:

Check style.css, line 51:
#extra-spacing {
    margin: 17px 0 0 0;
    padding: 0 0 0 7px;" /* <- extra quote */
}

When I removed the extra quote, it worked for me.

In the interest of education, this is how I found the problem:
First, I used IE9's developer toolbar (press F12 on the keyboard) to switch the browser mode to IE7.  (IE8 also has the developer toolbar)  Then I looked on the CSS tab and noticed that it was only loading a partial set of rules.  Since it stopped at the #extra-spacing rule, I knew there was probably a syntax error there.


Q:

MATLAB script use in System verilog using SNPS VCS tool

I have coded an algorithm using MATLAB R2019 script and i want it  to be called in an System verilog file i.e The output generated by the  matlab script is actually to be fed into the testbench written using SV. I dont want to use HDL coder tool as the algorithm is quite complex and re-coding it  in SV/ C is quite difficult. I use synopsys VCS tool for compilation and elaboration.
My question is :
1. Is it possible that a MATLAB script to be called in testbench written in SV ? I've heard about DPI, but not much idea on it, or worked on it.
2. Can the output of the MATLAB script stored in a separate file, let's say for example a text file and i can call that file in my SV test bench.?

A:

To answer your questions in order, it is indeed possible.
You need to do the following:

In SV, import a C function (extern DPI-C) that you will call as required. Say we call this callMatlabFn
In C, define an extern function called callMatlabFn. This will then actually call your matlab fn. Have a look here for calling matlab in C : https://www.mathworks.com/help/matlab/matlab_external/call-matlab-functions-from-c-1.html
Note, you could return data via DPI but that may have a different meaning. It may be best to return any data in SV via reference in an output arg to the imported fn.

Finally, text File I/O in SV is implemented via the following system tasks:
$fopen (file_name) ;
$fclose (file_name) ;
$fdisplay (arguments) ;
$fwrite (arguments) ;
$fstrobe (arguments) ;
$fmonitor (arguments) ;
$readmemb ("file", memory_identifier [,begin_address[,end_address]]) ;
$readmemh ("file", memory_identifier [,begin_address[,end_address]]) ;


Q:

Do browsers request images that have been overwritten in CSS?

Let's say I have CSS that looks like this:
#element {background-image: url("image1.png");}
#element {background-image: url("image2.png");}

Will the browser:

Request image1.png, then request image2.png and display it? Or...
Parse the CSS first, see that the selector specifying image2.png takes priority, and only request and display image2.png?

A:

It parses the CSS first, and then requests the image, so image1.png would not be downloaded

A:

From some quick testing with Chrome and the Developer Tools:

If #element does not exist then neither image is downloaded, since the browser has no matching element to apply the style to
If #element exists the usual CSS cascading and specificity rules apply and only image2.png will be downloaded since that rule appears after the image1.png rule.

That said, other browsers may behave differently.


Q:

Get distinct rows combined from multiple fields (including a joined one)

I've got two tables:
Products
ID   productname    organization
---  ------------   ------------
1         X            orga #1
2         X            orga #2

Artifacts
ID   productID        status     revision  platform
---  ------------   ----------   --------  --------
1         1          milestone    0.9.0      win
2         1          milestone    0.9.0      osx
3         2           release     1.0.0      win

What I need to combine are artifacts containing the same productId,status,revision. Their only difference is the platform which isn't part of the resultset.
The resultset should contain:
artifact-id, status, revision, productname and organization
Can anyone help me out with that?

A:

SELECT a.id artifactID, status, revision, productname, organization
FROM Products p
JOIN Artifacts a ON a.productID = p.id
GROUP BY productID, status, revision


Q:

Create subcolumns in pandas dataframe python

I have a dataframe with multiple columns
df = pd.DataFrame({"cylinders":[2,2,1,1],
                  "horsepower":[120,100,89,70],
                  "weight":[5400,6200,7200,1200]})

 cylinders horsepower weight
0  2          120       5400
1  2          100       6200
2  1           80       7200
3  1           70       1200

i would like to create a new dataframe and make two subcolumns of weight with the median and mean while gouping it by cylinders.
example:
                        weight
  cylinders horsepower  median  mean
0  1          100       5299    5000
1  1          120       5100    5200
2  2           70       7200    6500
3  2           80       1200    1000

For my example tables i have used random values. I cant manage to achieve that.
 I know how to get median and mean its described here in this stackoverflow question.
:
df.weight.median()
df.weight.mean()
df.groupby('cylinders') #groupby cylinders

But how to create this subcolumn?

A:

The following code fragment adds the two requested columns. It groups the rows by cylinders, calculates the mean and median of weight, and combines the original dataframe and the result:
result = df.join(df.groupby('cylinders')['weight']\
           .agg(['mean', 'median']))\
           .sort_values(['cylinders', 'mean']).ffill()
#   cylinders  horsepower  weight    mean  median
#2          1          80    7200  5800.0  5800.0
#3          1          70    1200  5800.0  5800.0
#1          2         100    6200  4200.0  4200.0
#0          2         120    5400  4200.0  4200.0

You cannot have "subcolumns" for select columns in pandas. If a column has "subcolumns," all other columns must have "subcolumns," too. It is called multiindexing.


Q:

Merge 2 JSON Strings into one by different keys in PHP

I am trying to combine 2 JSON objects from an API with 2 different id keys.
I have tried some code in php based on my working code in react native(javascript) but rebuilding the code did not work as expected.
sample first JSON:
[{
    poiNumberWinter: null,
    minAge: null,
    maxAge: null,
    minSize: 100,
    maxSize: null,
    minSizeEscort: 1,
    id: 1,
    titleImageId: 390,
    titleImageWinterId: null,
    createdAt: "2018-03-14T15:45:47.000Z",
    updatedAt: "2019-03-26T10:58:44.000Z",
    _titleWinter: null
}]

sample second JSON:
[{
    open: false,
    poiId: "1",
    closing: null,
    opening: "2019-08-15 10:00:00",
    showTimes: null,
    waitTime: null,
    updatedAt: "2019-08-15T20:12:40.000Z",
}]

This is what I have tried:
$rideTimesconverted = json_decode($rideTimes);
$metaDataConverted = json_decode($metaData);
$fullRideData = array();
for ($i = 0; $i < count($rideTimesconverted); $i++) {
   $test = array_filter($metaDataConverted, function ($item) use (
     $i,
     $rideTimesconverted
   ) {
      return $item['id'] === (int) $rideTimesconverted[$i]['poiId'];
   });
      array_push($fullRideData, $rideTimesconverted[$i], $test);
}

based on my React Native code which works perfectly:
let rideTimes = await GetApiData.getRidesTime();
let rideMetaData = await GetApiData.getRidesMetaData();
let fullRideData = [];
    for (let i = 0; i < this.state.rideTimes.length; i++) {
        fullRideData.push({
           ...this.state.rideTimes[i],
           ...this.state.rideMetaData.find(
              itmInner =>
                  itmInner.id ===
                      parseInt(this.state.rideTimes[i].poiId)
              )
        });
    }

But the results get mixed up really weird:
{
open: false,
poiId: "1",
closing: null,
opening: "2019-08-15 10:00:00",
showTimes: null,
waitTime: null,
createdAt: "2019-08-15T22:18:03.000Z",
updatedRow: "2019-08-15T22:18:03.000Z"
},
  [
    {
        poiNumberWinter: null,
        minAge: null,
        maxAge: null,
        minSize: 100,
        maxSize: null,
        minSizeEscort: 1,
        id: 1,
        titleImageId: 390,
        titleImageWinterId: null,
        createdAt: "2018-03-14T15:45:47.000Z",
        updatedAt: "2019-03-26T10:58:44.000Z",
        _titleWinter: null
    }
],

I want this result, merged on poiId and id being the same:
[{
    open: false,
    poiId: "1",
    closing: null,
    opening: "2019-08-15 10:00:00",
    showTimes: null,
    waitTime: null,
    createdAt: "2019-08-15T22:18:03.000Z",
    updatedRow: "2019-08-15T22:18:03.000Z"
    poiNumberWinter: null,
    minAge: null,
    maxAge: null,
    minSize: 100,
    maxSize: null,
    minSizeEscort: 1,
    id: 1,
    titleImageId: 390,
    titleImageWinterId: null,
    createdAt: "2018-03-14T15:45:47.000Z",
    updatedAt: "2019-03-26T10:58:44.000Z",
    _titleWinter: null
}]

A:

This function should do the job if I read your question correctly.
$rideTimes = '[{
    "poiNumberWinter": null,
    "minAge": null,
    "maxAge": null,
    "minSize": 100,
    "maxSize": null,
    "minSizeEscort": 1,
    "id": 1,
    "titleImageId": 390,
    "titleImageWinterId": null,
    "createdAt": "2018-03-14T15:45:47.000Z",
    "updatedAt": "2019-03-26T10:58:44.000Z",
    "_titleWinter": null
},
{
    "poiNumberWinter": null,
    "minAge": null,
    "maxAge": null,
    "minSize": 100,
    "maxSize": null,
    "minSizeEscort": 1,
    "id": 3,
    "titleImageId": 390,
    "titleImageWinterId": null,
    "createdAt": "2018-03-14T15:45:47.000Z",
    "updatedAt": "2019-03-26T10:58:44.000Z",
    "_titleWinter": null
}]';

$metaData = '[{
    "open": false,
    "poiId": "1",
    "closing": null,
    "opening": "2019-08-15 10:00:00",
    "showTimes": null,
    "waitTime": null,
    "updatedAt": "2019-08-15T20:12:40.000Z"
},
{
    "open": false,
    "poiId": "2",
    "closing": null,
    "opening": "2019-08-15 15:00:00",
    "showTimes": null,
    "waitTime": null,
    "updatedAt": "2019-08-15T20:12:40.000Z"
}]';

function someFancyName($arrRideTime, $arrMetaData)
{
    $hits = [];
    foreach ($arrRideTime as $rTime) {
        foreach ($arrMetaData as $mData) {
            if ($mData['poiId'] == $rTime['id']) {
                $hits[] = array_merge($rTime, $mData);
            }
        }
    }
    return $hits;
}

$arrRideTime = json_decode($rideTimes, true);
$arrMetaData = json_decode($metaData, true);
echo '
';
var_dump(someFancyName($arrRideTime, $arrMetaData));
echo '
';


Q:

Avoid code duplication when reading/serializing from DbDataReader?

Consider the FetchData method below. It is designed to avoid duplicating the database query code every time you want to fetch some data from the database.
List<MyData> myData = new List<MyData();
FetchData((IDataReader reader) =>
   {
       myData.Add(new MyData(reader.GetString(0), reader.GetInt32(1)));
   }, "usp_get_my_data");

It works, but it would be nice if this object creation could somehow live inside the FetchData method.
Is there a better approach?
Perhaps FetchData can be modified to return a list of some type X directly?
protected void FetchData(Action<IDataReader> processor, String query)
{
    using (var connection = CreateConnection())
    {
        connection.ConnectionString = ConnectionString;
        connection.Open();

        using (var command = connection.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = query;

            using (IDataReader reader = command.ExecuteReader())
            {
                while (reader.read())
                {
                    processor(reader);
                }
            }
        }
    }
}

A:

Using generics maybe?
protected IEnumerable<T> FetchData<T>(Func<IDataReader, T> processor, String query)
{
    using (var connection = CreateConnection())
    {
        connection.ConnectionString = ConnectionString;
        connection.Open();

        using (var command = connection.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = query;

            using (IDataReader reader = command.ExecuteReader())
            {
                while (reader.read())
                {
                    yield return processor(reader);
                }
            }
        }
    }
}

Then you can use the enumeration however you want:
var myData = FetchData<MyData>(reader => new MyData(reader.GetString(0), reader.GetInt32(1)), "usp_get_my_data").ToList();


Q:

locals() and object reference in python

I found something curious about how python tracks objects in locals().
Considering the following script:
import gc

class T(object):
    pass

def func1():

    t = T()

    #locals()
    del t
    #locals()

    for o in gc.get_objects():
        if type(o) is T:
            print("STILL EXISTS")

func1()

Running with both locals() calls commented (as above) gives me no messages, indicated that the T() object created was garbage collected.
When I run it with the first locals() command (removing the first comment), it seems to create a dictionary that contains a reference to my t object. This dictionary is not associated to any names, so I wouldn't expect this dict to live as without being garbage collected.
The problem is that, running the code, I get "STILL EXISTS". Even if I delete t from the function namespace, the object is not garbage collected as the dict returned by locals() is still referring to it.
Funny enough, if I call locals() again (removing the second comment in the code above), then somehow the dictionary gets updated, it does not contain t in it and the object is garbage collected successfully (and I don't get an "STILL EXISTS" message).
I find this behaviour a bit weird.
Questions are:

Is it normal that the dictionary returned by locals() is long
lived, even without associating it with any names?
Is it normal or is there any reason that this dictionary does not get updated automatically when deleting names from the current scope?

Edit: I am using cpython 3.6
Thanks!

A:

locals() is weird. Inside a function, every locals() call copies the current local variable values into a dict associated with the stack frame and returns the dict. The dict is not used for actual local variable lookup, but it is attached to the frame object, and it is not a new dict every time; all locals() calls in the same stack frame reuse the same dict.
When you call locals(), the locals dict now has a reference to all objects currently referred to by local variables. This will keep those objects alive until either the stack frame dies, or a new locals() call is made inside that stack frame with different local variable values. A few other things will also update the locals dict, such as retrieving the f_locals attribute of the stack frame object, but local variable assignment does not update the locals dict by itself.


Q:

How do I change the default database schema in odoo?

By default when I create a new database in odoo, the tables are created in the public schema. Is there a way to change this configuration and that odoo create and use another defined scheme?

A:

There is no way to do that, odoo use it by default and it don't provide any config for this.
And you cannot do this because a lot of the module also use sql query that retrieve the data from the public schema.
Like account, amail, sale........  etc. They assume that it's public always.


Q:

How to 'mirror' live webcam video when using cv2?

I want to have two different outputs of webcam videos, one being the normal webcam footage and the other to be the "mirrored" version of it.  Is that possible with cv2?
import time, cv2

video=cv2.VideoCapture(0)
a=0
while True:
    a=a+1
    check, frame= video.read()

    gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow("Capturing",gray)

    key=cv2.waitKey(1)

    if key==ord('q'):
        break
print(a)

video.release()
cv2.destroyAllWindows

A:

In short, Yes it is possible using cv2. I have made some modification in your code to make it happen.
# Loading modules
import cv2
import numpy as np     # Numpy module will be used for horizontal stacking of two frames

video=cv2.VideoCapture(0)
a=0
while True:
    a=a+1
    check, frame= video.read()

    # Converting the input frame to grayscale
    gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Fliping the image as said in question
    gray_flip = cv2.flip(gray,1)

    # Combining the two different image frames in one window
    combined_window = np.hstack([gray,gray_flip])

    # Displaying the single window
    cv2.imshow("Combined videos ",combined_window)
    key=cv2.waitKey(1)

    if key==ord('q'):
        break
print(a)

video.release()
cv2.destroyAllWindows

Hope you get what you were looking for :)


Q:

What should a rescue team be equipped with?

The last weekend when I was coming back home from a trek on Sunday noon, I got a news about this accident that took place. The place was on the way, so instead of choosing to rest at home, I chose to alight at the station closest to the place where this happened and add my ounce of help if it was needed. I know those hills very well, and AFAIK the rescue was not that difficult. When I reached there, I was horrified seeing the people who were there as a rescue team. No preparations at all, Lack of necessary equipment. Later after discussing with them, I came to know that the team was formed out of local cops and Fire-Brigade (Fire station guys) dept. Except for Fire fighters, there was no one who was in a good shape to rescue.
I know this may (rather must) sound absolutely horrible that the most of the part in our country, except for Himalayas, there are no dedicated rescue teams for trekking/mountaineering and other adventure stuff. Its the local hikers who coordinate at the juncture and launch a rescue op.
In that sense, if a team plans for it, what all equipment should a rescue team have with them? I can pick most of the things like a Foldable/portable stretcher, Rope, Climbing equipment, Flashlights, Ready-to-eat food (probably dry fruits), etc..
But may be answers here would help to jot down a concrete list.

A:

To be honest, the most important thing a Rescue Team needs to have is plenty of manpower (and womanpower!) with training and experience  (speaking as a member of a UK Cave Rescue Team).

A:

Below is the bare minimum list of gear I would require anyone on my team to carry during and rescue operation. It does not include any of the numerous pieces of rope equipment that members of the rope team would cary in addition to the basic equipment ( only specific team members that have completed extensive training are qualified to be involved in any of the rope operations ) and, it is just equipment. Having the right equipment makes no guarantee of the training and skills needed to cary out a rescue operation. The worst thing you could possibly do is attempt a rescue without the skills and training needed and end up injuring or killing yourself in the process.
That said, enjoy:

Weather appropriate top and bottom base layer
Weather appropriate top and bottom outer layer
Waterproof breathable coat with hood ( brightly colored )
Weather appropriate gloves
Lug sole boots, gaiters
Climbing Helmet
3 pairs of weather appropriate socks
Extra sweater
Compass with mirror and declination adjustment
GPS Device(s)
VHF and UHF radio
Waterproof notepad and pen
Area maps
Fixed blade knife
Heavy duty survival blanket
Survey tape
Whistle
Fire starters
2 pieces of 20 foot 1" tubular webbing
50 feet of 500 pound nylon cord
Storm proof wooden matches
Waterproof match holder
Minimum 24 hour supply of food and snacks
Eye protection
Nylon tarp
Headlamps, extra batteries
Spare flashlight
Minimum 3 liters of water
Wood saw
2 plastic bags
Duct tape
Metal cup or small pot
Trekking poles
First aid kit with ace wrap/israeli bandage, heat and ice packs, trauma pads and tape
Weather appropriate snow gear
A backpack that fits you and can hold all of this gear.

A:

In addition to personal equipment appropriate to the terrain and conditions there are some rescue specific basics which should be easy to provide, this is more geared to providing support to the main search and rescue effort than actually going out at the sharp end yourself. Obviously a lot of search and rescue kit and training is quite specific but the support logistics are more generic and can be just as important :

Shelter : this should be easy to erect around a casualty in any terrain so things like tarps and blankets are preferable to tents.
Medical : even if you don't have proper medics,  basics like field dressings could make all the difference.
Communications : the ability to communicate the location of casualties quickly is very important in getting them treated and evacuated. This requires good communications both inside the rescue team and with the outside world. This need not be hugely sophisticated but things like procedures for RV points and packs of flares and chemical lights can greatly help air and vehicle rescue. Communications can also include keeping up to date with weather forecasts and keeping track of who is doing what in the overall operation.
Evacuation gear : here it is important to say that the decision to evacuate on  foot vs waiting for better equipped help is a critical one, especially where the casualty has traumatic injures  but there will be circumstances where it has to be done. Here a proper collapsible splint stretcher is idea but the knowledge to
improvise something from a tarp cut poles and rope is a lot better than nothing. Also if you are evacuating a casualty on foot every extra person who can help will significantly contribute to the rescue as carrying a casualty over rough terrain for any distance is exhausting and the original search team may already be tired by this point in the operation.
Organisation : in all emergencies command and control is always a big problem as you often have several different groups or organisations trying to cooperate and confusion can be as big an enemy as weather or terrain. even so taking on simple organisational jobs like keeping a list of names of who is involved an logging them in and out of base camp can make a big difference. Equally setting up an HQ with a table and some maps of the area. Often bad situations are made worse by skilled and well intentioned people acting at crossed-purposes

Another very important consideration is that an ad-hoc rescue team don't become casualties themselves. While passers by may be keen to help the rescue leaders need to take responsibility for their safety as well and at the very least they should be competent, fit and equipped to carry out any tasks assigned to them. Similarly  individually going off on their own may do more harm than good and a rescue organiser should establish proper channels of control and communication from the start.
As an extension of this lightweight high visibility vests, torches and chemical lights and IR markers are a very useful (and inexpensive) part of centralised rescue kit as well as the more obvious portable radios etc.
Similarly setting up a temporary base with shelter and hot food and drink for rescue workers is a big asset and this can be a very useful role for volunteers of uncertain experience.


Q:

Is there any way to check if any or all characters are present in a string in C?

I was trying to check and see if I give an array of characters -
like this
char  array_values[] = { 'A','B','C','D','a','b','c','d' };

and then running a sort of character matching in multiple strings e.g.-
....
str1 = 'AACDBACBAabcAcddaAABD'
str2 = 'aacbdAABDCAaDDCBCAabc'
....

and then returning a count of each char present in the strings.
I know it's easily done in python, R, perl, but I wanted to figure this out in C.
Maybe something like a regular expression? Any ideas?

A:

The easiest way to do it in C is to count each character regardless of its presence in the array_values, then use array_values items as indexes into the array of counts to get the results:
int count[256];
for (int i = 0 ; i != 256 ; count[i++] = 0);
// The example works with a single string. For multiple strings,
// iterate over the strings from your source in a loop, assigning str
// and incrementing the counts for each of your strings.
char *str = "AACDBACBAabcAcddaAABD";
for (char *p = str ; *p ; count[(unsigned char)*p++]++);
char array_values[] = { 'A','B','C','D','a','b','c','d' };
for (int i = 0 ; i != 8 ; i++) {
    printf("Found '%c' %d times", array_values[i], count[(unsigned char)array_values[i]]);
}

Here is a demo on ideone.


Q:

PHP/MySQL - Friends List SQL Query

I'm going based off this guide in a previous StackOverflow post:
"Table Name: User
Columns:
    UserID PK
    EmailAddress
    Password
    Gender
    DOB
    Location

TableName: Friends
Columns:
    UserID PK FK
    FriendID PK FK
    (This table features a composite primary key made up of the two foreign
     keys, both pointing back to the user table. One ID will point to the
     logged in user, the other ID will point to the individual friend
     of that user)

Example Usage:

Table User
--------------
UserID EmailAddress Password Gender DOB      Location
------------------------------------------------------
1      bob@bob.com  bobbie   M      1/1/2009 New York City
2      jon@jon.com  jonathan M      2/2/2008 Los Angeles
3      joe@joe.com  joseph   M      1/2/2007 Pittsburgh

Table Friends
---------------
UserID FriendID
----------------
1      2
1      3
2      3"

Now, I have all that done, and I've created this query:
if ($_SESSION["user_id"]) {
    $user_id = $_SESSION["user_id"];
    $query = "SELECT * ";
    $query .= "FROM friends ";
    $query .= "WHERE ";
    $query .= "user_id OR friend_id = '{$user_id}' ";
    $result = mysqli_query($connection, $query);
    $result_set = mysqli_fetch_assoc($result);
    print_r($result_set);

Yay! This print_r gets the associated array that I expected.
But now, because either user_id OR friend_id can be the logged in user, I'm stumped s to what kind of query I need to go with to be able to actually display the friends list.
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE id = ''

This is about as far as I've gotten due to my confusion.
Any point in the right direction would be amazing. thank you!

A:

Oh I get it. You (the user) want to display your friends (other users)
Try this:
SELECT U.EmailAddress, U.Gender, U.DOB, U.Location FROM User U
LEFT JOIN Friends F on U.UserID = F.Friend_ID WHERE F.User_ID = 1;

And then just change 1 to whatever the logged in user's id is.
Cheers!