Q:

Get Material 2 theme color scheme/palette for other elements

I am building an application but I want to keep a consistent color scheme that can be changed with settings so im using Material (2) with angular(2+), but I am not sure how to get the color scheme on elements that dont directly offer the ability to color them with color="primary" so im left with trying to figure out how to obtain the color/color scheme that my Material 2 theme uses.
And i want it to change when the theme changes, for instance my navbar will adapt to the theme change because its set to
<mat-toolbar color="primary" class="fixed-navbar mat-elevation-z10">

But a grid element from Material 2 doesnt take the same argument so Im left to attempt to style it in a close enough color or simply not match it at all (and it wont adjust to theme changes) as seen here:

I want it to match the color with the theme mat, which is here (and gets changed on options selected in navbar settings)
@import '~@angular/material/theming';

@include mat-core();

$candy-app-primary: mat-palette($mat-red);
$candy-app-accent:  mat-palette($mat-deep-orange, A200, A100, A400);
$candy-app-warn:    mat-palette($mat-red);
$candy-app-theme: mat-dark-theme($candy-app-primary, $candy-app-accent, $candy-app-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
.default {
  @include angular-material-theme($candy-app-theme);
}
.light {
  $light-primary: mat-palette($mat-blue, 200,300, 900);
  $light-accent:  mat-palette($mat-light-blue, 600, 100, 800);
  $light-warn:    mat-palette($mat-red, 600);
  $light-theme: mat-dark-theme($light-primary, $light-accent, $light-warn);
  @include angular-material-theme($light-theme);
}
@include angular-material-theme($candy-app-theme);

A:

I found an awesome workaround!!!!
I'm so excited to show this because its been bugging me how to implement this for ages.
So here goes;
First, change all of your css files to scss;
For existing projects

Run in console ng set defaults.styleExt=scss

(ng set seems to have been depreciated, but you can check out this for a fix thanks to user @wlyles get/set have been deprecated in favor of the config command )

Rename all existing .css files to .scss
Manually change the file extention of styles in .angular-cli.json from .css to .scss
If you didnt use a tool like WebStorm Refactor to rename then manually change all the styleUrls from .css to .scss

For future projects

Just for your new project simply use ng new your-project-name --style=scss
For all new projects to use scss use ng set defaults.styleExt=scss --global

Now you will need to have a theme.scss file in your app root like so:

Now in your style.scss file you want to add the following (as you can see I referrence background-color but you can change this to any element to theme your site however you want):
EDIT: You dont NEED to put this custom @mixin element in your styles.scss you can put it in any one of your *name*.component.scss and then simply import and include it the same way you do with the example given!
@import '~@angular/material/theming';

// Define a custom mixin that takes in the current theme
@mixin theme-color-grabber($theme) {
  // Parse the theme and create variables for each color in the pallete
  $primary: map-get($theme, primary);
  $accent: map-get($theme, accent);
  $warn: map-get($theme, warn);
  // Create theme specfic styles
  .primaryColorBG {
    background-color: mat-color($primary);
  }
  .accentColorBG {
    background-color: mat-color($accent);
  }
  .warnColorBG {
    background-color: mat-color($warn);
  }
}

Now go to your theme.scss file that you use to theme your Material 2 items, if you need help theming check this out: Material 2 Github - Theming guide
Now open your theme.scss and import your style.scss, since my theme.scss is within the root of the /src/app/theme.scss folder I must first go out of it to reference my /src/styles.scss global styling file like so;
@import '../styles';

Then we must actually include our new custom @mixin we created in ALL our themes (if you have multiple like I do, so it changes color according to current selected theme).

Include it above the actual angular-material-theme include, like so:

@include theme-color-grabber($theme);
@include angular-material-theme($theme);

If you have any themes like me add it in the same position like so:
.light {
  $light-primary: mat-palette($mat-blue, 200,300, 900);
  $light-accent:  mat-palette($mat-light-blue, 600, 100, 800);
  $light-warn:    mat-palette($mat-red, 600);
  $light-theme: mat-dark-theme($light-primary, $light-accent, $light-warn);
  @include theme-color-grabber($light-theme);
  @include angular-material-theme($light-theme);

}

You can see I added my theme-color-grabber above the include, it doesnt really matter if its above or below the actual theme because its getting the themes colors which is the main point.
My whole themes.scss looks like this:
@import '~@angular/material/theming';
//We import our custom scss component here
@import '../styles';

@include mat-core();

$theme-primary: mat-palette($mat-red);
$theme-accent:  mat-palette($mat-deep-orange, A200, A100, A400);
$theme-warn:    mat-palette($mat-red);
$theme: mat-dark-theme($theme-primary, $theme-accent, $theme-warn);
//
@include theme-color-grabber($theme);
@include angular-material-theme($theme);
.light {
  $light-primary: mat-palette($mat-blue, 200,300, 900);
  $light-accent:  mat-palette($mat-light-blue, 600, 100, 800);
  $light-warn:    mat-palette($mat-red, 600);
  $light-theme: mat-dark-theme($light-primary, $light-accent, $light-warn);
  @include theme-color-grabber($light-theme);
  @include angular-material-theme($light-theme);

}

And finally we can now call on our themes color for a background ANYWHERE!, for instance I give a mat-grid-tile the 'primary' color (it doesn't take the color='' argument, like other elements such as mat-toolbar) by simply setting its class to the appropriate class name like so:
EDIT: In each of your components scss files, you will need to import '<path-to>/theme.scss' in order for your theme to apply to that component. Don't import theme.scss in styles.scss because that will create an import loop!
<mat-grid-list cols="4" rows="4" rowHeight="100px">
  <mat-grid-tile
    colspan="4"
    rowspan="5"
  class="primaryColorBG">

Callum

Tech

      Ambitious and ready to take on the world of Information Technology,

      my love for programming and all things I.T. has not wavered since I first got access

      to my fathers computer at age 9.

  </mat-grid-tile>

</mat-grid-list>

Finally our result will look like this!:
Red theme active

Blue theme active

A:

I personally put those in css4 variables so I can use those without imports like so
background: var(--color-primary)
And here is how to set up the css4 variables
@import '~@angular/material/theming';
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$app-primary: mat-palette($mat-blue);
$app-accent:  mat-palette($mat-orange);
$app-warn:    mat-palette($mat-red);
$app-success: mat-palette($mat-light-green);

// Create the theme object (a Sass map containing all of the palettes).
$app-theme: mat-light-theme($app-primary, $app-accent, $app-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($app-theme);

$primary: map-get($app-theme, primary);
$accent: map-get($app-theme, accent);

:root {
  --color-primary: #{mat-color($app-primary)};
  --color-accent: #{mat-color($app-accent)};
  --color-warn: #{mat-color($app-warn)};
  --color-success: #{mat-color($app-success)};
}

now colors can be used in css files without import with
background: var(--color-primary)

A:

UPDATE:
A new version of this solution was published here:
https://github.com/mirismaili/angular-material-dynamic-themes
If you only need the answer of the asked question, probably is better to refer to the first version of the answer, below. Also, I recommend to read this section of the above repo's documentation: Use material themes for other elements.
But if want other capabilities you see in the below video, I recommend this new approach.

Live demo:
https://stackblitz.com/github/mirismaili/AngularMaterialDynamicThemes

Thank StackBlitz

ARCHIVED ANSWER:

stackblitz here

Most important parts:
In your styles.scss (or themes.scss if you have):
@import '~@angular/material/theming';

@include mat-core();

@mixin define-css-classes($theme) {
    @include angular-material-theme($theme);

    $primary: map-get($theme, primary);
    $accent: map-get($theme, accent);
    $warn: map-get($theme, warn);
    $background: map-get($theme, background);
    $foreground: map-get($theme, foreground);

    // CSS THEME-DEPENDENT-STYLES ARE HERE:
    .theme-dependent-colors {
        background: mat-color($primary);
        color: mat-color($accent);
    }
}

/**
* Define your custom themes in this map.
* The `key` of each member is the name of CSS class for that theme.
* To better understand the schema of the map, see `@each` loop below and especially pay attention to `map-has-key()` functions.
*/
$app-themes: (
        indigo-pink : (primary-base: $mat-indigo, accent-base: $mat-pink),
        deeppurple-amber: (primary-base: $mat-deep-purple, accent-base: $mat-amber),
        pink-bluegrey : (primary-base: $mat-pink, accent-base: $mat-blue-gray, is-dark: true),
        purple-green : (primary-base: $mat-purple, accent-base: $mat-green, is-dark: true),
);

@each $css-class, $theme in $app-themes {
    $primary: if(map-has-key($theme, primary), map-get($theme, primary), mat-palette(map-get($theme, primary-base)));

    $accent: if(map-has-key($theme, accent), map-get($theme, accent), mat-palette(map-get($theme, accent-base)));

    $warn: if(map-has-key($theme, warn), map-get($theme, warn), mat-palette(
            if(map-has-key($theme, warn-base), map-get($theme, warn-base), $mat-red)
    ));

    .#{$css-class} {
        @include define-css-classes(mat-light-theme($primary, $accent, $warn));
    }

    .#{$css-class}-dark {
        @include define-css-classes(mat-dark-theme($primary, $accent, $warn));
    }

    .theme-primary.#{$css-class} {
        background-color: mat-color($primary);
    }

    ...
}

Dynamic-theme-changing, using setTheme() in typescript (see here and here):
import {Component, HostBinding} from '@angular/core';
import {OverlayContainer} from "@angular/cdk/overlay";

const THEME_DARKNESS_SUFFIX = `-dark`;

export class AppComponent {
    @HostBinding('class') activeThemeCssClass: string;
    isThemeDark = false;
    activeTheme: string;

    setTheme(theme: string, darkness: boolean = null) {
        if (darkness === null)
            darkness = this.isThemeDark;
        else if (this.isThemeDark === darkness) {
            if (this.activeTheme === theme) return;
        } else
            this.isThemeDark = darkness;

        this.activeTheme = theme;

        const cssClass = darkness === true ? theme + THEME_DARKNESS_SUFFIX : theme;

        const classList = this.overlayContainer.getContainerElement().classList;
        if (classList.contains(this.activeThemeCssClass))
            classList.replace(this.activeThemeCssClass, cssClass);
        else
            classList.add(cssClass);

        this.activeThemeCssClass = cssClass;
    }

    constructor(overlayContainer: OverlayContainer) {
        this.setThemeClass('indigo-pink', false); // Default theme
    }
}

See other things in stackblitz.

CAVEAT: Adding 8 dynamic material themes to the app (4 lights + 4 darks) increased the size of built styles.css by ~420 kB in my case (compared with one static material theme).


Q:

What is a better way to go for a simple file upload and download: NSURLConnection or ASIHTTP?

I want to include simple file uploading and downloading [any type of file e.g. .pdf, .pptx ,.txt etc] functionality in my application.
What is the better way to opt for using asihttp or NSURLConnection?
Thanx in advance.

A:

Our team is using AsiHttp now, it supports more important functionality like synchronous and asynchronous request, better support for some network activity
AsiHttp


