Q:

what is the use of "@" symbol in the view file while property binding?

@Component({
  selector: 'app-hero-list-basic',
  template: `
<ul>
  <li *ngFor="let hero of heroes"
      [@heroState]="hero.state"
      (click)="hero.toggleState()">
    {{hero.name}}
  </li>
</ul>`,

I tried angular animations and it works fine, I don't understand this template part, why are they using @-symbol infront of the trigger in the view.
Docs: here

A:

That is used for triggering animations, which would load the specific styles from the styling file when you need it,
In the above when the variable heroState is inactive it will load the particular style with the animation
animations: [
  trigger('heroState', [
    state('inactive', style({
      backgroundColor: '#eee',
      transform: 'scale(1)'
    })),
    state('active',   style({
      backgroundColor: '#cfd8dc',
      transform: 'scale(1.1)'
    })),
    transition('inactive => active', animate('100ms ease-in')),
    transition('active => inactive', animate('100ms ease-out'))
  ])
]


Q:

Is there a definitive list of features in TFS 2010?

I don't want to know what the "new" features are, nor do I really want to know what capabilities are in Visual Studio (like modeling and such) that have nothing to do with TFS.
I have searched high and low and cannot seem to find the complete list of features anywhere.
Has anyone got a compiled list or can point me in the right direction on where to find such a list?

A:

I think this is what you're looking for: http://www.microsoft.com/visualstudio/en-us/products/2010-editions/team-foundation-server/features


Q:

analogue $ (document). click (function (e) without reference of event

I need to close some popup, click-through beyond.
For this I use the following code:
$(document).click(function(e){
    var target = $(e.target);
    if (target.is('div.date_body') || target.is('div.date_header') || target.is('div.date_header button') || target.parents('.popuplayout').length)
        return;

    $(document).unbind('click', arguments.callee);
    scope.callFadeOut();
    scope.accept();
});

But now, it was necessary to abandon the argument e passed.
Perhaps someone can suggest a way to implement it?

A:

Ok here is a code that should more or less do the same, also using event is probably the best call even Angular return the event object.
http://jsfiddle.net/6T4Rn/
Click once to see do nothing, note that it is triggered multiple times due to event propagation and well you need to access event to stop that.
If you remove the

, run the jsfiddle and click it will output do stuff here only once as the we unbind the handler.
HTML - generated by guess based on your JS

        <button>Button</button>

JS
// Basically target all elements but not the one we want to ignore
var selector = "*:not(.date_header, .date_header button,.date_body)";

$(selector).on("click", function() {

    // the popup layout check
    if ($(".popup_layout").size()) {
        console.log("do nothing");
        return;
    }

    $(selector).unbind("click");

    // your scope stuff here
    console.log("do stuff");
});


Q:

nameOfClass myObject ((something)someNumber) what does something mean when passing it in a class

How do I pass (something)someNumber in a constructor example: nameOfClass myObject ((something)someNumber); what type of constructor should receive it. I saw it in my exam but whatever I tried it said error. I don't know what it is, I hope someone could tell me how to receive the data. The only thing that I don't understand is (something).
`something` is not a type

Example that was given before.
the tip is not given
 int main() {
        int n, minuti, kojtip;
        char ime[50];
            cin >> ime;
            cin >> minuti;
            cin >> kojtip; //se vnesuva 0 za POP,1 za RAP i 2 za ROK
            Pesna p(ime,minuti,(tip)kojtip);
            p.pecati();
        return 0;
}

Only thing I should do is write the class

A:

From the comment //se vnesuva 0 za POP,1 za RAP i 2 za ROK it appears as if the value of kojtip can be 0, 1 or 2, which would then represent POP, RAP, and ROK respectively, whatever these would mean in the context of the code.
Therefore, you could create an enum as follows:
enum tip
{
    POP,
    RAP,
    ROK
}

This can then be used as it is used in the next statement.
Pesna p(ime,minuti,(tip)kojtip);
Of course, there should a class Pesna with a parameterized constructor that can accept whatever you are passing.


Q:

Is it possible to retrieve all posts with a certain value for metadata?

Under 4.5, I have posts with meta_key as series and meta_value as 19, 20, etc
I am trying to loop through them in a template, and I guess I'm a special kind of dense.
Most recently I have tried
$args = [
    'post_type' => 'series',
    'posts_per_page' => -1,
    'meta_key' => 'series',
    'meta_query' => [
        'key' => 'series',
        'value' => 19,
        'compare' => '=',
    ],
];

$posts = new WP_Query( $args );

It seems to return empty objects, or a result of one, depending on what I change.
Is there some trick to looping through, maybe?

A:

I am assuming your custom post type is also "series".
Can you try this, it should work.
 $args = [
        'post_type' => 'series',
        'posts_per_page' => -1,
        'meta_query' => [
            [
            'key' => 'series',
            'value' => 19,
            'compare' => '=',
            'type'=>'NUMERIC'
            ]
        ],
    ];

    $posts = new WP_Query( $args );

or you can simple use:
$args = [
            'post_type' => 'series',
            'posts_per_page' => -1,
            'meta_key'=>'series',
            'meta_value'=>19,
            'meta_compare'=>'=',
            'meta_type'=>'NUMERIC'
        ];

        $posts = new WP_Query( $args );

If you are using these meta values as NUMERIC it will be essential to provide "meta_type", as WordPress treats "Numeric" and "Char" values very differently. As you seems to use these value as Number, you need to provide "meta_type"


Q:

ipsec vpn up, but no traffic, no ping

I've set up a VPN between my mikrotik router and Google Cloud Platform VPN.
According to the Green check next to peer IP on the VPN Console, VPN is up, but all pings are timed out.
> /ip ipsec policy print
Flags: T - template, X - disabled, D - dynamic, I - inactive, * - default
 0 T * group=default src-address=::/0 dst-address=::/0 protocol=all
       proposal=default template=yes

 1     src-address=192.168.88.0/24 src-port=any dst-address=10.240.0.0/24
       dst-port=any protocol=all action=encrypt level=require
       ipsec-protocols=esp tunnel=yes sa-src-address=xxx.xxx.xxx.xxx
       sa-dst-address=yyy.yyy.yyy.yyy proposal=default priority=0

where xxx.xxx.xxx.xxx is my router's public ip, and yyy.yyy.yyy.yyy is the IP to VPN server; 192.168.88.0/24 is my home LAN, and 10.240.0.0/24 is remote LAN.
> ping
address: 10.240.0.1
  SEQ HOST                                     SIZE TTL TIME  STATUS
    0 10.240.0.1                                              timeout
    1 10.240.0.1                                              timeout
    2 10.240.0.1                                              timeout
    3 10.240.0.1                                              timeout
    4 10.240.0.1                                              timeout
    5 10.240.0.1                                              timeout
    sent=6 received=0 packet-loss=100%

A:

I figured out that GCE's IPSEC only connects sites, after route table set, you still need a VM instance to do the actual traffic forwarding.


Q:

How do I programatically get my Azure storage endpoint URLs?

I'm fairly new to Azure and I'm using Blob storage to store some binary images, but I can't seem to figure out how to programatically get my Azure storage endpoint URLs?
I am trying to render out some  tags that render correctly locally using the simulator, or when deployed to my live Azure instance.
So for example if I launch my site locally it would render out as:

and when deployed to Azure it would render out as:

Obviously one way would be to just store it as a setting in my ServiceConfiguration.Local.cscfg and ServiceConfiguration.Cloud.cscfg files, but there must be a way to get this value programatically.

A:

You're correct in that your connection strings should be stored in your configuration, and you can have different values for local and cloud. This is very simple to get at, programmatically:
First, make sure you set a config setting publisher during role startup:
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));

Now just retrieve your storage account and pull the URL:
var storageAccount = CloudStorageAccount.FromConfigurationSetting("MyStorage");
var urlBase = storageAccount.BlobEndpoint;

At this point, you'd base your IMG tags off urlBase.


Q:

Serialization using Json.NET

using JavaScriptSerializer we serialize like this:
var serializer = new JavaScriptSerializer();

string requestData = serializer.Serialize(new
{
   EventID = 1,
   SubscriberID = 5,
   ToList = "abcd",
   TemplateParamVals = ""
 });

How do I do the same using Json.NET?
The var serializer will be used in UploadDataTaskAsync method of WebClient.

A:

If you want to serialize to a string, you can use the static methods in the JsonConvert class.
string requestData = JsonConvert.SerializeObject(new
{
   EventID = 1,
   SubscriberID = 5,
   ToList = "abcd",
   TemplateParamVals = ""
 });

To serialize to a JsonWriter or TextWriter, use the JsonSerializer class.
var serializer = new JsonSerializer();
serializer.Serialize(writer, obj);


Q:

Remove an action from init in wordpress

I have a theme that defines a new post type but I want to remove that function in the child theme:
PARENT THEME FUNCTION:
add_action('init', 'portfolio_register');

function portfolio_register()
{
//post type definition
}

CHILD THEME FUNCTION:
This is what I tried but it is not working.
function child_remove_parent_function() {
    remove_action( 'init', 'portfolio_register' );
}
add_action( 'init', 'child_remove_parent_function', 15 );

Anyone has an idea of what am I doing wrong?
Thanks in advance.

A:

try this code before add action in child theme function.php
<?php
remove_action( 'init', 'portfolio_register' );
?>

or
<?php
add_action( 'after_setup_theme','remove_portfolio', 100 );

function remove_portfolio() {
    remove_action( 'init', 'portfolio_register');
}
?>


Q:

Disable button when clicked, then re-enable it

I am starting out Android development by building a simple quiz app with only two buttons, True and False. The app displays a Toast saying whether the answer is correct or incorrect.
What I am trying to do is disable both the buttons as soon as either is clicked/tapped, then re-enable them after the Toast has been displayed. This is what I tried in my listener for the buttons:
mFalseButton.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v){
            mTrueButton.setEnabled(false);
            mFalseButton.setEnabled(false);

            checkAnswer(false); //Display the appropriate Toast

            mTrueButton.setEnabled(true);
            mFalseButton.setEnabled(true);
        }
    });

This does not work. My buttons never get disabled when they are clicked/tapped. How can I do this correctly? Any help would be highly appreciated.

A:

Enable with a Handler like this after 1500 ms.
mTrueButton.setEnabled(false);
mFalseButton.setEnabled(false);

checkAnswer(false); //Display the appropriate Toast

new Handler().postDelayed(new Runnable() {
  @Override
  public void run() {
      mTrueButton.setEnabled(true);
      mFalseButton.setEnabled(true);
  }
}, 1500);

A:

Use
mTrueButton.setClickable(false);

instead of
mTrueButton.setEnable(false);


Q:

Visual Studio 2012: compile more TypeScript files to one JavaScript file

Is it possible to set a "compiler" option to compile more TypeScript files in one project to one JavaScript file?
The only solution I can find is passing multiple files to the "tsc" manually by hand, but I'd like to use the features of the IDE Visual Studio 2012.

A:

I am using bundling to do this in ASP.NET. You can use bundling with MVC or Web Forms.
If you are using Web Essentials, you will already be getting both a .js and a .min.js and bundling is clever enough to use the .js files at debug time and the minified versions in production - so you can debug easily but get smaller files in live.
You can read all about Bundling and Minification on the ASP.NET site.
However, if you want TypeScript to bundle the file (it won't minify it) you just need to use the following flag:
tsc --out combined.js app.ts

TypeScript will walk the dependencies and sort out the ordering for you so all you need to worry about is minifying the combined file.


Q:

Android fragments and activities questions

This is sort of an extension from a previous question, but with more questions and less code (Android starting another activity or calling a method from another class (using fragments)).  I'm trying to get a better idea of how fragments and activities work inside Android apps while writing a sample app of a navigation drawer combined with location API code.
As I understand it, the navigation drawer has to be created extending an Activity so as to do the UI components properly.  What I've done so far is broken down my UI panes into different fragments with different XML and Java files for each.  Java file builds the UI from the XML specified in it, and displays the content in the content pane while keeping the nav drawer in tact, similar to this:  http://manishkpr.webheavens.com/android-navigation-drawer-example-using-fragments/.
Each of those fragments, with the exception of "Home", needs code from the Location APIs/Location Activity, which is based on this MainActivity:  https://developer.android.com/training/location/retrieve-current.html.  However I am having two problems:

My Location Activity class has code onCreate to populate TextView variables from the UI.  But the UI is all handled by fragments.  So every time the Location Activity is created, those variables are null because the Activity doesn't seem communicate with the fragment UI.
The buttons in the fragments call methods that only exist in Location Activity.  And they don't seem to communicate with the activity, only their fragment Java class.

So first off, does this sound like the proper way to do this?  Using fragments to handle the options in the navigation drawer and producing content in the content pane?  If so, how do I make it work with the Location Activity?

A:

ive encountered what you are saying here in many aspects, and i don't think there is right and wrong here.. mostly because sometimes the work don't give you a free hand to do what you want.

answer:
yes you are right, you have some kind of an "egg & the chicken" situation here, so, how to solve it :

a. lets assume that you don't want the user to do anything until you finish inflating the fragment,
so the first action will be (ui/ux) showing a progress dialog.
b. for connivance matter only, assume you are adding or already add your fragment inside some kind of layout (lets say relative layout) ..
this layout can be extended to your own class see :
http://developer.android.com/training/custom-views/create-view.html
now, at your special class you can use one of two (depending the moment you want to enter)
either -
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }
or -
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
(put in mind that onMeasure is the potential to be called many time and not only on the start.)
so, we have a view, that is being extended, which we can grep on the onCreate of our activity even before it is being created and inflated.
in this extended view i would add a public function like:
public void setOnFinishInflatingTheChikenOrTheEggListener(IonFinished listenr) ...
the IonFinished  will be a simple interface with a simple function, only to tell you that the view finish inflating himself on the screen.
c. now let your activity implements IonFinished, and pass it into the  setOnFinishInflatingTheChikenOrTheEggListener function as a param, save it there, and when one of the function we Override before is being called you can trigger this listener.
d. this function is been trigger in you activity, here it is safe to get you fragment, and do something with him.. cause you are sure all of your views is in place... (dont forget to dismiss dialog at this point).
(if you didnt understand, tell me and ill make an example for you...)
2.
answer:
lets continue with the second problem, this is much easier then before,
in your fragment you have buttons, to them you set an onClickListner ...
in it you shoud use the following:
Activity activity =  getActivity();
if(activity!=null && activity instanceof LocationActivity ){
LocationActivity myLocationActivity = (LocationActivity)activity;
//****************************************************************
// call here to any public function in your activity, get set listeners, basically do anything..
}

hope it helps to understand more about fragments...


Q:

C++print container

I am attempting to print containers, like sets and maps. The book I am using says the following code is valid:
#include <iostream>
#include <set>
#include <iterator>
#include <fstream>
using namespace std;

template <typename Container>
void print (const Container & c, ostream & out = cout)
{
    typename Container::const_iterator itr;
    for( itr=c.begin(); itr!=c.end(); ++itr)
        out << *itr << " ";
    out << endl;
}

int main()
{
    ifstream fin("Test.txt");
    set<string> s(  istream_iterator<string>(fin),
                    istream_iterator<string>() );
    print( s );

    return 0;
}

Yet I am getting the an error from Visual Studio's compiler. What am I missing? I know it is likely something simple like an include yet I am unfamiliar with STL Containers and C++ iterators.
I already have #include <iterator>
Errors:

'Container': must be a class or namespace when followed by '::'
'itr' : undeclared identifier
'const_iterator' : is not a member of '`global namespace''

and a few more I am sure are a result of the first one.
Edit:
Per the textbook, the following code should be equivalent to that in my main. I could not get it to work but it may help:
ifstream fin("Test.txt");
string x;
set<string> s;
while( fin >> x)
    s.insert(x);

Edit:
Visual Studio build output:
------ Build started: Project: project, Configuration: Debug Win32 ------
Build started 4/15/2012 1:19:25 PM.
InitializeBuildStatus:

  Touching "Debug\project.unsuccessfulbuild".

ClCompile:

  Project4.cpp

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(11): error C2825: 'Container': must be a class or namespace when followed by '::'

          c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(22) : see reference to function template instantiation 'void print<std::set<_Kty>
(std::istream_iterator<_Ty>,std::istream_iterator<_Ty> (__cdecl *)(void))>(Container (__cdecl &),std::ostream &)' being compiled

          with

          [

              _Kty=std::string,

              _Ty=std::string,

              Container=std::set<std::string> (std::istream_iterator<std::string>,std::istream_iterator<std::string> (__cdecl *)(void))

          ]

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(11): error C2039: 'const_iterator' : is not a member of '`global namespace''

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(11): error C2146: syntax error : missing ';' before identifier 'itr'

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(11): error C2065: 'itr' : undeclared identifier

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2065: 'itr' : undeclared identifier

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2228: left of '.begin' must have class/struct/union

          type is 'std::set<_Kty> (__cdecl &)'

          with

          [

              _Kty=std::string

          ]

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2065: 'itr' : undeclared identifier

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2228: left of '.end' must have class/struct/union

          type is 'std::set<_Kty> (__cdecl &)'

          with

          [

              _Kty=std::string

          ]

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2065: 'itr' : undeclared identifier

c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(13): error C2065: 'itr' : undeclared identifier

Build FAILED.

Time Elapsed 00:00:01.00

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

A:

It thinks this is a function declaration:
set<string> s(  istream_iterator<string>(fin),
                istream_iterator<string>() );

Adding an extra pair of parentheses will correct it:
set<string> s( (istream_iterator<string>(fin)),
                istream_iterator<string>() );

There are many examples of this on SO if you search for Most Vexing Parse.
Edit: You also need to add #include <string>


Q:

Efficient 2d Java Line of Sight for a lot of entities?

My problem today is this:

I have many civilians going around, they are classes stored by an arraylist.
The idea is when they see another civilian panic, they'll start to panic and it will spread.
First I call each classes Step() function by looping through an iterator. Then in the Step() function it goes through another civillian iterator
     As it goes through, it tries to detect whether it can see the other civillian in the iterator, this is where performance time goes from 0 to 50 Milliseconds for having 100 Civillians.
This is the problem I need to fix, I tried to make an easy way to detect whether any objects are in the way of point a to point b.
Here's the code for the line of sight:
public static Object LOS(int x, int y, int x2, int y2, String Scan, Object Me, Object You) {
   DirectionX = (x-x2)/Quality;
   DirectionY = (y-y2)/Quality;
   CurrentX = x;
   CurrentY = y;
   String[] ScanArray = Scan.split(":");
   for(int I=0;I<=Quality;I++) {
      for(String Type: ScanArray) {
         if(Type.equals("Boxs")) {
            Iterator it=Level.Boxs.iterator();
            while(it.hasNext()) {
               Box Box = (Box)it.next();
               if(Me!=Box&&You!=Box) {
                  //Collision = Tools.Collision((int)(CurrentX-(Width/2)), (int)(CurrentY-(Width/2)), Width, Width, Box.GetX(), Box.GetY(), Box.GetWidth(), Box.GetHeight(), 1);
                  boolean Col = Tools.BasicCollision((int)(CurrentX-(Width/2)), (int)(CurrentY-(Width/2)), Width, Width, Box.GetX(), Box.GetY(), Box.GetWidth(), Box.GetHeight());
               }
            }
         }
      }

      CurrentX-=DirectionX;
      CurrentY-=DirectionY;
   }
   return null;
}