Q:

Getting a complete white image on downsampling

I performed an image downsampling with averaging operation.  The image is divided into 2 by 2 blocks, then it is downsampled by 4 times.  New pixel values of the downsampled image are replaced with the mean of each block as follows:
img = imread('cameraman.tif');
avgfilter = fspecial('average', [2 2]);
avgimg = filter2(avgfilter, img);
down1 = avgimg(1:2:end,1:2:end);
imshow(down1);

I used a grayscale image as input.  However, I'm getting a complete white image as output on downsampling.  Why is this happening?  Please help.

A:

The reason why this is happening is because your average image after you use filter2 is a double type image.  You're not the first person (and probably not the last person...) to experience this mixup with imshow.  In fact, almost all of the problems that I have solved with regards to imshow here on StackOverflow is because of this small mixup with imshow.
You have to be cognizant of the type of image you are trying to display with imshow before you decide to use the function.  Images of type double are expected to have its intensities / colour channels to be in the range between [0,1].  Anything below 0 is set to black while anything beyond 1 is set to white, which is why you are getting a completely white image.
You need to convert back to uint8 to properly display the image.  As such, try doing this before you show your image:
down1 = uint8(down1);
imshow(down1);

When I do this, this is what I get when I show the downsampled image.

Minor comment
FWIW, when it comes to image filtering, I would personally use imfilter instead.  imfilter is designed for image filtering where filter2 is for more generic 2D signals.  One thing that is good about imfilter is that it will output an image of the same type where filter2 will default to double.  I would stay away from filter2 unless you're forced to use it on images.
As such, replace your filter2 syntax with:
avgimg = imfilter(img, avgfilter);

If you do this instead, you don't need to cast your image back to uint8.  You will be able to visualize the results properly with imshow.


Q:

Java Swing MVC architecture

How is a Java Swing application organized to achieve MVC architecture?

A:

See: A Swing Architecture Overview


Q:

What does a pipe (|) do in a CSS selector?