If you have a headache the fundamentals are:
It figures out 10 points in between and detects whether it is inside, using BasicCollision:
public static boolean BasicCollision(int x, int y, int width, int height, int x2, int y2, int width2, int height2) {
   if(x<x2+width&&x+width>x2&&y<y2+height&&y+height>y2) {
      return true;
   } else {
      return false;
   }
}

My question is: Is there an easier way to detect this Line of Sight that doesn't severely impact my performance in large numbers? Any feedback?

A:

One thought would be to maintain non-panicky and panicky people in separate lists N and P, and then limit your LOS checks to <n, p> ∈ N × P. That way you never check same-state people, which will speed things up.
Another thing (which you may already be doing--not sure) would be to make sure that once you determine that a nonpanicker has become a panicker, immediately halt remaining checks for that former nonpanicker. This will help your algorithm scale with increasing population size for a fixed map. When the population gets very large then you should converge toward 100% panicking pretty quickly, which means no more checks are needed as noted in the comments below.


Q:

Sort data based on conditions

I have a (x) data frame in R with 5 numeric columns and apart from this one information is sorting order to be followed in form of a vector i.e.
1, 0, 2, 4, 3

dataset
v1 v2 v3 v4 v5
1  2  3  4  5
3  13 12 1  4
6  4  6  5  3

Expected result
v1 v2 v3 v4 v5
3  13 12 1  4
1  2  2  4  5
6  4  6  5  3

this vector define the sorting order that first column needs to be sorted first then 3rd column then 5th column and then 4th column. manually it can be done as
x = x[order(x[1],)]
x = x[order(x[3],)]
x = x[order(x[5],)]
x = x[order(x[4],)]
rownames(x) = NULL

Problem is for 5 columns, it is easy but it is complicated for 100s of columns.
 any lead to this will be appreciated.
Thanks

A:

We can do a match on the original vector and then use a for loop to get the output
i1 <-  match(seq_along(x), vec, nomatch = 0)
i1 <- i1[i1!=0]
for(i in i1){
 x <- x[order(x[i]),]
}

x
#   v1 v2 v3 v4 v5
# 2  3 13 12  1  4
# 1  1  2  3  4  5
# 3  6  4  6  5  3

data
x <- structure(list(v1 = c(1L, 3L, 6L), v2 = c(2L, 13L, 4L), v3 = c(3L,
12L, 6L), v4 = c(4L, 1L, 5L), v5 = c(5L, 4L, 3L)), .Names = c("v1",
"v2", "v3", "v4", "v5"), class = "data.frame", row.names = c(NA,
-3L))

vec <- c(1, 0, 2, 4, 3)


Q:

How to programmatically start/stop FFMPEG stream transcoding

I have an ip webcam which provides an MJPEG stream. I can successfully transcode and save that stream with ffmpeg under OSX. The following gives me pretty much what I want:
ffmpeg -f mjpeg -i "http://user:pass@10.0.1.200/nphMotionJpeg?Resolution=640x480&Quality=Standard" -b:v 1500k -vcodec libx264 /tmp/test.mp4

That will start an FFMPEG session and begin saving the live stream to my test.mp4 file. pressing q will quit ffmpeg and save the file.
I would like to programmatically start & stop the recording using a PHP or Bash shell script. I have tried the following:
<?php

$pid = pcntl_fork();

if($pid == -1){
    die("could not fork");
}elseif($pid){
    // we are the parent...
    print $pid.' started recording. waiting 10 seconds...';
    sleep(10); // Wait 10 seconds

    print_r(shell_exec("kill ".$pid)); // Kill the child recording process

    echo 'done';
    exit();
}else{
    // we are the child process. call ffmpeg.
    exec('../lib/ffmpeg -f mjpeg -i "http://user:pass@10.0.1.200/nphMotionJpeg?Resolution=640x480&Quality=Standard" -b:v 1500k -vcodec libx264 /tmp/test.mp4');
}

But there are two problems:

The ffmpeg process does not end/die (probably because its forked again)
When I manually kill the ffmpeg process, the video file is not readable

A:

So I was doing a combination of things wrong.
For starters, I needed to push the output form ffmpeg to a log file and also tell it to overwrite my temp file without prompting using the -y argument.
So instead of
ffmpeg -f mjpeg -i "http://user:pass@10.0.1.200/nphMotionJpeg?Resolution=640x480&Quality=Standard" -b:v 1500k -vcodec libx264 /tmp/test.mp4

I am now using
ffmpeg -y -f mjpeg -i "http://user:pass@10.0.1.200/nphMotionJpeg?Resolution=640x480&Quality=Standard" -b:v 1500k -vcodec libx264 /tmp/test.mp4 </dev/null >/dev/null 2>/tmp/ffmpeg.log &

The second problem was that I wasn't waiting long enough before sending the kill command to ffmpeg, and so a corrupt file was being created.
By adding the -t (for time limit) argument with 1 second, I determined that it takes an average of 15 seconds for ffmpeg to record 1 second of video. Increasing the time limit to 10 seconds made the average increase to 25 seconds, so it seems that on my server at least, theres 14 seconds of overhead. By increasing my sleep command in my php script to 30 seconds, I was able to get a useable video file.
So having PHP kill the ffmpeg process results in an unknown (or approximate at best) recording time length which is completely dependent on CPU power, network bandwidth, etc.
Thats a bit of a bummer because I had hoped to be able to increase the recording length depending on some external variables (I have insteon motion sensors feeding a database, i would like to record until the motion stops).
In any event, here is a working PHP script in case it helps someone in the future:
<?php
print date('H:i:s')."\nStarted recording. waiting 60 seconds...\n";
exec('../lib/ffmpeg -y -f mjpeg -i "http://user:pass@10.0.1.200/nphMotionJpeg?Resolution=640x480&Quality=Standard" -b:v 1500k -vcodec libx264 /tmp/test.mp4 </dev/null >/dev/null 2>/tmp/ffmpeg.log &');
sleep(60); // Wait long enough before killing, otherwise the video will be corrupt!

shell_exec('pkill ffmpeg'); // find and kill
echo "done\n\n";
exit();
?>


Q:

c# extracting a certain value within a string

I'm trying to remove a certain bit of text within a string.
Say the string I have contains html elements, like paragraph tags, I created some sort of tokens that will be identified with "{" at the beginning and "}" at the end.
So essentially the string I have would look like this:
text = "
{token}

 text goes here  {token3}
"

I'm wondering is there a way to extract all the words including the "{}" using C#-Code within the string.
Whilst each token could be different to the next, that is why i must use "{" and "}" to identify them as seen below
At the moment I'm got to this code:
var newWord = text.Contains("{") && word.Contains("}")

A:

Something like
var r = new Regex("({.*?})");
foreach(var match in r.Matches(myString)) ...

The ? means that your regex is non-greedy. If you omit it you´ll simply get everythinbg between the first { and the last }.
Alternativly you may also use this:
var index = text.IndexOf("{");
while (index != -1)
{
    var end = text.IndexOf("}", index);
    result.Add(text.Substring(index, end - index + 1));
    index = text.IndexOf("{", index + 1);
}


Q:

radiator grill fins bent

I have a over heating problem. I have replaced the water pump, thermostat, upper radiator hose and the coolant temperature sensor. They were all in need of replacement, but my car still over heats when going up hill only. I checked the fins on my radiator and there are three medium potatoe size areas where the fins are badly bent. Could this be causing my over heating problem?
My other question is if the fins are bent can this cause the transmission fluid to get to hot. My reason for this question is because when the car gets to normal operating temperature, but I have been driving for some time my transmission during first and second gear shifts hard. When the car is cool it does not?

A:

Firstly, you don't mention what car you have, which can help with diagnosis as we may be able to point you towards known issues with certain models.
Bent or missing fins will cause the radiator to work less efficiently than normal, but that sounds like a fairly small area, so shouldn't be causing you a major problem. It is probably worth flushing the radiator out if you haven't done so already.
The engine radiator is usually totally unconnected to the transmission fluid, so I doubt the two problems are related. Do you have a transmission cooler? If so, what condition is that in? Have you checked the condition and level of the transmission fluid?


Q:

Need a linebreak in text while converting html to txt

I am using xslt to converting html to a text file. When I view it in notepad, the content is shown as a single line.
What shall I make it to display like a paragraph. What should be included in template match p, after taking content from p tag to make the next p tag content to display in next line?

A:

To generate a line break in xslt you can do:
<xsl:text>
</xsl:text>

then the Linebreak between the tags should transfer to your textfile.


Q:

Can I copy a javascript image object?

I'm building a simple game engine in javascript, and I'm currently building separate spritesheets for left and right animations, but that seems a bit of a pain... What I want to do is something like this:
function loadSprite(graphic)
{
   var left_graphic = graphic;
   var right_graphic = graphic.flip();  //Create a flipped copy of the graphic
}

// [...]

function update()
{
   if(speed>0) context.drawImage(left_graphic);
   if(speed<0) context.drawImage(right_graphic);
}

To clarify, I want to create a copy of an Image() object, and mirror flip all it's pixels, so I don't have to maintain two spritesheets.
Is it possible?

A:

First off, you can copy the pixel data using the method described here: Get image data in JavaScript?
I assume you're using a sprite sheet with fixed-sized images.  Then you'll have to write an algorithm to flip each image in your image sheet:
for each image in the sheet:
  calculate sheet offset (xOffset, yOffset)
  for each pixel in half the image:
    read pixel ((x, y) + (xOffset, yOffset))
    read opposite pixel ((width - x, y) + (xOffset, yOffset))
    write on top of opposite pixel
    write opposite pixel on top of current pixel


Q:

Something Simple

A simple task: It’s White to move selfmate themselves in three moves. White pawns are moving up.

A:

The secret is that we are

 allowing promotion to an enemy piece. A literal reading of a previous version of the promotion rule implied that promotion to an enemy piece was legal. See this question: https://chess.stackexchange.com/questions/2756/do-the-official-rules-of-chess-forbid-promoting-a-pawn-to-a-piece-of-the-opposit

As a result, we could

 selfmate in two moves, as follows:

 1. dxc8=bN+ Nd6
 2. h8=bN Ng7#

 where the "b" prefix indicates that we are promoting to black knights in both cases.

However, the puzzle asks us to

 selfmate in 3 moves instead. The only way to do so is to throw in an in-between move:

 1. dxc8=bN+ Nd6
 2. b8=bN+ Nc6
 3. h8=bN Ng6#

 All moves are forced.


Q:

Percent function in java

I am a 11 year old app programer and I am making a calculator app. I want to add a percent button, so the user can find percantage, but when I enter 50% of 100, it gives me 0, even when the correct answer is 50. It also says wrong answers for other equations. Please help! This is my java code:
package com.example.lenovouser.calculatoraghav;
//IMPORT
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
// ASSIGNING THE NAMES OR VARIABLES
TextView result;
EditText number1, number2, txt;
Button
add,subtract,divide,multiply,squareroot,square,clear,Exponent,percent;
double resultnum;
int num1,num2,num3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //ASSIGNING THE VARIABLES TO THE ANDROID WIDGETS.
    result = (TextView)findViewById(R.id.sum);
    number1 = (EditText)findViewById(R.id.number1);
    number2 = (EditText)findViewById(R.id.number2);
    txt = (EditText)findViewById(R.id.txt);
    add = (Button)findViewById(R.id.button);
    subtract = (Button)findViewById(R.id.button2);
    multiply = (Button)findViewById(R.id.button3);
    divide = (Button)findViewById(R.id.button4);
    squareroot =(Button)findViewById(R.id.button6);
    square = (Button)findViewById(R.id.button5);
    clear = (Button)findViewById(R.id.button8);
    Exponent = (Button)findViewById(R.id.button9);
    percent = (Button)findViewById(R.id.button10);

    add.setOnClickListener(new View.OnClickListener(){

@Override
    public void onClick(View v){
        //ADD
        num1 = Integer.parseInt(number1.getText() .toString());
        num2 = Integer.parseInt(number2.getText() .toString());
        resultnum = num1 + num2;
        result.setText(String.valueOf(resultnum));
}
});

    subtract.setOnClickListener(new View.OnClickListener(){
        //SUBTRACT
        @Override
        public void onClick(View v){

            num1 = Integer.parseInt(number1.getText() .toString());
            num2 = Integer.parseInt(number2.getText() .toString());
            resultnum = num1 - num2;
            result.setText(String.valueOf(resultnum));
        }
    });

    multiply.setOnClickListener(new View.OnClickListener(){
        //MULTIPLY
        @Override
        public void onClick(View v){

            num1 = Integer.parseInt(number1.getText() .toString());
            num2 = Integer.parseInt(number2.getText() .toString());
            resultnum = num1 * num2;
            result.setText(String.valueOf(resultnum));
        }
    });

    divide.setOnClickListener(new View.OnClickListener(){
        //DIVIDE
        @Override
        public void onClick(View v){

            num1 = Integer.parseInt(number1.getText() .toString());
            num2 = Integer.parseInt(number2.getText() .toString());
            resultnum = num1 / num2;
            result.setText(String.valueOf(resultnum));
        }
    });

    squareroot.setOnClickListener(new View.OnClickListener(){
        //SQUAREROOT
        @Override
        public void onClick(View v){

            num1 = Integer.parseInt(number1.getText() .toString());

            resultnum = (Math.sqrt(num1));
            result.setText(String.valueOf(resultnum));
        }
    });

    square.setOnClickListener(new View.OnClickListener(){
        //SQUARE
        @Override
        public void onClick(View v){

            num1 = Integer.parseInt(txt.getText() .toString());

            resultnum = num1*num1;
            result.setText(String.valueOf(resultnum));
        }
    });

    clear.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v){
        //CLEAR
            num1 = (0);
            num2 = (0);
            num3 = (0);
            number1.setText("");
            number2.setText("");
            txt.setText("");
            resultnum = 0;
            result.setText(String.valueOf(resultnum));
        }
    });

    Exponent.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v){

            //EXPONENT
            int p = Integer.parseInt(number1.getText() .toString());
            int e = Integer.parseInt(number2.getText() .toString());
            resultnum = (Math.pow((double)p, (double)e));
            result.setText(String.valueOf(resultnum));
        }
    });

    percent.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v){

            //PERCENT
            num1 = Integer.parseInt(number1.getText() .toString());
            num2 = Integer.parseInt(number2.getText() .toString());
            resultnum = num1/num2;
            resultnum = resultnum * 100;
            result.setText(String.valueOf(resultnum));
        }
    });
}}

This is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<EditText
    android:id="@+id/number1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="26dp"
    android:ems="10"
    android:hint="number1"
    android:inputType="number"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/number2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="92dp"
    android:ems="10"
    android:hint="number2"
    android:inputType="number"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.502"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/sum"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="15dp"
    android:layout_marginLeft="15dp"
    android:layout_marginTop="24dp"
    android:text="result"
    android:textSize="25sp"
    app:layout_constraintStart_toStartOf="@+id/button"
    app:layout_constraintTop_toBottomOf="@+id/number2" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="18dp"
    android:background="@android:color/holo_blue_bright"
    android:text="ADD-+"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/sum" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="22dp"
    android:background="@android:color/holo_red_light"
    android:text="SUBTRACT--"
    app:layout_constraintStart_toStartOf="@+id/button"
    app:layout_constraintTop_toBottomOf="@+id/button" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="23dp"
    android:background="@android:color/holo_green_dark"
    android:text="MULTIPLY-X"
    app:layout_constraintStart_toStartOf="@+id/button2"
    app:layout_constraintTop_toBottomOf="@+id/button2" />

<Button
    android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="52dp"
    android:text="DIVIDE-/"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="@+id/button3"
    tools:background="@android:color/holo_orange_light" />

<Button
    android:id="@+id/button5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:layout_marginEnd="17dp"
    android:layout_marginRight="17dp"
    android:text="Square"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="@+id/button2" />

<Button
    android:id="@+id/button6"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="32dp"
    android:text="Square Root"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/button2" />

<EditText
    android:id="@+id/txt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="square number"
    android:inputType="number"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button4" />

<Button
    android:id="@+id/button8"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="10dp"
    android:text="CLEAR"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/number2" />

<Button
    android:id="@+id/button9"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="108dp"
    android:layout_marginEnd="16dp"
    android:layout_marginRight="16dp"
    android:text="Exponent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/number2" />

<Button
    android:id="@+id/button10"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="24dp"
    android:layout_marginRight="24dp"
    android:layout_marginBottom="8dp"
    android:text="Percent"
    app:layout_constraintBottom_toTopOf="@+id/txt"
    app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

So far, the calculator preforms well in addition, subtraction, ect. It is the percentage thats bugging me. This my percent function:
        percent.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v){

            //PERCENT
            num1 = Integer.parseInt(number1.getText() .toString());
            num2 = Integer.parseInt(number2.getText() .toString());
            resultnum = num1/num2;
            resultnum = resultnum * 100;
            result.setText(String.valueOf(resultnum));
        }
    });
}}

A:

I think your main problem that you perform calculation of percentage in Integer type. It's better to use double because in Java when you divide a smaller integer to bigger integer you will get 0.
Try to replace:
Double percentage = Double.valueOf(number1.getText().toString())
Integer num2 = Integer.parseInt(number2.getText().toString());
Double resultnum = percentage * num2 / 100;

It's just a draft sample. For sure, it would be better to perform all calculations in Double for such calculator app.
If your final goal to build a reliable calculator you can review even more precise data type: BigDecimal


Q:

"defunct" vs. "deceased" vs. "departed"

After reading some dictionaries I realized that these three words aren't perfectly interchangeable, even if I cannot exactly recognize their differences.
Specifically I don't understand whether "defunct" is used in reference to dead persons or not—it seems to be more appropriate in reference to abstract things ("a defunct argument", "a defunct story")—, and what the contexts are in which we should use "deceased" or "departed".
So, suppose I want to ask to a person if a their relative has died, how can I ask without being disrespectful?

Is/has your sister defunct?

Is/has your sister deceased?

Is/has your sister departed?

A:

Let's begin by confirming your first assumption: you're correct that defunct would not be used to refer to a person, though the dictionary definition might make you think otherwise:

de·funct  adj.
Having ceased to exist or live: a defunct political organization.

Though the definition sounds like it could describe a person, you'll note that the example sentence refers to a non-living entity, and I can't imagine native speakers using defunct to describe a person except in a satirical sense.
Now, as for deceased and departed (and your verb tenses). Deceased is definitely appropriate to be used with people. However it is a state of being, not an action, so you would say:

Is your sister deceased?