I found the following definition in a CSS stylesheet :
*|*:link {color:#ff00ff;}

What's the use of the |? Is it some sort of CSS Hack?

A:

It separates namespace and element name.
Unless a default namespace has been defined, *|*:link is a complicated way of writing *:link or just :link.
In an XML document, you could have the following:
<el xmlns="http://name/space" />
<style>
@namespace namespace_example url(http://name/space);
namespace_example|el {background: red;}
</style>

A:

It is used with namespaces, defining the namespace|element. For more information, have a look at the documentation here. If there is no namespace defined, it is pointless to define the selectors with namespace *.


Q:

Count method references, because of dex file limitation

I want to know the count of method references in my app. Somone can point me to a fitting profile software ? Or is ther maybe some other solution for this ?

A:

A bit late to the party, but we've recently released a Gradle plugin that will tell you how many method references are in your .apk after every build; it's at https://github.com/KeepSafe/dexcount-gradle-plugin.
If you already have an APK and just want to know how many method references are in it, you can find out on the command line (assuming you are using Mac OS X or a UNIX-like).  Unzip your APK and run the following shell command:
cat classes.dex | head -c 92 | tail -c 4 | hexdump -e '1/4 "%d\n"'

The number of references is part of the dex file header; this pipeline reads the four-byte count at offset 0x5C and prints it as a decimal number.


Q:

how can I add a new action to a controller?

I used the following in routes to add a new action to my Email controller:
   map.resources :emails, :member => { :newfwd => :put}

The expected result was that newfwd_email_path(:id => 1) would generate the following urL:  emails/1/newfwd
It does.  But I get an error, it treats '1' as an action and 'newfwd' as an id.  I want '1' to be interpreted as the id for emails, upon which the newfwd action acts.
I'm not sure what I'm doing wrong. (Note: I am using Rails 2.3.8)

A:

Try
link_to newfwd_email_path(1), :method => :put

:id => 1 is as good as 1 ;)


Q:

Is there any difference between accessing a subject directly on a class or using a getter

Lets say I have a service that exposes a subject:
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Injectable()
export class StateService {
  private mySubject = new BehaviorSubject<string>("test");
  mySubject$ = this.mySubject.asObservable();

  constructor() {}

  updateSubject(value: string) {
    this.mySubject.next(value);
  }

  get mySubject2$() {
    return this.mySubject.asObservable();
  }
}

In my component:
import { Component } from "@angular/core";
import { StateService } from "./state.service";

@Component({
  //...
})
export class AppComponent {
  name = this.state.mySubject$;
  name2 = this.state.mySubject2$;

  constructor(private state: StateService) {}
}

Are there any differences apart from stylistic in terms of using an accessor to return the subject or accessing it directly via a property on the class?

A:

There are two differences:

When you invoke the get accessor, it calls Subject#asObservable to create a new observable for each consumer, whereas the property is a single observable. An observable can have multiple subscribers, so it's slightly less efficient to create multiple observables.
When you use a public property, unless you explicitly mark it readonly, consumers can replace the observable, so that subsequent access wouldn't get the observable linked to the subject the instance is managing.

In your case, I would probably use:
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Injectable()
export class StateService {
  private mySubject = new BehaviorSubject<string>("test");
  readonly mySubject$ = this.mySubject.asObservable();

  updateSubject(value: string) {
    this.mySubject.next(value);
  }
}


Q:

argument defaults to a precedent argument's value

I vaguely remember that it was possible to write something like:
void f(int a, int b=0, bool c=!val);

if some extra stuff was written at the beginning of the arguments list. The example in GCC gives error of val non declared in scope.
Unfortunately, I cannot find any reference on the Internet, so I ask here.

A:

How about overloading f()? It won't be a problem whether val is const or not.
void f(int a, int b, bool c);

void f(int a, int b=0) {
   f(a,b,!val);
}


Q:

Why use multiple OpenGL context

For rendering I have a current GL context associated with a window. In the case where the application renders multiple scenes (for example using accumulation or different viewports) I believe it is ok to reuse the same context.
My question is, why should I use multiple GL contexts? I read in the ARB_framebuffer_object extension spec that calls to MakeCurrent can be expensive, and in the case the ARB_framebuffer_object extension is present I can render on a generic buffer without using MakeCurrent.
Apparently the only reason to use multiple GL context is to avoid to setup context state (pixel store, transfer, point size, polygon stipple...) or to have available multiple render buffers configuration (one context with accumulation, another without). How should I decide when it is better to use an alternative context instead of setting context state?

A:

I usually tend to use additional contexts only when I absolutely have to, such as rendering to multiple GUI windows. For everything else, I use framebuffer objects or state changes.
However, performance recommendations like this do not apply to all cases. If in doubt, you should measure your own application on your own hardware. gDEBugger might help, there's a trial version available.

A:

IIRC, objects like textures and buffer objects can be shared between contexts, so technically you could create a second context in a second thread and load the textures asynchronously there, without worrying whether the first thread is performing the rendering.

A:

If you want to address multiple GPU's, you need to use multiple context since you have at least one drawable per GPU, with a GPU-specific context.


Q:

No language could be found for jsonpath

I'm trying to aggregate messages using jsonpath in activemq.
But when I try to start the activemq, I get such exception:
ERROR: org.apache.camel.RuntimeCamelException: org.apache.camel.FailedToCreateRo
uteException: Failed to create route route2 at: >>> Choice[[When[jsonpath{$.pers
on[?(@.position = 'manager')]} -> [To[activemq:queue:test.manager]]]] Otherwise[
[To[activemq:queue:test.nonManager]]]] <<< in route: Route(route2)[[From[activem
q:queue:test.other]] -> [Choice[[... because of No language could be found for:
jsonpath

My Route looks like this:
from("activemq:queue:test.other")
                .choice()
                .when().jsonpath("$.person[?(@.position = 'manager')]")
                .to("activemq:queue:test.manager")
                .otherwise()
                .to("activemq:queue:test.nonManager")
                .end();

A:

The camel version bundled with ActiveMQ is limited to do basic routing to and from queues.
You can extend the dependencies in your lib/camel with features you want. Start out with the top level jar and grab all dependencies from Maven. I.e. camel--.jar In your case, if you are using activemq 5.11.0, it will be camel-jsonpath-2.14.1.jar
I typically use a script like this (using Apache Ivy to download the dependency graph) in the apache-activemq-5.11.0/lib/camel folder. Adjust script if you need to use Windows or similar.
curl -L -O http://search.maven.org/remotecontent\?filepath\=org/apache/ivy/ivy/2.3.0/ivy-2.3.0.jar
java -jar ivy-2.3.0.jar -dependency org.apache.camel camel-jsonpath 2.14.1 -retrieve "lib/[artifact]-[revision](-[classifier]).[ext]"
rm slf4j-api-1.6.6.jar
rm ivy-2.3.0.jar

Note the cleanup in the end. Remove all dependencies that might cause a conflict with other dependencies already found in ActiveMQ's lib folder.


Q:

Is down voting supposed to be anonymous?

Possible Duplicate:
Revealing voting patterns - new trend?

Is down-voting on SO supposed to be anonymous? I ask because it does not seem to me to be.
Example:
I asked a question today. I got 3 good and 1 mediocre responses. I voted up the two that helped me and accepted the one that worked best. A while later, several new comments from one person appeared, to which I responded (since they were questions for me), and then that same person posted a new answer. This answer was crap. The person missed the whole point of the question and gave vague "pseudo-code" (and calling it that is generous) that basically restated my question.
Though I try to use down votes sparingly, especially when someone takes the time to answer a question I asked, I really want to down vote his answer. However, if I do, then my "reputation" will report "-1 downvoted" today. Since we've been going back and forth in the comments (in my failed attempt to explain the question to him), it's fairly likely that he'll peg me for the down vote.
In rumaging through the his reputation, I noticed that he gets down voted a lot. Moreover, he often votes down things on the same day as he gets down voted. Looking at a few recent questions where he posted an answer that was down voted, it's pretty clear that he (often successfully) down votes questions or competing answers when he is down voted, perhaps based on comments or, as is easier, based on profiles where down votes are recorded.
In this particular case, it's worth it for me to down vote him because (1) it's a stupid answer, (2) I don't live and die by my SO reputation, and (3) it really wasn't a great question that I asked. However, this does bring up the larger point that perhaps a date should not be associated with a down vote.

A:

Yep, voting is supposed to be anonymous and the new design of the reputation tab can sometimes hint on who downvotes but it can't prove anything.
I say go ahead and downvote if you so strongly say it's a bad answer - that's exactly what downvotes exist for, to tell everyone "it's not a good answer".
Worst case you earned yourself nemesis who will stalk you and use all his daily downvotes to downvote questions and answers of yours - at some point he will get tired of this or blocked if there is "vote pattern recognition" that stop one from voting (either up or down) on single member.


Q:

PHP script to return MySQL data into a table, need carriage return

I have a PHP script selecting information from a MySQL database table and flowing it into a table using a while loop and then a foreach loop for each cell creating columns of information (date, image, sentence). My problem is these columns are side-by-side, running across my page and off into the distance (http://dankirchoff.com/drawingweek.php). I need a "carriage return" of some sort to keep them on the web page. I'm trying a modulus using the 'index' field as a counter, which isn't working. Any suggestions?

<?php
 include ("inc_connect.php");
 if ($link !== FALSE) {
     $db = "dkfineart_01";
     mysqli_select_db($db);
     $TableName = "drawingoftheweek";
     $sql = "SELECT * FROM $TableName";
  if ($res = mysqli_query($link, $sql)) {
   if (mysqli_num_rows($res) > 0) {
    while ($drawresults = mysqli_fetch_array($res)) {
     $drawing[] = $drawresults;
    }
    echo "

";
    foreach ($drawing as $draw) {
     echo "" . date('m/d/Y', strtotime($draw['date'])) . "	";
    }
    echo "

";
    foreach ($drawing as $draw) {
     echo "" . "" . "	";
    }
    echo "

";
    foreach ($drawing as $draw) {
     echo "" . $draw['drawingtext'] . "	";
    }
    echo "
";
    foreach ($drawing as $draw) {
     $index = $draw['index'];
      if ($index % 2 === 0) {
       echo "
";
      }
     }
    echo "
";
   }
    mysqli_free_result($res);
   }
   else {
    echo "No matching records are found.";
   }
  }
  else {
   echo "Unable to select from table. " . mysqli_error($link);
  }
 mysqli_close($link);
?>

A:

My suggestion would be to use something other than a table to lay this out and use CSS to create the breaks. This has the side benefit of allowing you to iterate over the results once rather than storing them in an array and iterating over the array multiple times. For example:

<?php
 include ("inc_connect.php");
 if ($link !== FALSE) {
     $db = "dkfineart_01";
     mysqli_select_db($db);
     $TableName = "drawingoftheweek";
     $sql = "SELECT * FROM $TableName";
  if ($res = mysqli_query($link, $sql)) {
   if (mysqli_num_rows($res) > 0) {
                echo "
";
    while ($draw = mysqli_fetch_array($res)) {
                    echo "
";
                    echo "
";
                    echo date('m/d/Y', strtotime($draw['date']));
                    echo "
";
                    echo "
";
                    echo "";
                    echo "
";
                    echo "
";
                    echo $draw['drawingtext'];
                    echo "
";
                    echo "
";
                }
                echo "
";

   }
    mysqli_free_result($res);
   }
   else {
    echo "No matching records are found.";
   }
  }
  else {
   echo "Unable to select from table. " . mysqli_error($link);
  }
 mysqli_close($link);
?>

This uses divs in place of tables and display:inline-block to essentially treat each block like a word and break at the end of a "line."


Q:

How to get outgoing call duration in real time?

Possible Duplicate:
It's possible to get outgoing call duration during call?

I need to show real-time outgoing call duration.
But I do not know when I should start timer.
I must start when get answer from other side.
I tried TelephonyManager.EXTRA_STATE_OFFHOOK -- but it's state is when
I press call-button..
OFFHOOK is the state when call is placed.
So we should be notified when the call is received.
How can we get that?
Can You help me? When I should start count outgoing time?
Thanks
upd..
I think this data produces mobile operator server. And this server return call-duration and current balance after each outgoing call .
Maybe It's right?
I can't find any solution, but after each call value of call duration will be stored in db. We can get it by CallLog.Calls.DURATION
How this value populate field in db?

A:

Using a content Observer to listen Call Logs content URI if it changed:
ContentResolver contentResolver = context.getContentResolver();
CallLogObserver mObserver = new CallLogObserver(new Handler(), context);
contentResolver.registerContentObserver(
    Uri.parse("content://call_log/calls"), true, mObserver);

This is your CallLogObserver:
public class CallLogObserver extends ContentObserver {
    private Context context;

    public CallLogObserver(Handler handler, Context context) {
        super(handler);
        this.context = context;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Log.i(TAG, "CallLogs Onhange()");
        try{
            Cursor c = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null,
                    null, null, CallLog.Calls.DATE + " DESC");
            if (c != null) {
                if (c.moveToFirst()) {
                    int type = Integer.parseInt(c.getString(c
                            .getColumnIndex(CallLog.Calls.TYPE)));
                    /*
                     * increase call counter for outgoing call only
                     */
                    if (type == 2){
                        String number = c.getString(c
                                .getColumnIndex(CallLog.Calls.NUMBER));

                        long duration = c.getLong(c
                                .getColumnIndex(CallLog.Calls.DURATION));

                                                    Log.i(TAG, "numer = " + number + " type = " + type + " duration = " + duration);

                                                }
                }
                c.close();
            }
            else
                Log.e(TAG,"Call Logs Cursor is Empty");
        }
        catch(Exception e){
            Log.e(TAG, "Error on onChange : "+ e.toString());
        }

    }


Q:

Pandas dataframe to structured array with Boolean series

I have a Pandas dataframe which I wish to convert to either a NumPy records array or structured array. I am using Python 3.6 / Pandas 0.19.2 / NumPy 1.11.3.
df = pd.DataFrame(data=[[True, 1, 2],[False, 10, 20]], columns=['a','b','c'])

print(df.dtypes)

a     bool
b    int64
c    int64
dtype: object

My attempts are below:
# record array
res1 = df.to_records(index=False)

# structured array
s = df.dtypes
res2 = np.array([tuple(x) for x in df.values], dtype=list(zip(s.index, s)))

However, the Boolean type doesn't seem to be evident in the dtype attribute of these results:
print(res1.dtype)

(numpy.record, [('a', '?'), ('b', '<i8'), ('c', '<i8')])

print(res2.dtype)

[('a', '?'), ('b', '<i8'), ('c', '<i8')]

Why is this? More generically, is this the only exception, or should we have to check manually each time to ensure the dtype conversion has been processed as anticipated?
Edit: On the other hand, it seems the conversion is correct:
print(res1.a.dtype)     # bool
print(res2['a'].dtype)  # bool

So is this just a display issue?

A:

Curiously, NumPy chooses ? to represent Boolean. From Data type objects (dtype):
'?' boolean
'b' (signed) byte
'B' unsigned byte
'i' (signed) integer
'u' unsigned integer
'f' floating-point
'c' complex-floating point
'm' timedelta
'M' datetime
'O' (Python) objects
'S', 'a'    zero-terminated bytes (not recommended)
'U' Unicode string
'V' raw data (void)

Confusingly, the NumPy Array Interface for access from C extensions uses a different mapping:
t   Bit field (following integer gives the number of bits in the bit field).
b   Boolean (integer type where all values are only True or False)
i   Integer
u   Unsigned integer
f   Floating point
c   Complex floating point
m   Timedelta
M   Datetime
O   Object (i.e. the memory contains a pointer to PyObject)
S   String (fixed-length sequence of char)
U   Unicode (fixed-length sequence of Py_UNICODE)
V   Other (void * – each item is a fixed-size chunk of memory)

Credit to @bobrobbob for finding this in the docs.


Q:

Find the number of multi-subsets of $M = \{r_1a_1,r_2a_2,...,r_na_n\}$

Find the number of multi-subsets of $M = \{r_1a_1,r_2a_2,...,r_na_n\}$. If someone is simply unaware of the term multi-subsets I am asking for the number of all combinations of $M$ where repetitions are allowed.

A:

A multi-subset of M is determined by how many elements of each type $a_1,\cdots,a_n$ that we choose,
so there are $(r_1+1)(r_2+1)\cdots(r_n+1)$ multi-subsets of M altogether.


Q:

How to get the content of /dev/logo in shell?

I can read the content of /dev/logo in C,
fd = open("/dev/logo", O_RDONLY);

len = read(fd, logo_addr, 512);

Now I want to do these things using shell command, how to do?
Can I use
$ adb shell cat dev/logo >logo.dev

?

A:

Are you able to use dd? Something like:
dd /dev/logo bs=1 count=512 of=logo.dev

Assuming you need to read 512 bytes of the device.


Q:

PHPMyAdmin inline edit corrupting serialized data in text field

I have a serialized object stored in a mysql database in a column of type text saved via php.
If I double click the field in PHPMyAdmin to edit the value of the field inline, and then save the edit by clicking away from the edit box, the serialized data in the field is rendered corrupt somehow.
I get the following PHP error after doing this:
Notice: unserialize(): Error at offset 913 of 1951 bytes in /path/to/file.php on line 46

I am not even changing any of the data, as I am only clicking in to copy the data to the clipboard so it's not as though I'm introducing anything weird, or making an error with the syntax etc. I thought maybe some whitespace is getting added or some wierd character(s).
Is there a solution to this?

A:

According to this question, in order to avoid errors you can try to base64 the output or serialize() before inserting it into the database:
$toDatabse = base64_encode(serialize($data));  // Save to database
$fromDatabase = unserialize(base64_decode($data)); //Getting Save Format


Q:

How to break a maven build when there is a dependency conflict?

I ran mvn dependency:tree for a project and I saw output like the following:
[INFO] my:project:jar:1.0.0-SNAPSHOT
[INFO] +- some.other:library:jar:2.0.0:compile
[INFO] |  \- org.slf4j:slf4j-api:jar:1.6.1:compile
[INFO] +- org.slf4j:slf4j-simple:jar:1.6.0:compile
[INFO] |  \- (org.slf4j:slf4j-api:jar:1.6.0:compile - omitted for conflict with 1.6.1)

This is a bad state to be in because my project depends directly on slf4j 1.6.0 and some library that we depend on transitively depends on slf4j 1.6.1. These two versions happen to be binary compatible so the build passes without any warnings. Is there a way to get Maven to be more strict about its dependency resolution so that I could configure a new build that would fail in this scenario? In this case, the solution would be to just update our dependency to the newer version of slf4j.

A:

The maven-enforcer-plugin has a dependencyConvergence configuration which does what I want. Coincidentally, the example from the documentation uses slf4j.
Configure it like this:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-enforcer-plugin</artifactId>
    <version>1.0</version>
    <executions>
        <execution>
            <id>enforce</id>
            <configuration>
                <rules>
                    <DependencyConvergence />
                </rules>
            </configuration>
            <goals>
                <goal>enforce</goal>
            </goals>
        </execution>
    </executions>
</plugin>

This combination of dependencies will cause a build to fail:
  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-jdk14</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-nop</artifactId>
      <version>1.6.0</version>
    </dependency>
  </dependencies>

With this being logged during compilation:
[ERROR]
Dependency convergence error for org.slf4j:slf4j-api:1.6.1 paths to dependency are:
+-org.myorg:my-project:1.0.0-SNAPSHOT
  +-org.slf4j:slf4j-jdk14:1.6.1
    +-org.slf4j:slf4j-api:1.6.1
and
+-org.myorg:my-project:1.0.0-SNAPSHOT
  +-org.slf4j:slf4j-nop:1.6.0
    +-org.slf4j:slf4j-api:1.6.0

A:

Though dated, I think this SO discussion is related.


Q:

MongoDB Configuration

I am new to MongoDb, I have 1 TB of Data in JSON format, what should be the processor speed, RAM, disc space required, network bandwidth for maximum of 10 concurrent users for production environment.

A:

I can just give you rules of thumb, of course. But it may help you.
Disk space and setup
In order to be able to create backups in a proper way, you should have at least have a RAID10 (the suggested RAID level for MongoDB) with a payload of around 2.5TB. Let me explain why:
You don't want to have 100% utilization of your disk space, so we add a reasonable security margin of 20% to give you enough time to take measures.
( 1024GB payload * 100 / 80 ) = 1280GB with security margin

Then, you want to be able to create backups using LVM snapshots. You need to allocate some space for changes which occur during the lifetime of the snapshot. This is hard to calculate without information, but to be on the safe side, we assume it is about 50% during the time of the backup, so we add another 500GB. Then, you would need some space to compress the backup to. To be on the safe side again, we add another 500GB. Since you don't want a utilization of 100% of the backup space, too, the above calculation for the space needed for backup applies again! effectively doubling the space.
The closest would be a RAID 10 with 6 disk of 1TB each giving you a payload of 3TB. That should give you the best balance between redundancy, performance and required payload. Please use 15k SAS disks at least. SSDs give an performance boost of about an an order of magnitude right out of the box, but that does not seem to be an issue with your requirements.
CPU
Hard to say what computing power you need, but as a rule of thumb you should buy fewer, but more powerful cores.
RAM
That is very hard to say without knowing how many and which indices you have. But again a rule of thumb jumps in: With MongoDB, there is no such thing as too much RAM. With 1TB payload, MongoDB could utilize 1TB+ to keep not only the indices, but the data, too in in RAM for fast reads.
The amount of RAM you need is hard to calculate. I usually would roughly calculate 10% to be on the safe side for optimal performance, since additional RAM never hurts. Especially when using spinning disks instead of SSDs.
That would be 128GB in your case. But it may well be that you get along with just 64 or even 32GB. My suggestion would be to start with 32GB and upgrade if you see a lot of page faults in MMS.
Network bandwidth
Without knowing how much data is send per query, it is impossible to calculate this. If you plan to set up a replica set (which you almost always should), you should not go below 1Gb internal bandwidth on write heavy applications. If you really have a lot of load, you might even want to bond two interfaces.
Disclaimer: These are only rules of thumb, based on the very limited information of the original question. Depending on your application, system administration skills and environment, your actual needs may vary.


Q:

Understand how knockout is interacting with a javascript object with the push.apply

This is probably yet another javascript scope question with a knockout spin.
Going through the examples in a book that I purchased in which the author presents an example of a single page application but chooses not to completely explain the javascript as it is not the focus of the book.
My question is how does the function in the success action in the ajax call understand the definition for the nested object used as an argument.
outerobj.myarray.push.apply(outerobj.myarray, data.map(function (nestedobj) { nestedobj.prop1 }))

The main object
var outerobj = {
  view: ko.observable("View1")
  nestedobj : {
           prop1 : ko.observable(""),
            prop2 : "",
            prop3 : ko.observable("")
        },
         myarray : ko.observableArray([])
}

In a later Ajax/Jquery option there is a call to push.apply with a call like this
var getProperties = function ()
 {
 $.ajax("/path", {
  type: "GET",
  success: function (data) {
  outerobj.myarray.removeAll();
  outerobj.myarray.push.apply(outerobj.myarray, data.map(function(nestedobj) { return nestobj.prop1; }))
  outerobj.view("Result");

}
});
}

A:

Array.prototype.push will push values into the 'top' of the array. It can receive a variable number of arguments, such that:
[1].push(2);  //[1,2]
[1].push(2, 3); //[1,2,3]

.apply executes a function from the given scope, applying a given array of arguments. It spreads out the array as arguments to the function. For example:
var arr =[];
[].push.apply(arr, [1,2]);  // this is equivalent to arr.push(1,2);

Finally, .map returns an array... So basically this is a nice way of pushing an array of items into the array.


Q:

Pattern not escaping characters

I've got this pattern which I use with preg_match and I can't figure where I go wrong.
$pattern = "{(\[fn:)([0-9]*)(\])((?:\\\[|[^\[])*)}";

It has to match each [fn:i]text_multiline untill another one starts so when it meets [ and i want to escapte the [ by \[ from the following example:

[fn:1] This is the text for \[this needs to be escaped] footnote 1.
Note that it could be multiple paragraphs.
[fn:2] This is the text for footnote 2.

This is the matches that I get at the moment:
array(5) {
  [0]=>
  string(6) "[fn:1]"
  [1]=>
  string(4) "[fn:"
  [2]=>
  string(1) "1"
  [3]=>
  string(1) "]"
  [4]=>
  string(0) ""
}

A:

The technique to use when you want to exclude and escaped [ is called "negative look behind".
For example,
(?<!\\)\[

This regex will match [ but ignore if its proceeded by a \
Let me know if you need any more help
Edit #1
This is the negative lookbehind applied to your specific scenario
\[fn:\d+](?:\\\[|[^[])*

and in php this becomes
if (preg_match('/\[fn:\d+\](?:\\\\\[|[^[])*/', $subject)) {
    # Successful match
} else {
    # Match attempt failed
}

Some notes

I use alternation and let it first match the escaped [ so it doesn't get excluded by what matches after the alternation (common trick that relies on the order in alternation)
I started from scratch so if you need to capture some groups then add parenthesis where needed
The construct (?:) is used to group but not to capture. This is (maybe) more efficient and as said I left out the capturing

The regex is tested against your example. Let me know if you can get it working now
Good luck, Buckley


Q:

Java How to thread a GUI

So I have a button that opens a while loop, then my whole GUI freezes until the while loop is over, with that being said how would I thread my GUI to update every second or so?
JButton Test= new JButton();
Test.setText("Test");
Test.setSize(230, 40);
Test.setVisible(true);
Test.setLocation(15, 290);

Test.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e){
int x = 0;
while(x<500){
    x++
});

A:

Use ExecutorService class
Test.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ExecutorService es = Executors.newCachedThreadPool();
            es.submit(new Runnable() {
                @Override
                public void run() {
                    int x = 0;
                    while (x < 500) {
                        x++;
                    }
                }
            });
        }
 });


Q:

Cannot convert int {Class}::* to int*

When I try to call a function, passing in a reference to my variable which has the type int, to the function which takes a type of int, I get an error that seems to point out that the int is the type of the class it was declared in, why is this?
Header:
class MyClass {
    public:
        int MAJOR = 3;
        int MINOR = 3;
        int REV = 0;
}

Code:
glfwGetVersion(&MyClass::OPENGL_VERSION_MAJOR, &MyClass::OPENGL_VERSION_MINOR, &MyClass::OPENGL_VERSION_REV);

Error:
error: cannot convert 'int MyClass::*' to 'int*' for argument '1' to 'void glfwGetVersion(int*, int*, int*)'

A:

Change to:
class MyClass {
    public:
        static const int MAJOR = 3;
        static const int MINOR = 3;
        static const int REV = 0;
};

If these versions are constant.

Otherwise as:
class MyClass {
    public:
        static int MAJOR;
        static int MINOR;
        static int REV;
};

Then somewhere in a .cpp file
int MyClass::MAJOR = 3;
int MyClass::MINOR = 3;
int MyClass::REV = 0;

Check live example here


Q:

My passport not stamped when I left the U.S. How can I reenter?

I'm an F-1 student in the U.S.  On Dec 28th last year, I left the U.S. temporarily for Japan, where I am a national.
Something was strange with the airport through which I flew out of the U.S.  For one thing, there was no officials there to stamp my passport.  Apparently this made me look suspicious to a custom official at the Japanese airport, who checked my baggage, something that does not happen always.
I am returning back to the U.S. very soon and I am expecting a similar hiccup at the U.S. airport (by the way, I am returning to the same airport).  How can I minimize the possible damage?  Is there something I should prepare?  Is there something that I should avoid?
(For example, I carry my pillow around when I travel, and I do not want it to be ripped by officials to check the contents.  I also carry similar childish items usually and I do not want to be embarrassed.)

A:

Unlike Japan, the US does not stamp your passport (and generally does not require any special procedure) upon exit. There is absolutely nothing abnormal here.
Do you know for certain that the Japanese customs inspector decided to inspect you because you had no exit stamp from the US? I find that difficult to believe, so unless you have very strong evidence, you should regard the two events as unrelated. Likewise, you are no more likely than any other person to be inspected when you are back to the US.


Q:

8 ball Pool: Left only with black ball

What happens if I have only the 8 (black) ball left to pot and my opponent who has a colored ball scratches the cue ball? Do I get a ball in hand or do I have to try potting the black ball from behind 'the line'?

A:

It depends what rules you play by.  By Official pool rules, you would have ball in hand as they committed a foul.

3.9 Standard Fouls
If the shooter commits a foul, play passes to his opponent. The cue ball is in  hand, and the incoming player may place it anywhere on the playing surface.

On the Foul:

6. Fouls
The following actions are fouls at pool when included in the specific
  rules of the game being played. If several fouls occur on one shot,
  only the most serious one is enforced. If a foul is not called before
  the next shot begins, the foul is assumed not to have happened.
6.1
Cue Ball Scratch or off the Table  If the cue ball is pocketed or driven off the table, the shot is a foul.

However, it depends what rules you play by, determined prior to the match start.

When the cue ball is in hand, the shooter may place the cue ball
  anywhere on the playing surfaceand may
  continue to move the cue ball until he executes a shot. Players may use any part of the cue stick to
  move the cue ball, including the tip, but not with a forward stroke
  motion. In some games and for most break shots, placement of the cue
  ball may be restricted to the area behind the head string depending on
  the rules of the game, and then 6.10 Bad Cue Ball Placement and 6.11
  Bad Play from Behind the Head String may apply.

For reference, behind the head string is also known as the kitchen.

I would recommend clarifying with your opponent which rules you want to play by prior to starting the game.  [I usually play any foul committed is ball in hand]
Rules


Q:

Codeigniter url changes from 'localhost' to 'http://127.0.0.1/'

https://stackoverflow.com/a/29562910/4713946
This is my problem, and I am not sure about the answer. I am unsure where I put this code. I cannot comment on the post itself as I do not have enough reputation so I have to start a new thread. /:
Can someone maybe help me out.
I do a redirect() and when I do this, the 'Localhost' changes to '127.0.0.1'

A:

So turns out all I had to do was change 'base_url' in 'config.php' file:
$config['base_url'] = '';

to
$config['base_url'] = '/';

A:

You should set your base url if your using codeigniter 3 versions
$config['base_url'] = 'http://localhost/yourproject/';

If base url is blank it codeigniter 3 versions will show ip_address in url instead of localhost.


Q:

Boost variant of references and equality comparison

The following program aborts:
#include <boost/variant.hpp>

using variant_type = boost::variant< int&, std::string& >;

int main () {
    int a, b;

    variant_type v (a), u (b);
    v == u;

    return 0;
}

with:
$ g++ -std=c++14 t.cpp && ./a.out
a.out: /opt/boost/default/include/boost/variant/detail/forced_return.hpp:39: T boost::detail::variant::forced_return() [with T = const int&]: Assertion `false' failed.
Aborted (core dumped)

AFAICT you can't compare for equality between variants of non-const references because of a wrong overload of operator function-call being selected in class known_get. known_get is instantiated for const T in the comparer visitor instead of what seems should have been T (variant.hpp:905 in v1.59.0).
Am I missing something?

A:

I think this is a Boost bug.
The type requirements here are:

CopyConstructible or MoveConstructible.
Destructor upholds the no-throw exception-safety guarantee.
Complete at the point of variant template instantiation. (See boost::recursive_wrapper<T> for a type wrapper that accepts incomplete types to enable recursive variant types.)

as well as:

EqualityComparable: variant is itself EqualityComparable if and only if every one of its bounded types meets the requirements of the concept.

A reference type is copy constructible, is no-throw destructible, complete, and equality comparable. So we're good on all points there. The issue is that the the visitor used in the implementation is:
template <typename T>
bool operator()(const T& rhs_content) const
{
    // Since the precondition ensures lhs and rhs types are same, get T...
    known_get<const T> getter;
    const T& lhs_content = lhs_.apply_visitor(getter);

    // ...and compare lhs and rhs contents:
    return Comp()(lhs_content, rhs_content);
}

That is, we're using const T as the known getter. This is fine for non-reference types, but incorrect for reference types, since known_get asserts if it gets the wrong type:
T& operator()(T& operand) const BOOST_NOEXCEPT
{
    return operand;
}

template <typename U>
T& operator()(U& ) const
{
    // logical error to be here: see precondition above
    BOOST_ASSERT(false);
    return ::boost::detail::variant::forced_return<T&>();
}

With int&, those overloads become:
const int& operator()(const int& ) const;
const int& operator()(int& ) const; [ U = int ]

The second overload is preferred since the type it refers to would be less const-qualified than the non-template overload. That's why you get the assert, and this behavior is clearly incorrect. We should be able to compare references!
The simpler solution would be to drop the consts from comparer and simply use:
template <typename T>
bool operator()(T& rhs_content) const
{
    known_get<T> getter;
    T& lhs_content = lhs_.apply_visitor(getter);

    return Comp()(lhs_content, rhs_content);
}

This would work for reference types as well as const types.


Q:

Why do some conferences have a variable amount of reviewers for each submitted paper?

Why do some conferences have a variable number of reviewers for each submitted paper?
For example, I read on https://redd.it/9nomv1 that the AAAI 2019 conference has between 3 and 5 reviewers for each paper submission. Why isn't the number of reviewers the same for all submitted papers? Is that to make up for non-experienced or outside-the-area reviewers, or for reviewers who do not turn in reviews?

A:

Editors usually invite more than the minimum amount of reviewers when they assign a paper for peer review, because not all invited reviewers will agree to do the review. A suggestion that I have seen in a guideline for editors (and which indeed mostly works well in my experience for this specific publication venue) is to invite 5 or 6 reviewers initially when aiming to get 2 reviews.
Occasionally an editor will be lucky and (almost) all invited reviewers will submit the review, leading to a higher than required number of reviews for this manuscript.
In other cases there will be less than the minimum number of reviews even though more reviewers have been invited, and the editor will have to invite even more reviewers.


Q:

How to Draw pixel data taken from the backbuffer back to itself?

I'm working on a mobile application for Symbian 5th edition using OpenGLES.
This application is a pretty standard 2D app, and I make no use of the DepthBuffer.
I need to grab a snapshot of the display and then draw the very same snapshot back to the backbuffer.
I'm using glReadPixels((GLint)0, (GLint)0,
            (GLint)nWidth-1, (GLint)nHeight-1,
                GL_RGB, GL_UNSIGNED_BYTE, m_pPixelData)

in order to get the pixel data I need, but I'm rather new to OpenGLES and I don't know how to draw the data back to the backbuffer. (in OpenGL its easy using DrawPixels..)
I've read that I should generate a texture from the data, so I did.
But now I'm not sure how to draw this texture.
Do I need to draw it as a texture of a Rectangular element ? if so than how am I suppose to define this rect ? ( the coordinates just doesn't make sense to me..)
The display size is 480x640 and here is the code I want to use in order to draw the rect:
    glEnable(GL_TEXTURE_2D);
    //displayTex is my texture built out of the pixel data
    glBindTexture(GL_TEXTURE_2D, m_pESSharedData->displayTex);

    //Bottom
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f);
    glVertex3f(-2.5f, -2.5f, 2.5f);
    glTexCoord2f(1.0f, 0.0f);
    glVertex3f(2.5f, -2.5f, 2.5f);
    glTexCoord2f(1.0f, 1.0f);
    glVertex3f(2.5f, -2.5f, -2.5f);
    glTexCoord2f(0.0f, 1.0f);
    glVertex3f(-2.5f, -2.5f, -2.5f);

    glEnd();

Note that above code is something I've picked up along the way, and I think this is the outline of what I'm suppose to do. feel free to take me off this track. :)
I thank you for your time.

A:

You first need to make sure that the version of OpenGL-ES on Series60 5th edition can handle textures whose height and width aren't powers of 2.
I would advise forum nokia for that kind of query.
Shameless plug:
Quick Recipes On Symbian OS contains a whole chapter explaining the basics of OpenGL-ES on Symbian OS. The 3D code samples are here.


Q:

Would it be physically possible for rotating tank armor to move in front of an incoming projectile fast enough to intercept?

The core challenge of building a tank is deciding where to focus its armor and how much speed / cost you're willing to trade for protection, so this got me thinking, with modern detection technology, like laser, could we potentially place a single very thick plate of armor on an axle and once a projectile is detected, rotate it (around the outside of the tank) in front of the projectile in time to stop it (assuming it isn't a close quarter engagement).
If so, tanks could stay much lighter and much cheaper and still have all the benefits of extremely tough armor, and more importantly, have that same protection on all sides of the tank rather than just the front.
Question is: Is that physically possible? Is it physically possible with known modern technology to detect an incoming projectile, then rotate a wheel with enough torque and speed to intercept the projectile's path before it passes?
Factors I know:

Fastest projectile should be traveling at 2000 m/s.
Radius to be traveled around the sides of an average tank is 15 meters including the gun barrel.
A 0.5 x 0.5 meter steel plate with a thickness of 120 mm will weigh 246 kg.
Processing / detection time isn't relevant. The time between scanning the incoming projectile (twice, to calculate angle and speed) and sending the correct information to the armor acceleration mechanism is easily less than 1ms, during which the projectile has only traveled 2 meters since detection.

What I don't know:

Assuming we use the best viable method known, how fast can that 246kg plate be accelerated to the correct location?
Would it be better if the plate was kept in constant motion and simply adjusted once the projectile is detected so it doesn't need to be accelerated from a zero energy state.?

Other factors to consider:

The armor doesn't have to be stopped right away. It can be accelerated to exactly the correct speed to be in front of the projectile at the calculated time and place of collision, then freely continue swinging around the tank and slow down gradually.
There might need to be 2 equally sized plates on opposite ends of the tank to counter each other so the tank can remain stable - so potentially twice the weight.

A:

Assuming we use the best viable method known, how fast can that 246kg
  plate be accelerated?

It's not just a plate to accelerate, it's a moment of inertia to fight and it depends on the position of the plate regarding the center of rotation, its geometry, thus depends on the design of the tank, then it depends on the acceleration curve of the motor and the initial position of the plate, etc.…
I think there is no engineer answer to your question, too many guesses and unsupported assumptions need to be made on too many variables without access to (classified) accurate data.
Like :

"How far a laser can detect an incoming projectile accurately" : "accurately" needs to be defined, what is your maximum acceptable error of position ? Then, is it by clear weather or in the dust/storm/etc. ?
"What's the fastest scan rate that can be achieved by the laser detection system? We need to read 2 locations to determine the projectile's attack vector." : you certainly need to use satellites here, since the tank might be blinded by mountains etc. Thus, you need to take into account the latency of the transmission, the risk of data loss, etc. And you need at least 3 readings to achieve proper accuracy in a short amount of time. After that, you need to achieve a third-order accuracy reading on the missile acceleration in order to get a first-order accuracy on the position of the impact (since it's  a double integral). As you see, it's not just sensing and measuring, it's differential equations to solve in real-time, thus the numeric overhead is significant.
"The armor doesn't have to be stopped right away. It can be accelerated to exactly the correct speed to be in front of the projectile at the calculated time and place of collision, then freely continue swinging around the tank and slow down gradually." : actually, using a moving armor is quite clever and might make good use of the conservation of the angular momentum. However, the very aspect of the automation control is a challenge here. Assuming you have the perfect motor (actuator) to do so, ensuring a proper control to achieve precision on position, speed and acceleration based on an acceleration and position input needs at least a 3rd-order accurate controler with a very fast numeric solver. Since your oversized motor won't probably have a linear response, you will have to correct that as well. So it's a lot of math to process with a lot of measures to gather and a lot of errors to handle in a short amount of time, and by the time you get the parameters to input in your motor controler, you might just be dead already.

Yes, physically, this is just basic newtonian mechanics and tennis playing with missiles, and it is possible in theory.
However, there is no definitive answer to the feasibility aspect until someone does it, and this is more sci-fi than engineering.


Q:

Accessing Parent Properties in Nested Components

In anticipation of Routable Components coming soon, I'm attempting to use Components wherever possible in my Ember 2.0 application. I'm running into a confusing issue where I cannot access the parent component's properties from the template when provided in block form. It may be very well that this isn't possible, but wanted to be sure. Here's an example:
Template:
// templates/approvals.hbs
{{#x-secure/schedule/approvals}}

  {{#x-secure/layout/full sectionTitle=sectionTitle sectionDescription=sectionDescription}}
    ...
  {{/x-secure/layout/full}}

{{/x-secure/schedule/approvals}}

Component Template:
// templates/components/schedule/approvals.hbs
{{yield}}

Component:
// components/schedule/approvals.js
import Ember from 'ember';

export default Ember.Component.extend({

  /////////////////////////////////////
  // PROPERTIES
  /////////////////////////////////////

  sectionTitle: 'Scheduling: Approvals',
  sectionDescription: 'Lots of magical , fanstastic stuff.'

});

The issue I'm having is that I'm unable to access sectionTitle and sectionDescription from the parent component (approvals) and pass it into the layout/full component. However, if I remove code from the block of the component and move it to the templates/components/schedule/approvals.hbs template, it works as expected. Is it just not possible to access a parent component's properties from the block form of a component?
Thanks!

A:

It is not possible indeed. The component's properties are available in the component's template, but not in the template that instantiates the component.
If you need the component to make things available, it should yield them explicitly:
// templates/components/schedule/approvals.hbs
{{yield sectionTitle sectionDescription}}

And using the component:
// templates/approvals.hbs
{{#x-secure/schedule/approvals as |title description|}}

  {{#x-secure/layout/full sectionTitle=title sectionDescription=description}}
    ...
  {{/x-secure/layout/full}}

{{/x-secure/schedule/approvals}}

Notice the as |x y ...| notation to assign names to yielded values.
Anything may be yielded this way, including this (be careful with that though, that breaks encapsulation) and actions.


Q:

$wpdb is get_results escaped

I'm guessing the answer is no here, but wanted to be sure.  I would expect that when I get a database object or array using get_results that I still need to add htmlspecialchars() or esc_html() when placing the output in HTML.  I did look at the function, but it's not really clear without finding functions that the get_results function uses (and not sure how deep I would need to dig).  This question brings up one very small other question.  Any reason to use the WordPress function esc_html() over the generic htmlspecialchars()?

A:

The answer is: of course they are not - otherwise you couldn’t use them to save them in DB.
But... the answer to your question isn’t so easy.
Sanitizing is a process of preparing data for storing in DB. So for example if you insert some illegal characters in post_name, then it will be removed, so the post_name is sanitized, before saving. If you use color picker in Customizer, then you should sanitize it (checking if it really is a color and not some random string) before saving. And so on.
But sanitized data can still be dangerous. You can use “>” character in title, so title containing it will be sanitized. But of course you can’t print it in HTML of your code.
That’s where escaping joins the game. Escaping is a process of making data from DB secure for HTML code (based on context). Remember that the same title should be escaped in a different way when it’s printed inside  tag (then you should use esc_html), than when it’s used as html attribute (you should use esc_attr) and so on.
So yes - you should always sanitize your data before storing it in DB and always use correct way of escaping based on given context.


Q:

specified cast is not valid. in c# window web application

I wish to create an invoice window form application, I get the error when I want to store the data that I have select into the database.The invoice ID should be auto generated, but now I manual insert invoiceID=6; to test whether the data can load into the database. However I get the error when I execute the reader. My overview of data table can refer at here
Properties of invoiceID Column

Data Type: int;
Identity Increment:0;
Identity Seed:0;
Is Identity:False;
Length:4;
Nullable: False;
Precision:10;
Scale:0

Error:

Specified cast is not valid

Edited Code:
private void StoreData()
    {
        int invoiceID;
        int Item_Id;
        int quantity;

        using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xchoo\Documents\Visual Studio 2012\Projects\WindowsFormsApplication_test2\WindowsFormsApplication_test2\Data.mdf;Integrated Security=True;Connect Timeout=30"))
        {
            con.Open();

            using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = @"insert into Invoice(invoiceID, subtotal,tax,total) values (7, @subtotal,@tax,@total); select SCOPE_IDENTITY() as invoiceID;";
                cmd.Parameters.AddWithValue("@subtotal", subtotal);
                cmd.Parameters.AddWithValue("@tax", tax);
                cmd.Parameters.AddWithValue("@total", total);
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                     {
                         //invoiceID = cmd.GetInt32("InvoiceID");
                        //invoiceID = (int)reader["invoiceID"];  //error
                         cmd.Parameters.AddWithValue("@invoiceID", Convert.ToInt32("invoiceID"));
                    }

                }
            }
            foreach (var item in OrderItems.Rows)
            {
                using (var cmd = con.CreateCommand())
                {

                    cmd.CommandText = @"insert into InvoiceItem(invoiceID,Item_Id,quantity) values (@invoiceID,@Item_Id,@quantity);";
                     cmd.Parameters.AddWithValue("@InvoiceID", invoiceID);
                     cmd.Parameters.AddWithValue("@Item_Id", Item_Id);
                     cmd.Parameters.AddWithValue("@quantity", quantity);
                   // cmd.Parameters.AddWithValue("@invoiceID", Convert.ToInt32("invoiceID"));
                    //cmd.Parameters.AddWithValue("@Item_Id", Convert.ToInt32("Item_Id"));
                    //cmd.Parameters.AddWithValue("@quantity", Convert.ToInt32("quantity"));
                    cmd.ExecuteNonQuery();

                }
            }

            con.Close();
        }
    }

A:

1 . line cmd.CommandText = @"insert into Invoice(invoiceID, subtotal,tax,total) values (6, @subtotal,@tax,@total); select SCOPE_IDENTITY() as invoiceID;";
invoiceID is not not Identity column in Invoice
 select SCOPE_IDENTITY() as invoiceID

will return null after insert
also instead of
using (var reader = cmd.ExecuteReader())
{
     if (reader.Read())
     {
         cmd.Parameters.AddWithValue("@invoiceID", Convert.ToInt32("invoiceID"));
     }
}

i would try the following code to get result
object idObj = cmd.ExecuteScalar()

2 . line cmd.Parameters.AddWithValue("@invoiceID", Convert.ToInt32("invoiceID"));
Convert.ToInt32("invoiceID") will never work becuase "invoiceID" is not a number
remove quotes: Convert.ToInt32(invoiceID)
the same problem with Convert.ToInt32("Item_Id") and Convert.ToInt32("quantity")


Q:

Как администратору залогиниться от лица пользователя?

Есть сайт построенный на yii2, шаблон advanced. Как из backend реализовать авторизацию во frontend от лица рядового пользователя? Backend и frontend на разных поддоменах. Реализовывал такое как-то давно, не на yii, путем подмены кук, а тут даже не знаю с чего начать, гугление результатов не дало, какие будут годные советы?

A:

Такое действие назвается "имперсонализация". Для первого Yii есть статья про это:
http://www.yiiframework.com/wiki/154/impersonate-users-within-yii-framework/
Не могу сказать насколько переносимо во вторую версию. Надеюсь сам принцип понятен.


Q:

CryptoNight can mine monero?

Thanks in advance for all answers
at first I am new in this business.
I want to buy Baikal N240 which has Algorithm CryptoNight and CryptoNight-lite. I want Mine Monero.
My question is, can we mined Monero Algorithm CryptoNight? or must need CryptoNight variant 1 (CNv1)?
or can I go with any good product for mine? if any good profitable product than please give me suggestion
Thanks

I really salute you from bottom of my heart.
that means I should't buy CryptoNight algorithm hardware?
please could you suggest me which hardware is profitable for mining.
thanks and regards

A:

The current algorithm is CryptoNightV1 [edit: now Cryptonight v4 as of may 2019], and will change in the future.
If you want to mine with ASIC or FPGA, you're looking at the wrong cryptocurrency.
Monero will change its algo at every network upgrade to remain ASIC and FPGA-resistant, and help the decentralization through the smaller player (CPU & GPU) wider participation.
With a CryptoNight ASIC/FPGA you could mine some XMC along with other ASICs.
Edit: If you want to mine Monero, then CPU (AMD ryzen series) and GPU (AMD RX550 and newer) are good hardware.
If you have enough Money, choose AMD Vega 56/64 GPUs.


Q:

Wiring +5V to Micro USB

I'm wiring 5V from a power supply directly to a micro USB cable. I'm only using the +5V and GND connectors, and leaving Data+ and Data-. While I only plan to use the cable for power, do I need to do anything with that D+ and D- cables, or can I leave them disconnected from both ends?
UPDATE I should clarify that the USB cable is connected to a Raspberry Pi, not a basic circuit.

A:

You can leave them open.
Think about it this way - if nothing is plugged into the USB port they are essentially not connected to anything anyway.


Q:

Why did Cypher say they were going to kill Neo?

In the beginning of the first movie, in the first conversation, between Cypher and Trinity, he says:

Cypher: We're going to kill him, understand?
Trinity: Morpheus believes he is the One.
Cypher: Do you?

Why did Cypher said that? Was it a habit to kill potential red pills? Was Neo considered to be a threat, so he needed to be killed if he was not the One?

A:

Instead of interpreting Cypher's statement literally it should be interpreted as "what we are doing has a high risk of resulting in Neo's death".
This is true in general since Neo is older than most people who are unplugged from the Matrix, and Morpheus explains that

We have a rule. We never free a mind once it's reached a certain age. It's dangerous, the mind has trouble letting go.
transcript for The Matrix

The danger posed by an attempt to "free" a mind includes possible death. This is a fact confirmed by the comic Saviors, in which the parents of an adult red pill operative die because they are unplugged from the Matrix and were already too old (H/T @Valorum).
Of course, Trinity knows of this danger and doesn't need to be reminded by Cypher. However, Cypher has two ulterior reasons to say this.
1. Cypher was betraying the crew and covering up his involvement in Neo's likely death as a result of the betrayal.
Here's the dialogue you quoted along with the rest of the conversation:

Cypher: We're going to kill him, understand?
Trinity: Morpheus believes he is the One.
Cypher: Do you?
Trinity: It doesn't matter what I believe.
Cypher: You don't, do you?
Trinity: Did you hear that?
Cypher: Hear what?
Trinity: Are you sure this line is clean?
Cypher: Yeah, of course I'm sure.
Trinity: I better go.
transcript for The Matrix

Cypher was in the process of letting the Agents trace the line between him and Trinity. Later, after Trinity has escaped, the Agents have the following conversation:

Agent Brown: She got out.
Agent Smith: Doesn't matter.
Agent Brown: The informant is real.
Agent Smith: Yes.
Agent Jones: We have the name of their next target.
Agent Brown: The name is Neo.
Agent Smith: We'll need a search running.
Agent Jones: It's already begun.
transcript for The Matrix

The informant is, of course, Cypher. And he has proved to the Agents that he is a true informant.
Cypher expected Neo to die since Cypher did not believe Neo was The One, and Cypher was betraying the crew. Cypher tells Trinity that they're going to kill Neo to raise Trinity's expectations that Neo will not be saved and will die during the process of trying to release him from the Matrix. This will help prevent her from suspecting his betrayal as the cause of Neo's death.
2. Cypher is infatuated with Trinity and attempting to undermine Trinity's belief that Neo is The One.
Cypher repeatedly attempts to convince Trinity that Neo is not The One. If Cypher can convince Trinity that Neo is not The One then, in his mind, she may fall in love with him instead. But as Cypher points out:

I mean, how can he be the One if he's dead?
transcript for The Matrix

Again, if Trinity expects that Neo will die then she will not think he is The One.
Hidden Meanings
There are also two hidden meanings in Cypher's words. Neo symbolically dies twice in The Matrix. The first is when he is unplugged from the Matrix and "reborn" in the real world. The second is when Neo (who is not The One yet) dies at Agent Smith's hands but is resurrected as The One. Cypher obviously does not say that Neo will be killed for these reasons, but his line is for the audience's benefit -- by releasing Neo from the Matrix, they did kill him symbolically (and twice).


Q:

Java 8 - collect List attributes with Set type as a set of values

I have a List<Entity> entites; where Entity has fields called testField with Set type:
class Entity {
    Set<String> testField;
}

I want to get all String that are contained in all testField Sets within entites list; So if I wouldn't use java 8 my code woud look lile:
Set<String> allTestFieldString = newHashSet();
for(Entity entity : entities) {
    allTestFieldString.addAll(entity.testField);
}

The following code doesn't compile for me:
entites.stream().map(entity -> entity.testField()).collect(Collectors.toSet());

Would appreciate any help, thanks!

A:

You need flatMap to produce a Stream of all the elements of all the testField Sets :
Set<String> allTestFieldString = entites.stream().flatMap(entity -> entity.testField.stream()).collect(Collectors.toSet())


Q:

get many value from json

I need to get latitude and longitude to my android, it got many values like this :

I tried this to get values from JSON :
ArrayList<String> longitude;
ArrayList<String> latitude;

public void parseJson(String result) {
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject jo = jArray.getJSONObject(i);
                latitude.add(jo.getString("Latitude").toString());
                longitude.add(jo.getString("Longitude").toString());
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
    }

But When I check the size of array, it's empty.
Anyone can help or suggest my wrong ? Thanks
@after modified,I still got 0 size of array. So,I tried to search where it's stop by Toast then I found :
public void parseJson(String result) throws JSONException {

        longitude = new ArrayList<String>();
        latitude = new ArrayList<String>();

        JSONArray jArray = (JSONArray)JSONValue.parse(result);

        for (Object obj: jArray) {

            JSONObject jo = (JSONObject)obj;
            //here is when I toast it's got nothing
            latitude.add(jo.get("Latitude").toString());
            longitude.add(jo.get("Longitude").toString());
        }

    }

@aroth I got an answer!! I back to use my way like this :
public void parseJson(String result) throws JSONException {

        longitude = new ArrayList<String>();
        latitude = new ArrayList<String>();
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject jo = jArray.getJSONObject(i);
            latitude.add(jo.getString("Latitude").toString());
            longitude.add(jo.getString("Longitude").toString());
        }

I think I forgot declare these:
         longitude = new ArrayList<String>();
         latitude = new ArrayList<String>();

I still no idea why your code is not work. However, thank a lot for your help :))

A:

The json.org library is needlessly obtuse with its get<Type> methods that all pointlessly throw JSONException, I would recommend switching to simple-json.  Then you could do:
ArrayList<String> longitude;
ArrayList<String> latitude;

public void parseJson(String result) {
    longitude = new ArrayList<String>();
    latitude = new ArrayList<String>();
    JSONArray jArray = (JSONArray)JSONValue.parse(result);
    for (Object obj : jArray) {
        JSONObject jo = (JSONObject)obj;
        latitude.add(jo.get("Latitude").toString());
        longitude.add(jo.get("Longitude").toString());
    }

}

//a simple test case
public static void main(String[] args) {
    String json = "[{\"Latitude\": \"1.23\", \"Longitude\": \"1.23\"}, \n{\"Latitude\": \"1.23\", \"Longitude\": \"1.23\"}, \n{\"Latitude\": \"1.23\", \"Longitude\": \"1.23\"}]";
    MyParser parser = new MyParser();
    parser.parseJson(json);

    //should print:  3, 3
    System.out.println(parser.latitude.size() + ", " + parser.longitude.size());
}

Should work, assuming your input JSON matches your example snippet.


Q:

Object Oriented Design for a Chess game

I am trying to get a feel of how to design and think in an Object Oriented manner and want to get some feedback from the community on this topic. The following is an example of a chess game that I wish to design in an OO manner. This is a very broad design and my focus at this stage is just to identify who is responsible for what messages and how the objects interact each other to simulate the game. Please point out if there are elements of bad design (high coupling, bad cohesion etc.) and how to improve on them.
The Chess game has the following classes

Board
Player
Piece
Square
ChessGame

The Board is made up of squares and so Board can be made responsible for creating and managing Square objects. Each piece also is on a square so each piece also has a reference to the square it is on. (Does this make sense?). Each piece then is responsible to move itself from one square to another.
Player class holds references to all pieces he owns and is also responsible for their creation (Should player create Pieces?) . Player has a method takeTurn which in turn calls a method movePiece which belongs to the piece Class which changes the location of the piece from its current location to another location. Now I am confused on what exactly the Board class must be responsible for. I assumed it was needed to determine the current state of the game and know when the game is over. But when a piece changes it's location how should the board get updated? should it maintain a seperate array of squares on which pieces exist and that gets updates as pieces move?
Also, ChessGame intially creates the Board and player objects who in turn create squares and pieces respectively and start the simulation. Briefly, this might be what the code in ChessGame may look like
Player p1 =new Player();
Player p2 = new Player();

Board b = new Board();

while(b.isGameOver())
{
  p1.takeTurn(); // calls movePiece on the Piece object
  p2.takeTurn();

}

I am unclear on how the state of the board will get updated. Should piece have a reference to board? Where should be the responsibility lie? Who holds what references? Please help me with your inputs and point out problems in this design. I am deliberately not focusing on any algorithms or further details of game play as I am only interested in the design aspect. I hope this community can provide valuable insights.

A:

I actually just wrote a full C# implementation of a chess board, pieces, rules, etc.  Here's roughly how I modeled it (actual implementation removed since I don't want to take all the fun out of your coding):
public enum PieceType {
    None, Pawn, Knight, Bishop, Rook, Queen, King
}

public enum PieceColor {
    White, Black
}

public struct Piece {
    public PieceType Type { get; set; }
    public PieceColor Color { get; set; }
}

public struct Square {
    public int X { get; set; }
    public int Y { get; set; }

    public static implicit operator Square(string str) {
        // Parses strings like "a1" so you can write "a1" in code instead
        // of new Square(0, 0)
    }
}

public class Board {
    private Piece[,] board;

    public Piece this[Square square] { get; set; }

    public Board Clone() { ... }
}

public class Move {
    public Square From { get; }
    public Square To { get; }
    public Piece PieceMoved { get; }
    public Piece PieceCaptured { get; }
    public PieceType Promotion { get; }
    public string AlgebraicNotation { get; }
}

public class Game {
    public Board Board { get; }
    public IList<Move> Movelist { get; }
    public PieceType Turn { get; set; }
    public Square? DoublePawnPush { get; set; } // Used for tracking valid en passant captures
    public int Halfmoves { get; set; }

    public bool CanWhiteCastleA { get; set; }
    public bool CanWhiteCastleH { get; set; }
    public bool CanBlackCastleA { get; set; }
    public bool CanBlackCastleH { get; set; }
}

public interface IGameRules {
    // ....
}

The basic idea is that Game/Board/etc simply store the state of the game.  You can manipulate them to e.g. set up a position, if that's what you want.   I have a class that implements my IGameRules interface that is responsible for:

Determining what moves are valid, including castling and en passant.
Determining if a specific move is valid.
Determining when players are in check/checkmate/stalemate.
Executing moves.

Separating the rules from the game/board classes also means you can implement variants relatively easily.  All methods of the rules interface take a Game object which they can inspect to determine which moves are valid.
Note that I do not store player information on Game.  I have a separate class Table that is responsible for storing game metadata such as who was playing, when the game took place, etc.
EDIT: Note that the purpose of this answer isn't really to give you template code you can fill out -- my code actually has a bit more information stored on each item, more methods, etc.  The purpose is to guide you towards the goal you're trying to achieve.

A:

Here is my idea, for a fairly basic chess game :
class GameBoard {
 IPiece config[8][8];

 init {
  createAndPlacePieces("Black");
  createAndPlacePieces("White");
  setTurn("Black");

 }

 createAndPlacePieces(color) {
   //generate pieces using a factory method
   //for e.g. config[1][0] = PieceFactory("Pawn",color);
 }

 setTurn(color) {
   turn = color;
 }

 move(fromPt,toPt) {
  if(getPcAt(fromPt).color == turn) {
    toPtHasOppositeColorPiece = getPcAt(toPt) != null && getPcAt(toPt).color != turn;
    possiblePath = getPcAt(fromPt).generatePossiblePath(fromPt,toPt,toPtHasOppositeColorPiece);
   if(possiblePath != NULL) {
      traversePath();
      changeTurn();
   }
  }
 }

}

Interface IPiece {
  function generatePossiblePath(fromPt,toPt,toPtHasEnemy);
}

class PawnPiece implements IPiece{
  function generatePossiblePath(fromPt,toPt,toPtHasEnemy) {
    return an array of points if such a path is possible
    else return null;
  }
}

class ElephantPiece implements IPiece {....}


Q:

LruCache not working

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                return bitmap.getByteCount() / 1024;
            }
        };
    URL url = new URL("http://s2.goodfon.ru/image/260463-1920x1200.jpg");
    Bitmap bitmap = BitmapFactory.decodeStream((InputStream) url.getContent(), null, options);
    if(bitmap != null)
        Log.i("Success", "BITMAP IS NOT NULL");

    String key = "myKey";
    Log.i("Get is null", "putting myKey");
    mMemoryCache.put(key, bitmap);

    Bitmap newBitmap = mMemoryCache.get(key);
    if(newBitmap == null)
        Log.i("newBitmap", "is null");

Hello, here is a code. I get bitmap from URL successfully (Log says Bitmap is not null and I can display it easy). Then I am trying to put it into LruCache and get it  back, but it return null. (Log says newBitmap is null). Where is my mistake? Please, tell me.
Android 4.1.2 Cache size 8192 Kb.

A:

If it is 1.19 MB on disk but ~ 9 MB in memory, that means that as a compressed JPEG file, it's 1.19 MB and once you extract that into a Bitmap (uncompressed) that can be displayed, it will take up 9 MB in memory.  If it's a 1920 x 1200 pixel image as suggested by the url in your code snippet, the image will take up 1920 x 1200 x 4 bytes of memory (4 bytes for each pixel to represent ARGB values from 0 to 256 times 2.3 million total pixels = 9,216,000 bytes).  If you're using 1/8 of your available memory for this cache, it's possible/likely that 9MB exceeds that total memory space so the Bitmap never makes it into the cache or is evicted immediately.
You're probably going to want to downsample the image at decoding time if it's that large (using BitmapFactory.Options.inSampleSize...lot's of documentation on the web for using that if you're not already familiar).
Also, you're using Runtime.maxMemory to compute your cache size.  This means you're requesting the maximum amount of memory that the whole VM is allowed to use.
http://developer.android.com/reference/java/lang/Runtime.html#maxMemory%28%29
The more common approach is the use the value given back to you by the ActivityManager.getMemoryClass() method.
Here's an example code snippet and the method definition in the docs for reference.
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    int memClassBytes = am.getMemoryClass() * 1024 * 1024;
    int cacheSize = memClassBytes / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize)

http://developer.android.com/reference/android/app/ActivityManager.html#getMemoryClass%28%29


Q:

Docker image build hangs at "pacman -S ..."

I am trying to build a Docker image from the official Arch Linux image. These are the things I have done so far:
I PULL-ed the official Arch Linux Image:
docker pull base/archlinux

I wrote this "Dockerfile":
# Set base image
FROM base/archlinux:latest

# Fix mirrorlist file
#RUN rm /etc/pacman.d/mirrorlist
#RUN echo "Server = http://..." >> /etc/pacman.d/mirrorlist
#RUN echo "Server = http://..." >> /etc/pacman.d/mirrorlist
#RUN echo "Server = http://..." >> /etc/pacman.d/mirrorlist
#RUN echo "Server = http://..." >> /etc/pacman.d/mirrorlist

# Update pacman and install packages
RUN pacman-db-upgrade
RUN pacman -Syyu --noconfirm
RUN pacman -S --noconfirm nodejs phantomjs cronie

# Make cronjobs
RUN echo "*/2 * * * *   node /srv/visitor/visitor.js" >> mycronjobs
RUN echo "*/5 * * * *   killall -older-than 5m phantomjs" >> mycronjobs
RUN echo "0 0 * * *     rm /srv/visitor/visitor-info.log" >> mycronjobs
RUN crontab mycronjobs
RUN rm mycronjobs

# Fix hosts file
RUN echo "192.92.13.243 www.lololol.gr"

# Copy app code
COPY . /srv/visitor

# Install app dependencies
RUN cd /srv/visitor
RUN npm install

EXPOSE 80
CMD ["/bin/bash"]

What I want is the container to start at the command prompt, so that I can run in in interactive mode, and attach to it.
Now, I get this error at the time of building the image:
Step 3 : RUN pacman -S --noconfirm nodejs phantomjs cronie
 ---> Running in 30870b31aed6
error: failed to initialize alpm library
(database is incorrect version: /var/lib/pacman/)
error:   try running pacman-db-upgrade
INFO[0127] The command [/bin/sh -c pacman -S --noconfirm nodejs phantomjs cronie] returned a non-zero code: 255

What confuses me is that it looks like the package database is updated correctly, and the base system upgraded, and it hangs when trying to install three packages manually.
Any ideas?

A:

Well, I don't know Arch at all, but if you do this:
RUN pacman-db-upgrade

And then run this to upgrade your current packages:
RUN pacman -Syyu --noconfirm

It seems possible that you've just upgraded pacman and any other tools that touch the package database, so that when you run your next pacman command...
RUN pacman -S --noconfirm nodejs phantomjs cronie

...it fails because the package database has not been upgraded by the currently installed tools.  I suspect you want to re-order those RUN statements:
RUN pacman -Syyu --noconfirm
RUN pacman-db-upgrade
RUN pacman -S --noconfirm nodejs phantomjs cronie


Q:

How to combine list of X and list of Y into one (X,Y) list?

I have two lists:
X = [1.4 ,3.2, 5.8, 2.1, 3.5]
Y = [2.1, 5.6, 1.2, 1.3, 4.6]

How can I make one array from everything in X and Y?
I have tried this:
for i in X:
    X_Y[i] = {X[i], Y[i]}

But it gives me an error list indices must be integers or slices, not float
So then I tried zip but it just gave me a location zip at ...
I would appreciate any help!

A:

You can use zip and list comprehension to get a list of (X, Y) tuples.
XY = [i for i in zip(X, Y)]
# [(1.4, 2.1), (3.2, 5.6), (5.8, 1.2), (2.1, 1.3), (3.5, 4.6)]

Shorter version (See also Nathan's solution below)
XY = list(zip(X, Y))

Problem in your solution: When you do for i in X:, you are basically iterating over the individual elements of X. So in the first iteration, i will be 1.4 and then you do X_Y[i]. First problem is that you didn't initialize the empty list X_Y and second, the indices for the list cannot be float. Moreover, to add elements to a list, you use append. X[i], Y[i] for the first iteration means X[1.4], Y[1.4] which is incorrect.

How to make your code work?
You initialize an empty list first. Then you iterate over the length of the X and Y lists and then append each pair one by one as following:
X_Y = []
for i in range(len(X)):
    X_Y.append((X[i], Y[i]))

A one liner for these three lines of code using list comprehension would be
X_Y = [(X[i], Y[i]) for i in range(len(X))]

Another one liner using map and lambda function. Here you create a lambda function which takes two arguments: x and y and performs operation (x, y) element wise on the actual lists X and Y. list() acts on the mapped generator to get you the final list X_Y.
X_Y = list(map(lambda x, y: (x, y), X, Y))


Q:

Covariant derivatives and curvature

Let $\nabla$ be a covariant derivative on a manifold $M$ with $T$ and $R$ the torsion and curvature respectively. Suppose that $T=R=0$, could we ensure that the Christoffel symbols are 0 respect to a specific local chart?
In the case of the answer is affirmative, does somebody know a reference to see the proof?
Thank you very much.

A:

Choose a point $p \in M$ and a small neighborhood $U$ of $p$ diffeomorphic to a ball. Since the curvature vanishes, you know that parallel transport doesn't depend on the path in $U$ (see any book which discusses holonomy). Choose some basis $(e_1,\dots,e_n)$ of $T_pM$ and using parallel transport extend it to a local frame $(E_1,\dots,E_n)$ on $U$. The vector fields $E_i$ satisfy $\nabla E_i = 0$. Since $\nabla$ is torsion-free, we have
$$ 0 = T(E_i, E_j)  = \nabla_{E_i} E_j - \nabla_{E_j} E_i - [E_i, E_j] = -[E_i, E_j] $$
so $[E_i,E_j] = 0$ for all $1 \leq i, j \leq n$. By the theorem describing the canonical form for commuting vector fields (Theorem 9.46 in "Introduction to Smooth Manifolds" by Lee), this implies that we can find a coordinate neighborhood around $p$ such that $E_i = \frac{\partial}{\partial x^i}$ in that neighborhood. Since $\nabla_{E_i} E_j = \nabla_{\partial_i}{\partial_j} = 0$, the Christoffel symbols with respect to the chart $(x^1,\dots,x^n)$ will vanish.


Q:

Remove layer of array that contains all zeros

I'm trying to remove a layer of an array that contains all zeros. Here's an example:
ii = c(25, 9, 0, 6, 19, 30, 13, 27, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 15, 7, 0, 18, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 43, 33, 40, 34, 42)
key = array(ii,dim=c(3,3,5))

The end result would be equivalent to key[,,-c(2,4)] or key[,,c(1,3,5)]. I saw this question but it can only do one row or column. Is there a way to do an entire layer?
Thanks!

A:

One idea, making use of the fact that apply can work on any combination of rows (MARGIN = 1), columns (MARGIN = 2) strata (MARGIN = 3) and higher dimensions as well (MARGIN= 4 and greater).
key[,,!apply(key,3,function(x) all(x == 0) )]
#or more simply:
key[,,apply(key,3,function(x) any(x != 0) )]
#or simpler again:
key[,,apply(key != 0, 3, any)]

#, , 1
#
#     [,1] [,2] [,3]
#[1,]   25    6   13
#[2,]    9   19   27
#[3,]    0   30    4
#
#, , 2
#
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0   15   18
#[3,]    0    7   16
#
#, , 3
#
#     [,1] [,2] [,3]
#[1,]    0    0   40
#[2,]    0   43   34
#[3,]   39   33   42


Q:

Strip outside quotes from text when writing to list in Python

I have a text file that looks like this when opened as file:
'element1', 'element2', 'element3', 'element4'

I then use a list comprehension to read this into a list
thelist = [line.strip() for line in open('file.txt', 'r')]

But the list looks like this with only one element at index 0
["'element1', 'element2', 'element3', 'element4'"]

Since the double quotes are appended to the ends of the first and last elements, python thinks it is a single element list. Is there a way to use the "strip()" inside the list comprehension to remove those outside double quotes?

A:

You don't have a list, you have a string that looks like a Python sequence.
You could use ast.literal_eval() to interpret that as a Python literal; it'll be parsed as a tuple of strings:
import ast

thelist = [ast.literal_eval(line) for line in open('file.txt', 'r')]

or you could just split on the comma, then strip the spaces and quotes:
thelist = [[elem.strip(" '") for elem in line.split(',')]
           for line in open('file.txt', 'r')]

This only works if your quoted values don't themselves contain commas.
Either way you get a list of lists; you could flatten that list:
thelist = [elem for line in open('file.txt', 'r')
                for elem in ast.literal_eval(line)]

or just read the one line:
thelist = ast.literal_eval(next(open('file.txt', 'r')))

You could also use the csv module:
import csv

reader = csv.reader(
    open('file.text', 'rb'),
    quotechar="'", skipinitialspace=True)
thelist = list(reader)

or for the first row only:
thelist = next(reader)


Q:

OnRowEditing Edit Textbox Focus

What I'm trying to do is, upon the GridView_OnRowEditing event, I want to focus on the textbox that appears in the cell I am editing. From there I will trigger a javascript keyboard, but I need to focus on the textbox first before I can do anything.
Here is my current code:
protected void GridView_OnRowEditing(object sender, GridViewEditEventArgs e)
    {
        var row = GridView.Rows[e.NewEditIndex];
        var gridText = (TextBox) row.Cells[5].Controls[0];
        gridText.Focus();
    }

EDIT:
Here's my GridView mark up. I'm not manually setting a textbox. If there is anyway to retrieve an ID of the cell that is converted to the textbox on RowEditing event, please let me know. Thank you.
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataKeyNames="RollNumber" DataSourceID="WoSource" HorizontalAlign="Center"
        OnRowUpdating="GridView1_RowUpdating" AllowSorting="true" Visible="True" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_OnRowEditing" OnRowCancelingEdit="GridView1_OnRowCancelingEdit" Width="100%">
        <Columns>
            <asp:BoundField DataField="WorkOrderNo" HeaderText="WorkOrderNo" ReadOnly="True" SortExpression="WorkOrderNo" Visible="False"/>
            <asp:BoundField DataField="RollNumber" HeaderText="RollNumber" ReadOnly="True" SortExpression="RollNumber" />
            <asp:BoundField DataField="ModelNumber" HeaderText="ModelNumber" ReadOnly="True" SortExpression="ModelNumber" />
            <asp:BoundField DataField="QtyGood" HeaderText="QtyGood" ReadOnly="True" SortExpression="QtyGood" />
            <asp:BoundField DataField="QtyRun" HeaderText="QtyRun" SortExpression="QtyRun"><ControlStyle Width="100%" Height="100%" Font-Size="36px"></ControlStyle></asp:BoundField>
        </Columns>
    </asp:GridView>

A:

With some help from @okisinch I discovered I could do this:
        $('#<%=GridView1.ClientID%> :input:enabled:visible:first').focus();
        $('#<%=GridView1.ClientID%> :input:enabled:visible:first').select();

The benefit of this is that I wouldn't need to find an textbox ID to be able to focus.
This link was the resource that helped me.
Edit: Discovered this code works as well. Note that the #insideContainer is a jquery keyboard that was implemented. I figured I would add the triggering that I did.
    $(function () {
        if ($('#<%=GridView1.ClientID%> :input:enabled:visible:first').val()) {
            $('#<%=GridView1.ClientID%> :input:enabled:visible:first').focus();
            $('#<%=GridView1.ClientID%> :input:enabled:visible:first').select();
            $('#insideContainer').show();
        } else {
            $('#insideContainer').hide();
        }
    });