What you're asking is is your sister currently in the state of being deceased. If you used has you would be saying has your sister deceased recently? and we don't talk like that; you could say has your sister died recently, but we don't use deceased as a verb like that.
[As an interesting aside, while we don't use decease in that manner, we do use predecease (meaning to die before someone else that way). For example, Mary predeceased her older brothers, Jim and Harry.]
Now, as for departed. Departed can be used in the context of people's deaths, but not in the sentence you've got there. If I heard:

Has your sister departed?

I'd wonder if she'd left for the train station yet, and if I heard:

Is your sister departed?

I'd have no idea what was meant.
The way we use departed in this frame of reference is in common phrases, such as the dearly departed. This has the clear meaning of loved ones who have passed away to native speakers.
However in conversation we tend to use euphemisms to avoid touchy subjects, so probably the most common and socially acceptable sentence would be:

Has your sister passed away?

A:

None of these is really suitable for asking this delicate question.*
Defunct, as you say, is rarely used of persons.
Deceased is mostly legal or official. It is used as an attributive adjective or as a nominal, but rarely as a predicate adjective.

I leave my library to JohnB, the son of my deceased uncle WilliamB.
  According to the police, the deceased is a white male of middle age.

Departed is quite old-fashioned. It is used mostly as a nominal, and my impression is that it is mostly employed now at funerals, by the presiding minister.
The most common verb in US euphemistic speech today is probably pass away or in recent years simply pass. The participle is not used much, however, so you should say

Has your sister passed away?

But in most circumstances I would think it more graceful to ask

Is your sister still alive?

*I myself use die and dead, but I am notoriously crude.


Q:

Convex subsets of an infinite dimensional vector space

Let $C$ be a convex subset of $\mathbb{R}^{α}$ for an ordinal $α$. Call $C$ nice iff for every linear map $λ : \mathbb{R} \to \mathbb{R}^α$, the preimage $λ^{-1}(C) ⊆ \mathbb{R}$ is bounded.
An example of a nice set is the Cartesian product of intervals $[-1, 1]^α$.
I believe that if $α$ is finite, then for any nice subset of $\mathbb{R}^α$, there is an isomorphism $\phi : \mathbb{R}^α \to \mathbb{R}^α$ such that $\phi(C) ⊆ [-1, 1]^α$. Is this also true for infinite $α$?

A:

The answer is no. Let $α = ω + 1$. I'll write elements of $\mathbb{R}^{ω+1}$ as pairs of an element of $\mathbb{R}^\omega$ and an element of $\mathbb{R}$. As this answer (and this one) discusses, there is an unbounded linear function $f : [0, 1]^ω \to \mathbb{R}$. Let
$$
C = \big\{ (x, y) ∈ \mathbb{R}^{ω + 1} \; \big| \; x ∈ [0, 1]^ω, \; 0 ≤ y ≤ f(x) \big\}
$$
$C$ is convex. If $(x, y)$ and $(x', y')$ are in $C$, then we have
\begin{align}
0 & ≤ λy + (1 - λ)y' \\
 & ≤ λf(x) + (1 - λ)f(x') \\
 & = f(λx + (1 - λ)x')
\end{align}
$C$ is nice. Let $λ : \mathbb{R} \to \mathbb{R}^{ω + 1}$ be a linear map. Let $(x, y) = λ(1) ∈ \mathbb{R}^{ω + 1}$. If $x = 0$, then $f(x) = 0$, so $y = 0$, so $λ^{-1}(C) = \{0\}$. Otherwise, for $a > (\sup_i x_i)^{-1}$, we have $(λ(a))_i = a x_i > 1$, and thus $λ(a) ∉ C$. So $λ^{-1}(C)$ is bounded.
But no isomorphism $\phi$ maps $C$ into the cube. For any isomorphism $\phi$, and any $x ∈ [0, 1]^ω$, we have
$$
\phi(x, f(x)) = \phi(x, 0) + f(x) \, \phi(0, 1)
$$
If the first term is always in the cube, then since $f(x)$ is unbounded (and $\phi(0, 1) ≠ 0$) this must land outside of the cube for some $x$.


Q:

Uppercase surname, excluding the lowercase prefix section of a surname

I am trying to determine a method to uppercase a surname; however, excluding the lowercase prefix.
Example of names and their conversion:

MacArthur -> MacARTHUR
McDavid   -> McDAVID
LeBlanc   -> LeBLANC
McIntyre  -> McINTYRE
de Wit    -> de WIT

There are also names that would contain the surnames that would need to be fully capitalized, so a simple function to identify the prefix such as strchr()would not suffice:

Macmaster -> MACMASTER
Macintosh -> MACINTOSH

The PHP function mb_strtoupper() is not appropriate, as it capitalizes the complete string. Similarly strtoupper() is not appropriate, and loses accents on accented names as well.
There are some answers around SO that partly answer the question, such as : Capitalization using PHP
However, the common shortfall is assuming that all names with a surname as as Mac are followed with a capital.
The names are capitalized properly in the database, so we can assume that a name spelled as Macarthur is correct, or MacArthur is correct for another person.

A:

Going with the rule to capitalise everything after the last capital letter:
preg_replace_callback('/\p{Lu}\p{Ll}+$/u',
                      function ($m) { return mb_strtoupper($m[0]); },
                      $name)

\p{Lu} and \p{Ll} are Unicode upper and lower case characters respectively, and mb_strtoupper is unicode aware… for a simple ASCII-only variant this would do too:
preg_replace_callback('/[A-Z][a-z]+$/',
                      function ($m) { return strtoupper($m[0]); },
                      $name)


Q:

While executing mocha tests, Getting error "reflect-metadata shim is required when using class decorators"

Written one mocha test case with chai in Typescript and followed the article http://brianflove.com/2016/11/11/typescript-2-express-mongoose-mocha-chai/ to install all dependencies.
While I am running the test cases with "npm test", I am getting below error

C:\J\MEAN\MSDN-App\node_modules\@angular\core\bundles\core.umd.js:335
                  throw 'reflect-metadata shim is required when using class decorators';
                  ^
  reflect-metadata shim is required when using class decorators
  npm ERR! Test failed.  See above for more details.

The package.json is:

{
  "name": "test-app",
  "version": "1.0.0",
  "description": "test description",
  "main": "server.js",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "test": "mocha -r ts-node/register test/**/*.ts",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "^2.0.1",
    "@angular/compiler": "^2.0.1",
    "@angular/core": "^2.0.1",
    "@angular/forms": "^2.0.1",
    "@angular/http": "^2.0.1",
    "@angular/platform-browser": "^2.0.1",
    "@angular/platform-browser-dynamic": "^2.0.1",
    "@angular/router": "^3.4.10",
    "@angular/upgrade": "^2.0.1",
    "@covalent/core": "^1.0.0-beta.3-2",
    "@ngrx/store": "^2.0.1",
    "@types/node": "7.0.7",
    "@types/underscore": "^1.8.0",
    "angular-in-memory-web-api": "^0.1.1",
    "body-parser": "^1.17.1",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "ejs": "^2.5.6",
    "express": "^4.15.2",
    "mongojs": "^2.4.0",
    "node-sspi": "^0.1.14",
    "nodemailer": "^4.0.1",
    "nodemailer-smtp-transport": "^2.7.4",
    "properties-reader": "0.0.15",
    "reflect-metadata": "^0.1.10",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.39",
    "ts-node": "^3.0.4",
    "underscore": "^1.8.3",
    "zone.js": "^0.6.25"
  },
  "devDependencies": {
    "@types/chai": "^3.5.2",
    "@types/core-js": "0.9.35",
    "@types/mocha": "^2.2.41",
    "chai": "^3.5.0",
    "concurrently": "^3.0.0",
    "lite-server": "^2.2.2",
    "mocha": "^3.4.1",
    "reflect-metadata": "^0.1.10",
    "ts-node": "^3.0.4",
    "typescript": "^2.0.3",
    "typings": "^1.4.0"
  }
}

And tsconfig.json is:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
 "exclude": [
  "node_modules",
  "node_modules/@types",
  "bower_components",
  "typings"
 ]
}

Please help to resolve the error.

A:

Very simple answer but hard to find out. Should not include the @angular/http in test.ts files and to test services use unit testing, to test angular components we must test with Angular testing utilities.


Q:

LIBGDX : add a clickable text link

I'm developing a little game with libgdx and in my about screen I would like to have a label (wrapped in a table) in which there would have a clickable text link (underlined or with a different color) like this:
You can review the code here

Edit:
What I've tried is:
HorizontalGroup monGroup = new HorizontalGroup();
Label howRotationRep = new Label("They have been based on the information provided on this ", new Label.LabelStyle(game.petiteFont, Color.WHITE));
howRotationRep.setWrap(true);
howRotationRep.setWidth(tailleCell);

Label test = new Label(" site", new Label.LabelStyle(game.petiteFont, Color.RED));
test.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {

   Gdx.net.openURI("http://tetrisconcept.net/wiki/SRS");

}
});
monGroup.addActor(howRotationRep);
monGroup.addActor(test);
table.add(monGroup).left().width(tailleCell);

And it gives me this

A:

If you need only a portion of the Label clickable, I think the best way to implement this is having two Labels, this should work:
    Label lblReviewCode = new Label("You can review the code ", skin);
    Label lblReviewCodeLink = new Label("here", skin, "linkstyle");
    // If you don't want to provide a custom style...
    //Label lblReviewCodeLink = new Label("here", skin);
    lblReviewCodeLink.addListener(new ClickListener(){
        @Override
        public void clicked(InputEvent event, float x, float y) {
            Gdx.net.openURI("https://bitbucket.org/batman3000/batris");
        }
    });
    // If you didn't provided the style, you can at least paint it blue by doing this...
    //lblReviewCodeLink.setColor(Color.BLUE);

    HorizontalGroup codeLink = new HorizontalGroup();
    codeLink.addActor(lblReviewCode);
    codeLink.addActor(lblReviewCodeLink);

    table.add(codeLink);


Q:

Can you write a unit test assembly in C# to test against an assembly written in VB?

Probably a dumb question, but can you write a unit test project in one language to test against another project in a different language?
I'd like to translate one of our VB assemblies into C#, but want to build unit tests to verify the results.  I've tried to set a unit test project up to do this, but I can't seem to access the VB code within a unit test... I can't figure out if I'm just missing/doing something stupid, or it really isn't allowed.
EDIT:
I'm going to close this as it seems I've gotten my "Yes, it's possible" answer... I am referencing it, so there's gotta be just something I'm not seeing.

A:

Once you add a reference to your original project or assembly in your unit test project, you should be able to write a unit test without problems, assuming the members you want to test are public. (You can add an InternalsVisibleTo assembly attribute in the original assembly if you need access to classes marked internal).


Q:

how would you approach giving an introductory class about Bayesian statistics?

I need to give a lecture about Bayesian statistics, introducing it to people who have already basic knowledge of classic statistics (but not too much of it in general).
I want to start with some example, showing the main differences between Bayesian statistics and classic statistics. Is anyone familiar with a very basic intro that I can derive slides from, or actual slides I can use?
I think the best would be to start with an example... I would rather not have a coin toss example, but I can be persuaded to do that :-)
I would also be happy to talk about some of the history.

A:

A good book to read/reference for the history is "The Theory That Would Not Die".
For the example I would start with something that can be done either way, a common dataset that a frequentist would do a simple t-test and confidence interval on, then show how you could analyze the same data/question using a Bayesian approach.  Show that for diffuse priors the 2 methods give pretty much the same results.  Then talk about when you might use each one, for the simple case the frequentist approach is quick and easy, but the Bayesian case would allow the use of prior information.  Then maybe show some other examples that could be done either way, but the Bayesian approach has advantages, maybe think about linear regression and show (or briefly point out) that the slopes can be estimated either way and you can constuct intervals either way, but what about if you know the slopes are all non-negative (or want to constrain that anyways).  That can be done using frequentist methods, but it takes more work and it is less clear how to construct the confidence intervals.  A Bayes approach is to just use priors on the slopes that are 0 for negative values.  Then maybe end with a more complicated example where a Bayesian approach really shines.


Q:

Entry message: [MSC v.1500 64 bit (AMD64)] on win32

I was wondering in, when I start python I get the following message:
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

I am using 64 bit python but why does it mention win32 as opposed to win64?

A:

win32 is the general name for the Windows NT/95 API, whether you are on a 32-bit or 64-bit OS (or even using Win32s on a 16-bit OS).*
The 64 bit (AMD64) tells you that it is a 64-bit Python, built for a 64-bit Win32 OS, so everything is good.
The win32 is the same string that you see in sys.platform, which documents the strings you should see for each supported platform.
The [MSC v.1500 64 bit (AMD64)] identifies the compiler. On other platforms, Python doesn't cram the platform information into the compiler-name field.** But I guess they decided it was important, and there was nowhere else for it to go. :)
Anyway, the safe way to get this information is not to try to parse it out of the banner, but to use sys.maxsize.bit_length() > 32 on Python 3.x, or sys.maxsize > 2**32 on Python 2.x. (Note that platform.architecture specifically suggests that.)

* Why? Who knows. Some documentation does talk about "the Win32/Win64 API", although in most of the current docs they avoid that and say "the Windows API". This may be related to the fact that they have trademarks on "Win32", "Windows", and "Windows API", but not "Win64", "Win32 API", or "Win64 API"…
** Partly because it can't know that at compile time, if Python could be built as a universal binary for multiple architectures. For example, Python 2.7.6 on my Mac has both x86 and x86_64 code; it's 32-bit if I run the former, 64-bit if I run the latter. So the compiler just says [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)].


Q:

Android CustomView integrated in Fragment

I want to create a draw application. For this I have created a Custom DrawingView. To enable additional options during the drawing, the CustomView should be included in the activity_main.xml in a specific area.
public class MainActivity extends AppCompatActivity {

DrawingView dv ;
private Paint mPaint;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.GREEN);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(12);

    dv = new DrawingView(this, mPaint);
    setContentView(R.layout.activity_main);
}
}

.
public class DrawingView extends View {

public int width;
public  int height;
private Bitmap mBitmap;
private Canvas  mCanvas;
private Path    mPath;
private Paint   mBitmapPaint, mPaint;
Context context;
private Paint circlePaint;
private Path circlePath;

public DrawingView(Context c, Paint pPaint) {
    super(c);
    context=c;

    mPaint = pPaint;
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    circlePaint = new Paint();
    circlePath = new Path();
    circlePaint.setAntiAlias(true);
    circlePaint.setColor(Color.BLUE);
    circlePaint.setStyle(Paint.Style.STROKE);
    circlePaint.setStrokeJoin(Paint.Join.MITER);
    circlePaint.setStrokeWidth(4f);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.drawBitmap( mBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath( mPath,  mPaint);
    canvas.drawPath( circlePath,  circlePaint);
}

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

private void touch_start(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX = x;
    mY = y;
}

private void touch_move(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
        mX = x;
        mY = y;

        circlePath.reset();
        circlePath.addCircle(mX, mY, 30, Path.Direction.CW);
    }
}

private void touch_up() {
    mPath.lineTo(mX, mY);
    circlePath.reset();
    // commit the path to our offscreen
    mCanvas.drawPath(mPath,  mPaint);
    // kill this so we don't double draw
    mPath.reset();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
    }
    return true;
}
}

.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:gravity="center"
tools:context="de.sentoon.touchtesterv4.MainActivity"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hello World!" />

<de.sentoon.touchtesterv4.DrawingView
    android:layout_width="match_parent"
    android:layout_height="150sp" />
</LinearLayout>

But if I try this, there is always an InflateException thrown
FATAL EXCEPTION: main
              Process: de.sentoon.touchtesterv4, PID: 11743
              java.lang.RuntimeException: Unable to start activity ComponentInfo{de.sentoon.touchtesterv4/de.sentoon.touchtesterv4.MainActivity}: android.view.InflateException: Binary XML file line #20: Binary XML file line #20: Error inflating class de.sentoon.touchtesterv4.DrawingView
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2788)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1503)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6209)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               Caused by: android.view.InflateException: Binary XML file line #20: Binary XML file line #20: Error inflating class de.sentoon.touchtesterv4.DrawingView
               Caused by: android.view.InflateException: Binary XML file line #20: Error inflating class de.sentoon.touchtesterv4.DrawingView
               Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]
                  at java.lang.Class.getConstructor0(Class.java:2204)
                  at java.lang.Class.getConstructor(Class.java:1683)
                  at android.view.LayoutInflater.createView(LayoutInflater.java:618)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:288)
                  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                  at de.sentoon.touchtesterv4.MainActivity.onCreate(MainActivity.java:27)
                  at android.app.Activity.performCreate(Activity.java:6745)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2788)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1503)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6209)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Thanks for helping.

A:

Caused by: java.lang.NoSuchMethodException:  [class android.content.Context, interface android.util.AttributeSet]

You have not declared enough constructors.
Normally custom view shoud have at least 2 constructors. One accepts Context, the other Context and AttributeSet.
public class DravingView extends View {
    public DravingView(final Context context) {
        super(context);
    }

    public DravingView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }
}

Why do I need that constructor?
First the xml is being parsed, and then the appropriate class object is being created. After parsing the layout xml file, framework would try to create DrawingView object for you with applied parameters in xml. Those parameters are being passed through AttributeSet. But as long as it cannot find such a constructor in DrawingView class, it crashes.


Q:

XPath results to empty string

Following is my XML file
<xyzevent xmlns="http://www.xyz.com/common/xyzevent/v1" xmlns:xsi="http://www.w3.org2001XMLSchema-instance">
<header>
 ----
</header>
<subscription xmlns="http://www.xyz.com/common/xyzevent/source/v1">
  <sender></sender>
  <receiver>
    <clientsubscription>
        <servicemap>nanna</servicemap>
    </clientsubscription>
  </receiver>
</subscription>
</xyzevent>

When I budila org.w3c.dom.Document from this XML and applying XPathExperssion with expression
/xyzevent/subscription/receiver/clientsubscription/servicemap/text()

results empty string. What can be the issue with the expression?
Thank you

A:

That's because your XML document uses a namespace. XPath is really annoying with namespaces. To confirm this, strip the two xmlns=http://.../v1 from the document and run your XPath expression agains the unnamespaced, unverifiable XML file. It'll match.
What's happening is that your XPath expression tries to select /xyzevent, when your document contains {http://.../v1}:xyzevent, which is not the same thing.
There are various ways around this problem. The proper way is to set up a NamespaceContext so you can use the prefix:localName notation in your XPath expression and have the prefixes be resolved to the correct URI. There's a short blurb about this in the xerces docs and some more  elsewhere on StackOverflow. There's an extensive description at ibm.com.
Your NamespaceContext will contain two (or more) mappings:
{
    event => http://www.xyz.com/common/xyzevent/v1
    source => http://www.xyz.com/common/xyzevent/source/v1
}

Your XPath expression can then become /event:xyzevent/source:subscription/source:receiver/.../text().
As a nasty workaround, you can rewrite your xpath expression to select using the local-name() function:
/*[local-name()='xyzevent']/*[local-name()='subscription'/ ...

In this case, the expression matches any element whose local name is xyzevent, regardless of namespace URI.


Q:

Python, compare and calculate data in lists

I am trying to calculate the attendance in 3 courses.
The raw data in an Excel spreadsheet looks like this (“1” means attended, “0” means no):

What’s needed is to calculate:
In those who attended Course A, how many of them (%) attended Course B, and attended Course C.
In those who attended Course B, how many of them (%) attended Course A, and attended Course C.
In those who attended Course C, how many of them (%) attended Course A, and attended Course B.
The results I have from the codes are here.
They mean:
In those attended Course A, 100% attended Course A, 50% attended Course B, and 75% attended Course C.
In those attended Course B, 67% attended Course A, 100% attended Course B, and 100% attended Course C.
In those attended Course C, 75% attended Course A, 75% attended Course B, and 100% attended Course C.
Project A to Project A@100%
Project B to Project A@50%
Project C to Project A@75%
 -  -  -  -  -  -  -  -  -
Project A to Project B@67%
Project B to Project B@100%
Project C to Project B@100%
 -  -  -  -  -  -  -  -  -
Project A to Project C@75%
Project B to Project C@75%
Project C to Project C@100%

As you can see, the clumsy codes running isn’t very smart. And if the number of courses (columns) increased largely, for example to 100 columns, manual add-on is a tedious job.
What’s the smart way to do such calculations? Thank you.
from xlrd import open_workbook,cellname
import xlwt, xlrd
from xlutils.copy import copy
from xlwt import Workbook,easyxf,Formula

workbook = xlrd.open_workbook("C:\\Sheet1.xls")
old_sheet = workbook.sheet_by_index(0)

B1 = old_sheet.cell(0, 1).value
C1 = old_sheet.cell(0, 2).value
D1 = old_sheet.cell(0, 3).value

sum_of_Column_B = []
sum_of_Column_C = []
sum_of_Column_D = []

Column_B_B = []
Column_B_C = []
Column_B_D = []

Column_C_B = []
Column_C_C = []
Column_C_D = []

Column_D_B = []
Column_D_C = []
Column_D_D = []

for row_index in range(1, old_sheet.nrows):
#     Column_A = old_sheet.cell(row_index, 0).value
    Column_B = old_sheet.cell(row_index, 1).value
    Column_C = old_sheet.cell(row_index, 2).value
    Column_D = old_sheet.cell(row_index, 3).value

    sum_of_Column_B.append(int(Column_B))
    sum_of_Column_C.append(int(Column_C))
    sum_of_Column_D.append(int(Column_D))

# Paragraph 1
    if Column_B == 1 and Column_B == 1:
        Column_B_B.append(1)
    if Column_B == 1 and Column_C == 1:
        Column_B_C.append(1)
    if Column_B == 1 and Column_D == 1:
        Column_B_D.append(1)

# Paragraph 2
    if Column_C == 1 and Column_B == 1:
        Column_C_B.append(1)
    if Column_C == 1 and Column_C == 1:
        Column_C_C.append(1)
    if Column_C == 1 and Column_D == 1:
        Column_C_D.append(1)

# Paragraph 3
    if Column_D == 1 and Column_B == 1:
        Column_D_B.append(1)
    if Column_D == 1 and Column_C == 1:
        Column_D_C.append(1)
    if Column_D == 1 and Column_D == 1:
        Column_D_D.append(1)

# Paragraph 1
B_over_B = float(sum(Column_B_B)) / float(sum(sum_of_Column_B))
C_over_B = float(sum(Column_B_C)) / float(sum(sum_of_Column_B))
D_over_B = float(sum(Column_B_D)) / float(sum(sum_of_Column_B))

# Paragraph 2
B_over_C = float(sum(Column_C_B)) / float(sum(sum_of_Column_C))
C_over_C = float(sum(Column_C_C)) / float(sum(sum_of_Column_C))
D_over_C = float(sum(Column_C_D)) / float(sum(sum_of_Column_C))

# Paragraph 3
B_over_D = float(sum(Column_D_B)) / float(sum(sum_of_Column_D))
C_over_D = float(sum(Column_D_C)) / float(sum(sum_of_Column_D))
D_over_D = float(sum(Column_D_D)) / float(sum(sum_of_Column_D))

# Paragraph 1
print B1 + " to " + B1 + " + {0:.0f}%".format(B_over_B * 100)
print C1 + " to " + B1 + " + {0:.0f}%".format(C_over_B * 100)
print D1 + " to " + B1 + " + {0:.0f}%".format(D_over_B * 100)

# Paragraph 2
print " - " * 20
print B1 + " to " + C1 + " + {0:.0f}%".format(B_over_C * 100)
print C1 + " to " + C1 + " + {0:.0f}%".format(C_over_C * 100)
print D1 + " to " + C1 + " + {0:.0f}%".format(D_over_C * 100)

# Paragraph 3
print " - " * 20

print B1 + " to " + D1 + " + {0:.0f}%".format(B_over_D * 100)
print C1 + " to " + D1 + " + {0:.0f}%".format(C_over_D * 100)
print D1 + " to " + D1 + " + {0:.0f}%".format(D_over_D * 100)

A:

Dummy data
import pandas as pd
import itertools
import numpy as np

names = [f'student {i}' for i in range(1, 8)]
courses = [f'course {i}' for i in 'ABC']
df = pd.DataFrame(data = np.random.randint(0, 2, size=(len(names),len(courses))), index = names, columns=courses)

in reality
df = pd.read_excel(filename)
courses = df.columns

You might need to tweak some of the arguments, especially index_col and header

df

    course A    course B    course C
student 1   0   0   1
student 2   1   1   0
student 3   1   0   0
student 4   0   1   0
student 5   1   0   1
student 6   1   0   1
student 7   1   0   1

Comparison
results = pd.DataFrame(columns=courses, index=courses)
for i, j in itertools.product(courses, repeat=2):
    attended = df[df[i] == 1]
    results.loc[i, j] = sum(attended[i] & attended[j]) / len(attended)

results

    course A    course B    course C
course A    1   0.2     0.6
course B    0.5     1   0
course C    0.75    0   1

So 75% of those that attended course C attended course A


Q:

Click handler doesn't work in template-expanding directive

My application has a custom template-expanding directive which is used to create several section-toggle elements.  The section-toggle elements represent buttons that the user clicks to toggle the display of one of several section elements on the page.

Toggle Section 1

Toggle Section 2

Toggle Section 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Mauris dignissim vehicula risus ac vestibulum.

Vivamus congue risus at tortor varius egestas.

My controller scope has a property called shownSection (a string that represents which section to show on the page) and a function called toggleSection(), which sets the value of shownSection to whatever value is present in the toggle attribute of the section-toggler element.
app.controller("NavCtrl", function ($scope) {
    $scope.shownSection = 'section1';
    $scope.toggleSection = function(section) {
        $scope.shownSection = section;
    };
});

app.directive('sectionToggler', function() {
    return {
        restrict: 'E',
        scope: false,
        link: function(scope, element, attrs) {
            element.bind("click", function(){
                scope.toggleSection(attrs["toggle"]);
            });
        }
    }
});

The problem I'm having is that the directive doesn't appear to change the controller's $scope.shownSection value, which would in turn show and hide the individual sections.
I thought that the scope = false in the directive definition object would force the directive to use NavCtrl's scope, and that attrs("toggle") would get the value of the section-toggler's toggle attribute.
To no avail, I have tried using this.attr("toggle") and element.attr("toggle") in place of attrs["toggle"] (none of which work), and I've tried changing $scope.shownSection = section in the controller to shownSection = section.
Here's a JSFiddle.

A:

Clicking on the section togglers do in fact change $scope.shownSection. You can verify this by adding console.log($scope.shownSection) at the bottom of the $scope.toggleSection function.
The problem is that bind (as in element.bind("click") is a jqLite/jQuery function which does not trigger Angular's digest loop. It's when the digest loop runs that Angular will update the UI to reflect the updated model values.
To trigger it manually you can for example use $apply:
element.bind("click", function () {
  scope.$apply(function () {
    scope.toggleSection(attrs["toggle"]);
  });
});

Demo: http://jsfiddle.net/qdhau2zb/6/


Q:

How to fix Prestashop Fatal error: Uncaught --> Smarty Compiler?

Fatal error: Uncaught --> Smarty Compiler: Syntax error in template "/home/sites/riversoft.com.mk/public_html/admin397ebpwvj/themes/default/template/header.tpl" on line 256 "headers: {"cache-control": "no-cache"}," - Unexpected ": ", expected one of: "}" <-- thrown in /home/sites/riversoft.com.mk/public_html/tools/smarty/sysplugins/smarty_internal_templatecompilerbase.php on line 256

A:

In the /home/sites/riversoft.com.mk/public_html/admin397ebpwvj/themes/default/template/header.tpl either remove headers: {"cache-control": "no-cache"} or enclose it in {literal} like this:
{literal}headers: {"cache-control": "no-cache"}{/literal}


Q:

There seems to be some disagreement about the "Minecraft" and "Pocket Minecraft" tags

Someone's just gone through and added the minecraft tag to all the minecraft-pocket-edition
Seems like someone previously went through and removed all of those tags.
Thought I should bring this to meta's attention.

A:

I have reverted all the retagging done by this user.  The serial upvoting script should catch his expanded privileges (he got super upvoted just a short while ago), and reverse the upvotes, thereby removing his ability to retag questions.
I spent some time while I was at reviewing and fixing some of the questions, too, so they should be a bit neater.
Still definitely not something that should be done, but the end result is (slightly) higher quality content.


Q:

Where should I ask users which layout they prefer?

I am designing a chart, and I have a few layout options that I'm considering.
I want to ask some people which they believe would be more beneficial to the users. I feel like this would be constructive, because I'm looking for answers with justifiable responses, not a discussion. That is, I'm looking for an answer like

I think you should choose option A, because it would be more valuable to see only the newest data, rather than having to page through old data to find what I'm looking for.

Where should I ask this question?

A:

Really it sounds like you need something like Usaura, a simple online usability testing solution where you can present many sort of tests, including simple A/B "which layout do you prefer" tests.
User Experience can help you design specific, constructive design questions, but we're neither a user testing site nor a critique site. We do have plenty of questions that can help you learn how to conduct (formal or informal) usability testing and user research.


Q:

Formatting the code en-masse in Visual Studio

I've inherited a project where all the private variables, and there are thousands, are separated by a blank line.  For instance,
    private pnlSecurityReport _pnlSecurityReport = null;

    private pnlCalendar _pnlCalendar = null;

    private CtlContacts _pnlContacts = null;

    private pnlEmails _pnlEmails = null;

    private CtlNotes _pnlNotes = null;

    private pnlRoles _pnlRoles = null;

    private pnlSecurity _pnlSecurity = null;

    private pnlSignatures _pnlSignatures = null;

This is really annoying. I'd like to remove the blank lines. Beyond writing my own tool to seek out and remove the extra line, is there a way to do this, perhaps, using RegEx-Fu in the Search and Replace dialog?

A:

Try replacing \n\n with \n, with Use Regular Expressions checked.

A:

Not very thoroughly tested, but something like this could work: open the Replace dialog, check "Regular Expressions", enter {^:b*:w+:b+:i:b+:i:b+=:b+.*;$\n}\n into the "Find" text box, and \1 in the "Replace with" text box.
In short; match lines that matches the pattern word identifier identifier = value; followed by a blank line, tag all of the match except the last newline and then replace the full match with the tagged expression.
This will have the upside of not blindly removing all blank lines from the file, but only those that follow after typical field- or variable declarations combined with value assignments.
Expression breakdown:
{    - Start of tagged expression
^    - Match beginning of line
:b*  - Zero or more whitespace characters (such as space or tab)
:w+  - One or more alphabetic characters
:b+  - One or more whitespace characters
:i   - An identifier string
:b+  - One or more whitespace characters
:i   - An identifier string
:b+  - One or more whitespace characters
=    - an equal sign
:b+  - One or more whitespace characters
.+   - One or more characters of any kind
;    - a semicolon
$    - end of the line
\n   - a newline
}    - end of tagged expression
\n   - a newline


Q:

Are generalized descriptions of suspects considered lawfully admissable?

My question mainly pertains to descriptions law enforcement receives from individuals reporting a crime.
My example would be as follows:
Officer John receives complaint of irate black male with short hair wearing a white T-shirt and Jeans. He responds, but the person in question is no longer located at said location. He then spots an individual within a few thousand feet of said location. The state in which he is currently in does not require to show ID so long as no crimes have been committed. The black male refuses to show his ID card because he has been mistaken for someone else, making the argument that he has done nothing wrong.
The officer then explains that he must provide ID because his description fits what the officer was told and that he is within direct proximity of the area. Again the individual refuses and claims "Racial profiling". By reasoning of Vague and generalized interpretation of appearance.
He claims that many black individuals wear white T-shirts and jeans.
This in and of itself is not a false statement. Does the officer have the right to arrest this individual? Perhaps even detain him at the least for simply fitting a description with such a vague amount of information?

A:

In your example, there is nothing that indicates to me that there is a  "particularized and objective basis for suspecting the particular person stopped of . . . criminal activity".
If you have described the totalilty of the circumstances, the officer does not have the right to arrest or detain the individual.
To your broader question about how specific descriptions must be in order to provide a basis for a stop, the assessment is based on the "totality of the circumstances". For example, an anonymous tip that "a woman would drive from a particular apartment building to a particular motel in a brown Plymouth station wagon with a broken right tail light [carrying cocaine]" was enough to warrant a stop. Alabama v. White, 496 U.S. 325 (1990)1
In contrast, the court "determined that no reasonable suspicion arose from a bare-bones tip that a young black male in a plaid shirt standing at a bus stop was carrying a gun." Florida v. J. L., 529 U. S. 266 (2000)
The “reasonable suspicion” necessary to justify such a stop “is dependent upon both the content of information possessed by police and its degree of reliability.” Navarette v. California
572 U.S. ___ (2014)
In any case, a crime must be part of the particularized suspicion.
1. This case focused on the indicia of reliability necessary for an anonymous tip to support a reasonable suspicion, but it is also an example of a degree of non-specificity in identification of a suspect.


Q:

Hibernate beginner - Duplicate import

I am following the tutorials from pluralsight - introduction to hibernate and encountered errors when persisting my object.
I have re-watch several times the videos and I have followed every step correctly, but i could not figure out where the issue was.
Can anyone advise what have I done incorrectly?
Note: I downloaded hibernate 4.3.5 and copy hibernate-release-4.3.5.Final\lib\required to the \lib folder of my eclipse project.
Error:
Aug 02, 2014 10:49:03 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Aug 02, 2014 10:49:03 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
Aug 02, 2014 10:49:03 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 02, 2014 10:49:03 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Aug 02, 2014 10:49:04 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/simpleprogrammer/User.hbm.xml
Aug 02, 2014 10:49:04 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Aug 02, 2014 10:49:04 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/simpleprogrammer/User.hbm.xml
Aug 02, 2014 10:49:04 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Aug 02, 2014 10:49:04 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Aug 02, 2014 10:49:04 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/]
Aug 02, 2014 10:49:04 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=appuser, password=****}
Aug 02, 2014 10:49:04 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Aug 02, 2014 10:49:04 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Aug 02, 2014 10:49:04 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration$MappingsImpl addImport
INFO: HHH000071: Duplicate import: com.simpleprogrammer.User -> com.simpleprogrammer.User
Aug 02, 2014 10:49:04 PM org.hibernate.cfg.Configuration$MappingsImpl addImport
INFO: HHH000071: Duplicate import: com.simpleprogrammer.User -> User
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/simpleprogrammer/User.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.simpleprogrammer.HibernateUtilities.<clinit>(HibernateUtilities.java:22)
    at com.simpleprogrammer.Program.main(Program.java:9)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/simpleprogrammer/User.hbm.xml
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3762)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXmlQueue(Configuration.java:3751)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3739)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
    at com.simpleprogrammer.HibernateUtilities.<clinit>(HibernateUtilities.java:17)
    ... 1 more
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.simpleprogrammer.User
    at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2835)
    at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:178)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3759)
    ... 6 more

My mapping file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 2, 2014 9:15:11 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.simpleprogrammer.User" table="USERS">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="total" type="int">
            <column name="TOTAL" />
        </property>
        <property name="goal" type="int">
            <column name="GOAL" />
        </property>
    </class>
</hibernate-mapping>

My configuration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/</property>
  <property name="hibernate.connection.username">appuser</property>
  <property name="hibernate.default_schema">protein_tracker</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.show_sql">true</property>
  <mapping resource="com/simpleprogrammer/User.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

My POJO
package com.simpleprogrammer;

public class User {

    private int id;
    private String name;
    private int total;
    private int goal;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }
    public int getGoal() {
        return goal;
    }
    public void setGoal(int goal) {
        this.goal = goal;
    }
}

My main class:
package com.simpleprogrammer;

import org.hibernate.Session;

public class Program {

    public static void main(String[] args) {

        Session session = HibernateUtilities.getSessionFactory().openSession();
        session.beginTransaction();

        User user = new User();
        user.setName("Joe");
        user.setGoal(250);
        session.save(user);

        session.getTransaction().commit();
        session.close();

        System.out.println("Hello World");
        HibernateUtilities.getSessionFactory().close();
    }

}

A:

Resolved.
package com.simpleprogrammer;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtilities {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration().configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

I used the incorrect method to get the SessionFactory


Q:

MSSQL - Rows as Columns

I have following Table:
+------+--------------+------------+--------+
|  ID  |    TestID    | QuestionId | Answer |
+------+--------------+------------+--------+
|   1  |      10      |     15     |    0   |
|   2  |      10      |     23     |    0   |
|   3  |      10      |     41     |    1   |
|   4  |      16      |     15     |    0   |
|   5  |      16      |     23     |    1   |
|   6  |      16      |     41     |    1   |
|   7  |      24      |     15     |    1   |
|   8  |      24      |     23     |    0   |
|   9  |      24      |     41     |    0   |
+------+--------------+------------+--------+

For internal reports I need following output:
+--------------+----------------+----------------+----------------+
|  QuestionId  |      Test_1    |      Test_2    |      Test_3    |
+--------------+----------------+----------------+----------------+
|      15      |        0       |        0       |        1       |
|      23      |        0       |        1       |        0       |
|      41      |        1       |        1       |        0       |
+--------------+----------------+----------------+----------------+

I have no idea how to do this.
Do you have any suggestions?

A:

Use Pivot
;WITH CTE
AS
(
    SELECT
        SeqNo = ROW_NUMBER() OVER(PARTITION BY QuestionId ORDER BY TestId),

        *
        FROM YourTable
)
SELECT
    QuestionId,
    Test_1 = MAX([1]),
    Test_2 = MAX([2]),
    Test_3 = MAX([3])
    FROM CTE
    PIVOT
    (
        SUM(Answer)
        FOR SeqNo in
        (
            [1],[2],[3]
        )
    )P
    GROUP BY QuestionId

My Result