Q:

Compare DateTime with 24 hours

``I have a method to retrieve DateTime from MS Acesss. I want to allow a client to cancel his booking up to 24 hours prior to the date. How can I code this using if else statement?
this is my method.
    public static string Date(int c)
    {
        string a;
        OleDbConnection myconn = DBConn();
        string myQ = "SELECT DateTime FROM Booking WHERE movie_ID=" + c;
        OleDbCommand myCmd = new OleDbCommand(myQ, myconn);
        try
        {
            myconn.Open();

            a = myCmd.ExecuteScalar().ToString();

            return a;

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in DBHandler", ex);
            return null;
        }
        finally
        {
            myconn.Close();
        }
    }

How to code if else statement like
       string d = db.date(id);
       DateTime n = Convert.toDateTime(d);
       if ( n <= 24 hours???){
       do.this....
      }

A:

make a method like this
public static bool canCancel(string date)
{
    DateTime booking = Convert.ToDateTime(date);
    DateTime ending = booking.AddHours(23).AddMinutes(59).AddSeconds(59);

    var n = DateTime.Compare(ending, DateTime.Now);
    if(n == -1)
    {
       // within 24 hour from booking
       // so can not cancel
       return false;
    }
    else
    {
       // greater than 24 hour
       // so can cancel
       return true;
    }

}

then call it
public static string Date(int c)
    {
        string a;
        OleDbConnection myconn = DBConn();
        string myQ = "SELECT DateTime FROM Booking WHERE movie_ID=" + c;
        OleDbCommand myCmd = new OleDbCommand(myQ, myconn);
        try
        {
            myconn.Open();

            a = myCmd.ExecuteScalar().ToString();

            var can_cancel = canCancel(a);
            return a;

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in DBHandler", ex);
            return null;
        }
        finally
        {
            myconn.Close();
        }
    }


Q:

Load Parse.File url into EJS template

I'm trying to rendering out an html template using EJS, Express and Parse.com. Basically whenever I try to reference a Parse.Files url() call from within my EJS template it errors and nothing gets returned. These images are hosted on Parses cloud, not in the public directory.

        <% reviews.forEach(function(review,index) { %>

<img class="profile-img" src="<%= review.get('createdBy').get('pictureThumbnail').url() %>" width="35" height="35"/>Test

        <% }) %>

I've run a console.log() on review.get('createdBy').get('pictureThumbnail').url() and I get back a simple url string. But if I put it in the template I get nothing.
I've tried using <%- <%= <%, but nothing seems to work.

A:

So, the issue was that I wasn't checking to make sure that the file actually existed and there were two items that had no images associated with them, this was causing the whole thing to error, but since I wasn't getting an error in the terminal I really had no idea what was happening.
So lesson learned, always make sure you are checking for empty objects in EJS.


Q:

getting an amazon ec2 instance similar (in terms of performance) to my desktop PC

I am a bit puzzled by the performance of amazon ec2 instances.
Specifically, I would like to know whether I can obtain an amazon EC2 windows instance that is close to my current desktop pc.
My desktop pc has 36 gb RAM (1600 mhz), i7 3770K and a fast SSD drive (kingston hyperX).
My computational needs are simple: I use a lot of statistical programs (such as R or Stata) which essentially
1) read the data from the hard disk
2) store the data in the RAM
3) perform computations (most of which can take advantage of up to 4 cores)
What do you think? Can I get an equal or greater performance?
Any help is greatly appreciated!

A:

You can check the AWS EC2 Instance Types Matrix.

CPU: They use Intel Xeon, should be better than your desktop i7 cpu. Also the vCPU number could be up to 32.
RAM: Memory could be up to 32G.
SSD: Mostly SSD. You could even add extra SSD storage.

It's likely to gain better performance than your desktop pc if using
Compute Optimized instance type c3.4xlarge or higher.


Q:

How to split a cell of many numbers by group of 3-3 in each next cells?

As above image I have a column which consists many numbers separated by comma. I need to split those numbers by group of 3-3 in each next cell.

A:

So, brutal but does work:
=LEFT(A1,FIND(",",A1,FIND(",",A1,FIND(",",A1,1)+1)+1)-1)

You can play with MID() and RIGHT() to get others....
See


Q:

Extra form fields not bound to model in angularjs

How can I retrieve a form value in the controller, when the specific field is no field of the model?
<form name="userForm" ng-submit="updateUser()">
       //fields of model
       <input type="text" name="firstname" ng-model="user.first_name" required/>

       //not bound to model
       <input type="password" name="password"/>
       <input type="password" name="password_confirmation"/>
 </form>

In the controller:
 console.log($scope.password);

returns undefined. Is it possible to get the passwords without modifing the user resource?

A:

You can just add ng-model="password", it'll get added to the scope but not $scope.user:
<input type="password" name="password" ng-model="password" />
<input type="password" name="password_confirmation" ng-model="password_confirmation" />


Q:

Copy all output jars with dependencies into one folder

I've got a parent POM.xml defining 4 modules, 3 of which reference the first one (this project to be precise).
I am trying to copy all output jars with their runtime dependencies into one folder using the following commands:
mvn package
mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.1:copy-dependencies
-DoutputDirectory=deps -DincludeScope=runtime
-DexcludeGroupIds=com.acadiasoft.im

The first command succeeds and the last fails with the error:

[ERROR] Failed to execute goal on project simm: Could not resolve dependencies for project com.acadiasoft.im:simm:jar:1.0.0-SNAPSHOT: Could not find artifact com.acadiasoft.im:base:jar:1.0.0-SNAPSHOT -> [Help 1]

Note the last parameter -DexcludeGroupIds=com.acadiasoft.im which is how I tried working around this error. I also tried excludeArtifactIds to the same effect.
Question 1: Why doesn't it work? Why is it not skipping artefacts with group id com.acadiasoft.im?
Question 2: Is there a way to make maven 'see' the the jars produced in the mvn package step and copy them over along with their dependencies?
Version info:

Maven 3.6.1
JDK 1.8

Please note that I would prefer a command line based solution rather than having to modify a POM. Thanks.

A:

working spell is
mvn clean install
mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.1:copy-dependencies -DoutputDirectory=deps -DincludeScope=runtime -DexcludeGroupIds=com.acadiasoft.im

note package -> install


Q:

Create Connected object in GraphQL via Mutation

What is the best practice to create an object via mutation connected to another object.
Using the following schema:
type Question @model {
  id: ID!
  text: String!
  answers: [Answer] @connection(name: "QuestionAnswers")
}
type Answer @model {
  id: ID!
  text: String!
  question: Question @connection(name: "QuestionAnswers")
}

The following (and variants of it) fail:
mutation CreateAnswer {
  createAnswer(input: {
    text:"Yes",
    question: {
      id: "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8"
    }
  })
    {
        id
    }
  }

Serverside code:
mutation CreateAnswer($input: CreateAnswerInput!) {
  createAnswer(input: $input) {
    id
    text
    question {
      id
      text
      answers {
        nextToken
      }
    }
  }
}

With the above, receiving the following error:

"Validation error of type WrongType: argument 'input' with value
  'ObjectValue{objectFields=[ObjectField{name='text',
  value=StringValue{value='3'}}, ObjectField{name='question',
  value=ObjectValue{objectFields=[ObjectField{name='id',
  value=StringValue{value='9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8'}}]}}]}'
  contains a field not in 'CreateAnswerInput': 'question' @
  'createAnswer'"

A:

Seems that this may be a naming convention in AppSync. The below worked for me:
mutation createAnswer {
  createAnswer (input: {
    text: "5"
    answerQuestionId: "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8"
  }) {
    id
  }

Adding answer to QuestionId was what was needed.


Q:

Why was my edit rejected again?

I'd like to know why my original edit was rejected again even though I asked to give sometime to the OA (original answerer) to review it:
Was there anything factually wrong in my edit? It added a link, formatted, and expanded a few sentences. I misunderstand why it was rejected but I further misunderstand why my request that the OA would review it itself was denied (or the OA did?, I don't know how to ensure that because I can't see edit history for this rejected edit here).

A:

I just rejected your 2nd attempt about the edit you suggested. I did so with reason attempt to reply, of which these are some details of it:

It should have been written as a comment or an answer.

If you really want to get your corrections/additions included, then I strongly recommend you to post an additional answer in which you mention how it complements and/or corrects the existing answer. It is that easy ... As a bonus, your answer may even get upvoted ...

A:

It was rejected because the users who reviewed the suggested edit thought it was changing the meaning of the answer.
Effectively, the suggested edit added that Drush 9 is Composer-centralized, while it's simply suggested not to install Drush 9 globally (which is possible also with Composer).
It also introduce a grammar error, in the following sentence. (Emphasis on the wrongly changed part is mine.)

A composer based Drupal project is installed by composer create-project drupal-composer/drupal-project includes Drush 9 locally by default and this is the only recommend way to use Drush 9.

The correct sentence is the original one.

A composer based Drupal installed by composer create-project drupal-composer/drupal-project includes Drush 9 locally by default and this is the only recommend way to use Drush 9, see https://github.com/drupal-composer/drupal-project.

Inlining a link, or editing it to show its title is fine; rewriting a sentence to make it clearer is fine, but adding a sentence the poster didn't put (and containing a not correct assertion) isn't fine.


Q:

Reverse Each Specific Line in a String

I am attempting to reverse my lines within a text file using the recursion method. I am pretty stuck right now and my current output is a Segmentation Error- Can someone explain what the segmentation error is from and push me in the right direction?
void RecursionLine();
int main (int argc, char argv)
{
  RecursionLine();
  printf("\n");
}

void RecursionLine()
{
  int c;
if((c = getchar()) != EOF || (c != '\n'))
    {
      RecursionLine();
      printf("%c",c);
    }
 else if((c = getchar()) != EOF && (c == '\n')){
      printf("\n");
      RecursionLine();
}
}

Input:
Dogs
Cats
Boys
Output
sgoD
staC
syoB

A:

You are getting a Segmentation error because you have an || condition in your first if statement, where one of those conditions will always be true, causing your stack to overflow from infinite recursion! Change this to an && and it should be all fixed!
if((c = getchar()) != EOF && (c != '\n'))

EDIT: Additionally I believe you are going to run into some improper functionality due to the second getchar(). I would change your function to:
void RecursionLine()
{
  int c = getchar();
if(c != EOF || c != '\n')
    {
      RecursionLine();
      printf("%c",c);
    }
 else if(c != EOF && c == '\n'){
      printf("\n");
      RecursionLine();
}
}

Otherwise you are going to read in potentially 2 characters every iteration and that is going to cause one/both of them to be skipped!


Q:

How to access Membership/roles through silverlight

I have a silverlight control on my asp.net mvc page, need to communicate with a webservice where i need to send the current role of the user logged into the system with. But how do I access the "Roles.GetRolesForUser()" from within my silverlight application?

A:

http://blogs.msdn.com/brada/archive/2008/05/03/accessing-the-asp-net-authentication-profile-and-role-service-in-silverlight.aspx
I hope that helps you out.


Q:

MS Access: How to filter report on non-report field?

I haven't worked with Access in 8 years -- I believe I've forgotten more than I ever knew. Someone asked me to modify a report so that a list of drawings, which currently displays all drawings, will list drawings for a specific customer (or for all customers).
I located the nested queries used by the report, and I modified the inner query to accept a parameter (first mistake?). Then I added a new form to display the customer name and retrieve the associated primary key, customerId. Now I need to feed the customer ID from the form to the report. DoCmd.OpenReport and adding a whereCmd doesn't seem to match up the where condition with the parameter.
So, I removed the parameter in the query, and tried just specifying the condition. Only the outer query doesn't know what a customerId is. Do I need to expose this in the inner query, and in the outer query, then just not use it in the final report just so I can filter it in the where clause?
They have other sample code that uses VBA in the form to rebuild a query (adding in whatever criteria for filtering) before launching the report. Surely this can't be the recommended practice, can it?

A:

Include the filter field in the report's record source.  Then you can filter on that field when you open the report.
DoCmd.OpenReport "rptFoo", View:=acViewPreview, _
    WhereCondition:="[id]=1"

The record source field used in the WhereCondition does not have to be displayed by any of the report's controls ... as long as it's present in the record source it can be used in the WhereCondition.


Q:

Button fires on double not single click

I got view animations to work perfectly in Xcode (slide off the screen on a button click with CGRect.) Unfortunately I have to click the button twice to execute the animation. What have I done wrong? I appreciate any feedback
Here's my .H code
@interface AnimationBlocksViewController : UIViewController{
    IBOutlet UIView *theview;
    IBOutlet UIView *theview2;

    BOOL isAnimated;
    BOOL switchback;
}

-(IBAction)animate:(id)sender;
-(IBAction)change:(id)sender;

Here's my .M code
-(IBAction)animate:(id)sender;{
    if (isAnimated) {

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        [UIView setAnimationDuration:0.5];
        [theview setFrame:CGRectMake(0, 0, 320, 460)];
        [theview2 setFrame:CGRectMake(320, 0, 320, 460)];
        [UIView commitAnimations];
        isAnimated=NO;

    }

    else{

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        [UIView setAnimationDuration:0.5];
        [theview setFrame:CGRectMake(-320, 0, 320, 460)];
        [theview2 setFrame:CGRectMake(0, 0, 320, 460)];
        [UIView commitAnimations];
        isAnimated=YES;

    }
}

-(IBAction)change:(id)sender;{
    if (switchback) {

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        [UIView setAnimationDuration:0.5];
        [theview2 setFrame:CGRectMake(0, 0, 320, 460)];
        [UIView commitAnimations];
        switchback=NO;

    }

    else{

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        [UIView setAnimationDuration:0.5];
        [theview2 setFrame:CGRectMake(320, 0, 320, 460)];
        [theview setFrame:CGRectMake(0, 0, 320, 460)];
        [UIView commitAnimations];
        switchback=YES;

    }
}

It works but I have to double click to trigger the animation, what have I done wrong?
Thank you

A:

After your initial double click, does a subsequent single click trigger the animation properly? If so, it may be that you haven't explicitly initialised your BOOL variables, though they should default to NO. Try doing that and see if it helps.
If you always need to do two taps to animate, maybe try inserting a call to the run loop to see if it's only processing the animation after running on your application thread for a while i.e. it could be that only when it comes to process a second click event does it actually go and fetch any pending animations and execute them. The code for that would be (after you set isAnimated and call commitAnimations):
[[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate date]];

Not sure whether you can just use nil for a date but try that too if you like.


Q:

Include all codeigniter functions to a new static page(php file) which is located in root folder

I am developing a website which having many static pages. so i created controller only for dynamic pages(it might be wrong practice). Keeping all other static files in root folder. Now i want to use base_url() function from codeigniter for the static pages which is located in root folder. But i am not sure im am doing good practice or not. so ** Please give me a solution to manage many static page in codeigniter. **

A:

you can create a controller with name Static_page send all your static pages requests to this controller
Static controller
class Static_Page extends CI_Controller{

    function index(){
       $page = $this->uri->segment(1,'default_static_page');
       if (!file_exists(APPPATH."views/{$page}.php"))
         {
           show_404();
         }
       $this->load->view($page);
   }

}

save all your static pages as views with same name as uri you will call like if you call http://your-site.com/about-us your view will be about-us.php, http://your-site.com/contact your view will be contact.php


Q:

Rust Inspect Iterator: cannot borrow `*` as immutable because it is also borrowed as mutable

Why can't I push to this vector during inspect and do contains on it during skip_while?
I've implemented my own iterator for my own struct Chain like this:
struct Chain {
    n: u32,
}

impl Chain {
    fn new(start: u32) -> Chain {
        Chain { n: start }
    }
}

impl Iterator for Chain {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        self.n = digit_factorial_sum(self.n);
        Some(self.n)
    }
}

Now what I'd like to do it take while the iterator is producing unique values. So I'm inspect-ing the chain and pushing to a vector and then checking it in a take_while scope:
let mut v = Vec::with_capacity(terms);
Chain::new(i)
    .inspect(|&x| {
        v.push(x)
    })
    .skip_while(|&x| {
        return v.contains(&x);
    })

However, the Rust compile spits out this error:
error: cannot borrow `v` as immutable because it is also borrowed as mutable [E0502]
...
borrow occurs due to use of `v` in closure
    return v.contains(&x);
           ^
previous borrow of `v` occurs here due to use in closure; the mutable borrow prevents subsequent moves, borrows, or modification of `v` until the borrow ends
    .inspect(|&x| {
        v.push(x)
    })

Obviously I don't understand the concept of "borrowing". What am I doing wrong?

A:

The problem here is that you're attempting to create both a mutable and an immutable reference to the same variable, which is a violation of Rust borrowing rules. And rustc actually does say this to you very clearly.
let mut v = Vec::with_capacity(terms);
Chain::new(i)
    .inspect(|&x| {
        v.push(x)
    })
    .skip_while(|&x| {
        return v.contains(&x);
    })

Here you're trying to use v in two closures, first in inspect() argument, second in skip_while() argument. Non-move closures capture their environment by reference, so the environment of the first closure contains &mut v, and that of the second closure contains &v. Closures are created in the same expression, so even if it was guaranteed that inspect() ran and dropped the borrow before skip_while() (which I is not the actual case, because these are iterator adapters and they won't be run at all until the iterator is consumed), due to lexical borrowing rules this is prohibited.
Unfortunately, this is one of those examples when the borrow checker is overly strict. What you can do is to use RefCell, which allows mutation through a shared reference but introduces some run-time cost:
use std::cell::RefCell;

let mut v = RefCell::new(Vec::with_capacity(terms));
Chain::new(i)
    .inspect(|x| v.borrow_mut().push(*x))
    .skip_while(|x| v.borrow().contains(x))

I think it may be possible to avoid runtime penalty of RefCell and use UnsafeCell instead, because when the iterator is consumed, these closures will only run one after another, not at the same time, so there should never be a mutable and an immutable references outstanding at the same time. It could look like this:
use std::cell::UnsafeCell;

let mut v = UnsafeCell::new(Vec::with_capacity(terms));
Chain::new(i)
    .inspect(|x| unsafe { (&mut *v.get()).push(*x) })
    .skip_while(|x| unsafe { (&*v.get()).contains(x) })

But I may be wrong, and anyway, the overhead of RefCell is not that high unless this code is running in a really tight loop, so you should only use UnsafeCell as a last resort, only when nothing else works, and exercise extreme caution when working with it.


Q:

Form processing issue while generating a dynamic form and preparing via API calls directly

How can I fix the processing and submission of forms that I am preparing and rendering dynamically via API calls.
function drupal_set_confirmation($message, array $options, array $escape=array(), $type='warning', $details=NULL){
    $form = array();

    $form['title'] = array(
    '#markup' => '<h3>' . t($message) . '</h3>'
    );

    if (!empty($details)) {
        switch(gettype($details))   {
            case 'string':
                $form['details'] = array(
                    '#markup' => $details,
                );
            break;
            case 'array':
                $form['details'] = $details;
            break;
        }
    }

    if (!empty($options)) {
        $form['options'] = array(
            '#type' => 'container',
            '#attributes' => array('class' => array('user-confirmation-options')),
        );

        foreach($options as $key => $option) {
            $form['options'][$key] = array(
                '#submit' => array($option['callback']),
                '#type' => 'submit',
                '#value' => $option['title'],
                '#attributes' => $option['attributes'],
            );
        }

        if (!empty($escape)) {
            $form['options']['escape'] = array(
                '#markup' => l($escape['title'], $escape['path']),
            );
        } else {
            $form['options']['escape'] = array(
                '#markup' => l(t('Cancel'), current_path()),
            );
        }
    }

    $form_state = form_state_defaults();
    $form_id = 'form_user_confirmation';

    drupal_prepare_form($form_id, $form, $form_state);
    // I do not see any reason to call drupal_process_form while serving the form.
    //drupal_process_form($form_id, $form, $form_state);
    $rendered_form = drupal_render($form);
    return drupal_set_message($rendered_form, $type);
}

And it works greatly to show a dialog form of my own choice by calling.
drupal_set_confirmation(t('Do you really want to suicide?'), array(
        'okay' => array(
        'callback' => '_yes_kill_me',
        'title' => t('Yes'),
        'attributes' => array('class' => array('button', 'tiny')),
    ),
    ), array(
        'title' => t('No'),
        'path' => current_path(),
    ));

And callback function as #submit handler for a particular element is not invoked.
How can I fix the form processing and submission issue using this approach to work?

A:

I fixed it this way, it started to invoke form submit handlers.
function MODULE_init() {
    if (!empty($_POST) && $_POST['form_id'] == 'form_user_confirmation') {
        $form_state = form_state_defaults();
        $form_id = 'form_user_confirmation';
        drupal_build_form($form_id, $form_state);
    }
}


Q:

JPQL having with exists

I want to find all buckets where at least one transaction is REJECTED but not all. Ideally i would like as result a Map with key=bucket_id and value=ids in a single query.
id | bucket_id | status
1  | 1         | 'AVAILABLE'
2  | 1         | 'AVAILABLE'
3  | 1         | 'REJECTED'
4  | 2         | 'REJECTED'
5  | 2         | 'REJECTED'
6  | 2         | 'REJECTED'

My current not working query :
SELECT distinct t.bucket_id, t.id
FROM Transaction t
GROUP BY t.bucket_id, t.id
HAVING
EXISTS (select t.id FROM t WHERE t.status=REJECTED)
AND
EXISTS (select t.id FROM t WHERE t.status<>REJECTED)

As result of this query i get both buckets 1 and 2.
How can i express the condition: "at least one rejected but not all " in the HAVING clause ?

A:

First have to remove t.id, otherwise distinct wouldnt work
Second use T2 in the inner select so you can compare bucket_id.
And you dont need GROUP BY or HAVING use WHERE instead
Now if you need id you have to join this query with another one. Do you want first id, last id?

SQL FIDDLE DEMO
SELECT distinct t.bucket_id
FROM transac t
WHERE
    EXISTS (SELECT T2.id
            FROM transac T2
            WHERE
                T2.status='REJECTED'
            AND T2.bucket_id = t.bucket_id)
AND EXISTS (SELECT T2.id
            FROM transac T2
            WHERE
                T2.status<>'REJECTED'
            AND T2.bucket_id = t.bucket_id)

EDIT
If status only have 2 posible values this is another solution much simpler. Meaning Exists another transac with diferent status to the one you are looking.
SELECT distinct t.bucket_id
FROM transac t
WHERE
    EXISTS (SELECT T2.id
            FROM transac T2
            WHERE
                T2.status <> t.status
            AND T2.bucket_id = t.bucket_id)


Q:

How to store formed command line without running it in bash or terminal?

For example, I have formed a long complicated command that will improve the world and lower an entropy in the Universe. But then (huh!) I see that I forgot to make a dir required. I want to store my command, run mkdir and then restore my command.
Assume doing it in a raw tty.
Is there a way to do so?

A:

On your command-line press Ctrl-u (it stores it in the  kill-ring), issue the other one mkdir for example, and then press Ctrl-y.


Q:

A question regarding SATB (4 part) harmonization

I'm working through examples in my Harmony 9 book from the RCM Celebration series and I stumbled across a SATB harmony question that I am unsure of.

the red is what is given, you have to choose the chords to use and complete the SATB voicing. So far we've only been introduced to root position chords I, IV, V and V7.
If anyone has tips and corrections please let me know

A:

There is one "really bad" mistake. If you are only using chords in root position, you can't harmonize 5 4 in the soprano with V iv, because you have parallel octaves between soprano and bass. You will have to repeat the i chord in the third bar from the end.
The first bar is a bit clumsy, but it's hard to see how to improve it if you are so restricted in your choice of chords. The tenors aren't going to thank you for making them start singing a part that sound like it starts in C# major (C# E# C# C#) while the rest of the choir is putting them off by singing in a different key!
A smoother sounding version would have the first inversion of V on the second beat with E# in the bass, but you said you aren't allowed to write that yet!


Q:

Why does my code generate a figure whose kurtosis looks a little higher than the one I am trying to reproduce?

this figure (fig_1) is an univariate normal distribution in 3D, the corresponding equation is in the top left hand corner

it seems that x varies from -5 to 5; sigma varies from 0 to 4.
This Python code is trying to reproduce this figure
ax = plt.figure().gca(projection='3d')
xx, yy = np.meshgrid(np.arange(-5,5,.1), np.arange(0.1,4,.1))
zz = norm.pdf(xx,0,yy)
ax.plot_surface(xx, yy, zz, alpha=.5)

and I got this figure

and this guy
zz = norm.pdf(xx,0,np.sqrt(yy))

gives this figure

which is better although the kurtosis looks a little higher than fig_1.
any clue

A:

The value 's' in the original graph is the variance, which is the square of the Gaussian sigma (i.e. the scale parameter of the normal distribution). So norm.pdf(xx,0,np.sqrt(yy)) should be correct.
Note that the shape of the peak you see is very much dependent on the y value where the graph starts. Your starting point of 0.1 may be a little smaller than in the original graph, which looks like it starts at about 1/6 ~= 0.167, so you may see a narrower and taller peak for that reason. Also, the original graph doesn't quite have enough horizontal resolution to resolve the shape of the peak entirely, as you can see from how far apart the grid lines are spaced vertically on the sides of the peak.


Q:

Limit as $r$ tends to zero of integral $\int_C \frac{e^{iz}-1}z \mathrm dz$

Let $\mathcal C$ be a semi-circle of center $O(0,0)$ and radius $R$, such that $y \ge 0$. Find the limit as $R$ tends to zero of:
$$\int_{\mathcal C} \frac{e^{iz}-1}z \mathrm dz$$
How can I find this?

A:

Note that
$$\bigl|e^{iz}-1\bigr|=2\left|\sin{z\over2}\right|\ .$$It follows that
$$\left|\int_{\cal C}{e^{iz}-1\over z}\>dz\right|\leq\int_{\cal C}\left|{\sin(z/2)\over z/2}\right|\>|dz|\ .$$
As $\lim_{z\to0}{\sin z\over z}=1$ and ${\rm length}({\cal C})\to0$ when $R\to 0+$ the right hand side tends to $0$ when $R\to 0+$.


Q:

AVCaptureScreenInput and kCGWindowListOptionOnScreenBelowWindow

I am doing screen capture with AVCaptureScreenInput. The app has a window with configuration options.
I want to record the screen but not record the window in the recorder application. Quicktime does this if you do a screen recording, as an example.
I think I found what will do it, but I'm not sure how or if they can be used together.
kCGWindowListOptionOnScreenBelowWindow is found in CGWindow.h in the Core Graphics framework. AVCaptureScreenInput is part of AVCaptureInput.h in the AVFoundation framework.
If you are taking a single screenshot, you can pass kCGWindowListOptionOnScreenBelowWindow and a windowID so that only windows below that window's level are captured. I can accomplish my goal by setting the capture app's window to a very high level if this works.
I'm relatively new to Objective-c ands its not clear to me if its possible to use the kCGWindowListOptionOnScreenBelowWindow with AVCaptureScreenInput. If it is, could someone provide tips on what the resulting code needs to look like?
How to access the pixel buffer of an NSWindow in OSX?

A:

As far as I know, there is no way to exclude specific windows from OS X's built-in display recording APIs:

AVFoundation's AVCaptureScreenInput  (10.7+)
Core Graphics CGDisplayStream (10.8+)

Both above methods seem to grab the screen content after compositing, when the final screen output has already been composited together.
So excluding your recording window would require you to use an API that allows you to composite the windows yourself and later append those custom frames to an AVAssetWriterInput.
Quartz Window Services allow you to take snapshots of single windows via CGWindowListCreateImage.  A good sample project that also shows how to composite multiple window shots together is Son of Grab.
After retrieving the stitched together shot, you'd have to append it to an AVAssetWriterInput. AVFoundation provides a convenience class to append custom pixel buffers to a movie: AVAssetWriterInputPixelBufferAdaptor.
Especially the AVFoundation part could become very frustrating and you might run into performance problems as the compositing is very likely to be slower than OS X's built-in compositor, but overall it should be possible to to achieve what you want.


Q:

How to use goto to break a nested loop

How can I use a "goto" statement to break out of a loop
for(i = 0; (i < 9); i++)
    {
        for(j = 0; j < 9; j++)
        {
            //cout << " " << Matrix[i][j];
            //cout << "i: " << i << endl;
            if(Matrix[i][j] == 0)
            {
                //temp = 10;
                [goto] ;
                //break;
            }
        }
    }

I wanted to keep the values at which i and j were when I left the nested for loop. How can I use a goto statement for that?

A:

Like this:
int i,j;
for(i = 0; i < 9; i++)
{
    for(j = 0; j < 9; j++)
    {
        //cout << " " << Matrix[i][j];
        //cout << "i: " << i << endl;
        if(Matrix[i][j] == 0)
        {
            //temp = 10;
            goto end;
            //break;
        }
    }
}
end:
cout << i << " " << j << endl;

A:

Just as you use goto in any other situation. As long as you don't cross scopes with local variables in them, you can actually think of it as "goto this and that line":
for (/* ... */) {
  /* ... */
  if (/* ... */)
    goto finalise;
}
finalise:
  foo = bar; //...

However, there are many situations when goto is an indicator for not well designed code. By no means always, but often.
I suggest you use gotos big brother return and factor out your code into a function:
inline std::pair<int,int> findZeroEntry(std::vector matrix) {
  for (int i = 0; i < 9; i++)
    for (int j = 0; j < 9; j++)
      if (Matrix[i][j] == 0)
        return std::make_pair(i,j);
  return std::make_pair(9,9); // error
}


Q:

Laravel: ErrorException guraded vs fillable

Laravel:

ErrorException in Model.php line 2336: in_array() expects parameter 2
  to be array, string given

class Student extends Model
{
protected $guarded = 'student_id';

//protected $fillable = ['full_name',  'current_grade','branch'];
}

should I use  fillable ? because when I use guarded alone its throwing this error

A:

You need to pass in an array even when you only have one item in guarded.
protected $guarded = ['student_id'];


Q:

How to produce an array from a function in r?

X and Y are distributed as poisson RV's with lambda 10 and 20 respectively. I need to create a function sample() that generates n realisations of (X, Y)  and produces an nx2 array.
So far I have done:
sample=function()
{
  X=rpois(1,10)
  Y=rpois(1,20)
}

How do I then produce an array?

A:

fred_sample <- function(n){
  X <- rpois(n, 10)
  Y <- rpois(n, 20)
  matrix(c(X, Y), n)
}

A few points:

I'd avoid naming your function sample or you will end up masking the base function named sample.
You need to pass n to sample if you want it to generate an n by 2 array.


Q:

Mock same method with different return value called twice in a function in python

I have a method to be tested using pytest. The method is calling same database model twice.
 def function:
    ids = database_model.object.filter(user="user1").filter(group="admin").values_list(ids, flat=True).allow_filtering()
    response_list = []
    unquie_ids = list(set(ids))
    for ids in unique_ids:
        response = database_model.object.filter(ids=ids).limit(1)
        for res in response:
            temp_dict = {}
            temp_dict['name'] = res.name
            temp_dict['description'] = res.description
            response_list.append(temp_dict)
   return response_list

This works well. I am tring to write unit test case for this.
As the same database_model requires return value twice. It does not work for me.
  @patch('database_model')
  def test_function(mock_model):
      mock_model.objects.filter.return_value.filter.return_value.values_list.return_value.allow_filtering_return_value = [Mock_id]
      mock_model.objects.filter.limit.return_value = mock_dict

      response = function()

      assert len(response) > 0

mock_id and mock_dict are values created for test case.
My question is first time i am assigning a return_value to mock_model.objects.filter.return_value.filter.return_value.values_list.return_value.allow_filtering.return_value to [Mock_id] which gets assigned properly. But the next line i am trying to assign a return_value again to the same method. This takes as a magic mock object. So my test case fails because it is getting a empty list. I would like to know how can i assign two different return_values to the same method.

A:

You should write a side_effect for database_model.object.filter mock that gives you a Mock() configured to return the correct ids list after a mock to use in for cycle.
mock_filter_get_ids = Mock()
mock_filter_ids = Mock()
mock_model.objects.filter.side_effect = [mock_filter_get_ids, mock_filter_ids]
mock_filter_get_ids.filter.return_value.values_list.return_value.allow_filtering_return_value = [Mock_id]
mock_filter_ids.limit.return_value = mock_dict

But...
Forget it: refactor your code, at least extract:
database_model.object.filter(user="user1").filter(group="admin").values_list(ids, flat=True).allow_filtering()

In something like get_user_ids() and
database_model.object.filter(ids=ids).limit(1)

in get_ids_response().
You can mock the new methods and make your code simpler to read, simple to test means simple to read almost every time.


Q:

Alternative method for proxy_owner in ActiveRecord

ActiveRecord proxy_owner is now deprecated and the explanation here is very vague on how to change it, so I'm not sure how to use it my case:
 http://apidock.com/rails/ActiveRecord/Associations/AssociationProxy
Here is what I'm trying to do:
class Library < ActiveRecord::Base
  has_many :books do
    def some_method
      proxy_owner.author
    end
  end
end

I get a warning when I run this code that proxy_owner is deprecated:
DEPRECATION WARNING: Calling record.books.proxy_owner is deprecated. Please use record.association(:books).owner instead.

I can replace proxy_owner.author with:
@associaton.owner.author

This works; however, it seems dangerous. Am I missing something here?

A:

I think it's safer to send :owner to proxy_association instead:
class Library < ActiveRecord::Base
  has_many :books do
    def some_method
      proxy_association.owner.author
    end
  end
end

The use of proxy_association is now mentioned in the documentation:

However, inside the actual extension code, you will not have access to
  the record (record.association(:items).owner) as above. In this case, you can access proxy_association.
  For example, record.association(:items) and
  record.items.proxy_association will return the same object, allowing
  you to make calls like proxy_association.owner inside association
  extensions.


Q:

How do I split a text string in a Windows batch file?

Sometimes I have both a Real Name and an Author Name as a folder in this format as follows:
Real Name - as Author Name
Other times I have only an Author Name as a folder in this format as follows:
Author Name
I want to strip out the Real Name and the " - as " in cases where a real name exists and set the Author Name only to a variable, or set the Author Name only to that variable when only an author name exists as follows: AN=%something%
Here is my futile attempt:
SETLOCAL ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
FOR %%# IN (.) DO (SET CF=%%~f#
      SET NAME1=%%~nx#)
      SET $=%NAME1: - as =$%
for /f "tokens=1* delims=%$%" %%a in ("%NAME1%") do (
      SET part1=%%a
      SET AN=%%b
)

echo AN = %AN%
ENDLOCAL

Can someone please help me strip out the Author Name only and set it to a variable? Thanks in advance.

A:

Your code with

putting ) on a separate line,
using NAME1 instead of $ on left side of equal sign on line substituting  - as  by character $,
defining the delimiters for second FOR loop correct with $,
adding two more lines to work also for folder names not containing real name

is as follows:
@echo off
SETLOCAL ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
FOR %%# IN (.) DO (
    SET "CF=%%~f#"
    SET "NAME1=%%~nx#"
)
SET "AN="
SET "NAME1=%NAME1: - as =$%"
FOR /F "tokens=1* delims=$" %%I in ("%NAME1%") do (
    SET "part1=%%I
    SET "AN=%%J"
)
IF NOT DEFINED AN SET "AN=%NAME1%"
ECHO AN = %AN%
ENDLOCAL

By the way: It would be better to use | instead of $ two times in code above because it is impossible that a folder name contains the vertical bar character while it is possible that a folder name contains dollar sign although not very likely.

Another solution using a subroutine which can be called for each subdirectory in current directory by replacing
for %%# in (.) do call :GetNames "%%~nx#"

for example by
for /D %%# in (*) do call :GetNames "%%~nx#"

in the commented code below:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Run subroutine GetNames with name of current directory without path.
for %%# in (.) do call :GetNames "%%~nx#"

endlocal
goto :EOF

:GetNames
set "FolderName=%~1"

rem Get the string after " - as " which is the author name.
set "AuthorName=%FolderName:* - as =%"

rem If the author name is identical to folder name, then there
rem is not string " - as " included in folder name which means
rem the folder name is the author name.
if "%AuthorName%" == "%FolderName%" (
    set "RealName="
    goto OutputNames
)

rem Use delayed expansion to remove author name from folder
rem name to get real name in addition to author name.
setlocal EnableDelayedExpansion
set "RealName=!FolderName:- as %AuthorName%=!"
endlocal & set "RealName=%RealName%"

:OutputNames
echo Folder name: %~1
echo Real name: %RealName%
echo Author name: %AuthorName%
goto :EOF

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?
echo /?
endlocal /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?


Q:

Serverless scheduled, detect cron

I'd like to run a function via both HTTP and cron, but not seeing any documentation that let's me determine if it was an http request or cron request (explicitly):
    events:
      - http:
          path: /foo
          method: ANY
          cors:
            origin: '*'
      - schedule: rate(5 minute)

Is there a property in event or context that would allow me to detect what triggered the function?

A:

You can always pass an input to your schedule event and use that to determine that's a schedule event
events:
  - http:
      path: /foo
      method: ANY
      cors:
        origin: '*'
  - schedule:
      rate: rate(5 minute)
      input:
          isSchedule: true

There's more examples here: https://serverless.com/framework/docs/providers/aws/events/schedule/
EDIT:
Forgot about this
{
    "version": "0",
    "id": "53dc4d37-cffa-4f76-80c9-8b7d4a4d2eaa",
    "detail-type": "Scheduled Event",
    "source": "aws.events",
    "account": "123456789012",
    "time": "2015-10-08T16:53:06Z",
    "region": "us-east-1",
    "resources": [
        "arn:aws:events:us-east-1:123456789012:rule/my-scheduled-rule"
    ],
    "detail": {}
}

you can also check detail-type field
https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/RunLambdaSchedule.html


Q:

Get the Image Path from Json and assign to variable

Before I put the Image path in variable as below :
script
$(document).ready(function()
{
 var output = "http://sitename.com/images/oneheart.png";
 //some other code
});

Now I need to get the Image path from Json file , so i tried as below :
Both Json & html file are in same path....
Json :
{
  "path" : " shape\/",
  "info" : {
    "author" : ""
  },
  "name" : "shape",
  "layers" : [
    {
      "height" : 612,
      "layers" : [
        {
          "name" : "bg_rectangle_1"
        },
        {
          "height" : 475,
          "layers" : [
            {

              "src" : "http://sitename.com/images/oneheart.png",
              "name" : "mask_image_1"
            },
            {
              "name" : "useradd_ellipse1"
            }
          ],
          "name" : "user_image_1"
        }
      ],
      "name" : "loveshape_17"
    }
  ]
}

script :
$(document).ready(function() {

    $.getJSON('oneheart.json', function(data) // Get data from JSON file
        {
            var json = $.parseJSON(data);
            for (var i = 0; i < json.layers.length; i++) {
                var output += json.layers[i].src; // Place image in variable
            }
        });
    // Some other code
});

Here is Full Json file in pastebin & Full code in codepen

A:

Update your code as below, it should work.
$(document).ready(function() {
var output= "";
var mask1;
//Shubham Chaudhary code

$.getJSON('./oneheart.json', function(json){
  for(let layer of json.layers){
    if(layer.layers && layer.layers.length > 0){
      for(let temp of layer.layers){
        if(temp.src) output = temp.src;
        else if (temp.layers){
          for(let tl of temp.layers)
             if(tl.src) output = tl.src;
        }
      }
    }
  }

      mask1 = $(".container").mask({
        maskImageUrl: output,
        onMaskImageCreate: function(img) {
            img.css({
                "position": "fixed",
                "left": 73,
                "top": 1
          });
        }
    });
});
}); // end of document ready


Q:

How to input to date format from a number

I'm trying to put a number eg 20141001 into a date9. format eg 01OCT14.
I've tried to use the input function with an input format of yymmddn8. but SAS throws out 'informat could not be found or loaded'
Any ideas how to get around this? (Sample code below)
data _null_;
  date=20141001;
  output=input(date,yymmddn8.);
  format output date9.;
  put output=;
run;

A:

You are almost there.  Although there is a YYMMDDN format there is not an informat of the same name.  Use the YYMMDD informat. The Input function is expecting a character string i.e. the DATE variable. Redefine DATE as a character variable e.g.
data _null_;
  date='20141001';
  output=input(date,yymmdd8.);
  format output date9.;
  put output=;
run;

Alternatively you could have used these assignments:
output = input('20141001',yymmdd8.);

or
output = '01oct2014'd;


Q:

Wamp Server : Path of uploaded files

Hi I have a WAMP server where some files are upload into an specific path.

C:\wamp\www\upload\

in this case. However could it be possible to upload these files into for example

D:\Documents\User\upload ?

Upload.php specifies the path where the files are stored but I haven´t the way of changing to another path.
Thanks in advance,
Katherine
Edit: upload.php
Here is the upload_file.php
<?php
$target_path  = "c:\\";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
 echo "El fichero ".  basename( $_FILES['uploadedfile']['name'])." ha sido enviado";
} else{
 echo "Hubo un error, inténtalo de nuevo!";
}
?>

A:

Katherine,
In WAMP, Apache is setup ( as it should be for security reasons ) so that Apache will not allow access to the root folder of the C:\
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    **Deny from all**
</Directory>

This stops hackers that successfully break into your site from being allowed to cause REALLY SERIOUS DAMAGE.
So I would expect to see an error message in either your Apache error log or your Php error log. I would also expect to see and error on the screen from XDEBUG unless you have disabled that feature. Maybe you should re-enable it as these error messages are really useful while you are developing!!!
change php.ini
display_errors = On
Now it is possible to open up specific folders outside the normal website folder structure like this
This is an excerpt from the httpd.ini without all the comments
<Directory "d:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
#   onlineoffline tag - don't remove
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1

    </Directory>
    Alias /my_other_upload_folder_alias "c:/some_other/folder/my_other_upload_folder"
    <Directory "c:/some_other/folder/my_other_upload_folder">
        AllowOverride All
        Order Deny,Allow
        Deny from All
        Allow from 127.0.0.1
    </Directory>
</Directory>

You then use 'my_other_upload_folder_alias' as the folder name in your php code.
PS. You look like you are placing your site into c:\wamp\www  this is a bad idea!
Create subfolders for your sites like this
c:\wamp\www\site1
c:\wamp\www\site2

And think about create one virtualHost per site.


Q:

Bash : Poll for a file creation and terminate if exits

I'm trying to write a script that traps a exit signal and terminate. Instead of using the usual bash trap method, I would like to monitor a file creation every 10 seconds and cleanup some stuff before termination.
Here is what I have tried:
poll_time=10 // poll every 10 seconds
((term_time=$SECONDS+240)) // monitor until 4 min from current script time exec

while (( $SECONDS < $term_time)) do
    if [[ -r $some_path/file.txt ]]; then
        cleanup_function
        exit
fi
sleep ${poll_time}
done

//if file doesnt exit continue with below code
//blah blah blah ....

Is there a better way to do this? will above lines of code work?

A:

inotifywait from inotify-tools is what you need (to look at at least). Line like this will do the same trick your script is intended to do:
inotifywait -e create --timeout 240 "${some_path}/file.txt" && { cleanup_function; exit ; }

with the difference inotifywait works in event-based manner, so no polling or sleeping required.


Q:

Modify / Edit an Event on Facebook possible?

I don't see any documentation referring to the ability to edit events through the api, but I was just wondering if that's due to lack of documentation or if this is actually unavailable.
Many Thanks

A:

There is ample documentation on editing events:

Old REST API: http://developers.facebook.com/docs/reference/rest/events.edit
Graph API: http://developers.facebook.com/docs/reference/api/event

Note that "The application must be an admin of the event".


Q:

How to return a result from Meteor.call method in client?

I'm calling a server method from my client side code via the Meteor.call() function.
But I get an undefined value when I try to pass the callback function's return value to a var within the onCreated function.
Looking at this solution the result is still only available within the scope of the callback:
https://stackoverflow.com/a/31661065/1829251
Also when I read the docs for Meteor-call it explains that the method is async which explains that the return value of the function can't be assigned to a variable:
https://docs.meteor.com/api/methods.html#Meteor-call
Question:
How can you return a result from Meteor.call method in client?
Code snippet of client side code:
import { Template } from 'meteor/templating';
import { Meteor } from 'meteor/meteor';
import { Datasets } from '../../../../api/datasets/datasets.js';
import { Constants } from '../../../../startup/constants.js';

import './rollup-history.html';
import './rollup-history.scss';

Template.rollup_history.onCreated(function() {

  this.historyDays = 7;

  this.rollupHistoryMECTitles = () => {

    let mecObjects = [];

    // Query the MEC calendar dates from AppConfiguration collection
    let method = Constants.Methods.getAppConfigCollectionFromKeyDateSorted;
    mecObjects = Meteor.call(method, Constants.AppConfigKeys.meccalendarInitialValues, this.historyDays, (error, result) => {
          if(error){
            console.log("Error retrieving MEC Dates" + error);
          }

          //Logging values here shows the values as expected
          console.log("MEC Dates in View" + JSON.stringify(result));
          return result;
      }
    );

    //logging value here shows undefined value
    console.log("mec objects: " + JSON.stringify(mecObjects));

    return mecObjects;

  };

});

Template.rollup_history.helpers({

  mecHeaderColumns: function() {

    return Template.instance().rollupHistoryMECTitles();
  },

});

A:

Because the return statement is in the callback and is unblock you can't return a method value like that. you can put it https://github.com/stubailo/meteor-reactive-method which will return the value but it must live inside a helper or reactive environment.


Q:

Direct proof of the level four eta identity

Of Somos' over 6200 eta identities, the one of smallest level (maybe the simplest?) is the eta identity of level $4$ $$\eta(z)^{16} \eta(4z)^8 + 16 \eta(4z)^{16} \eta(z)^8 = \eta(2z)^{24}.$$
As with all identities among modular forms, we can prove it by checking the first few coefficients. I wonder if it is possible to give a "real" proof of this straight from the product $$\eta(z) = q^{1/24} \prod_{n=1}^{\infty} (1 - q^n)$$ in the style of this answer. The higher exponents in this problem seem to make it harder to use Jacobi's triple product.

A:

Consider the product representations of the Jacobi Thetanulls
(as functions of the period ratio $\tau$):
$$\begin{align}
    \varTheta_{00}(\tau)
    &= \frac{\eta(\tau)^5}{\eta\left(\frac{\tau}{2}\right)^2\eta(2\tau)^2}
&   \varTheta_{01}(\tau)
    &= \frac{\eta\left(\frac{\tau}{2}\right)^2}{\eta(\tau)}
&   \varTheta_{10}(\tau)
    &= \frac{2\eta(2\tau)^2}{\eta(\tau)}
\end{align}$$
and plug these into Jacobi's Vierergleichung
$$\varTheta_{00}^4 = \varTheta_{01}^4 + \varTheta_{10}^4$$
This results in
$$\frac{\eta(\tau)^{20}}{\eta\left(\frac{\tau}{2}\right)^8\eta(2\tau)^8}
= \frac{\eta\left(\frac{\tau}{2}\right)^8}{\eta(\tau)^4}
+ \frac{16\,\eta(2\tau)^8}{\eta(\tau)^4}$$
Multiplying out the denominators and setting $\tau=2z$
then results in the identity you asked about.

One way of proving the Vierergleichung works by first deducing
the period-doubling/-halving relations
$$\begin{align}
 \varTheta_{00}(\tau)^2
 &= \varTheta_{00}(2\tau)^2+\varTheta_{10}(2\tau)^2
& \varTheta_{00}(2\tau)^2
 &= \frac{1}{2}
 \left(\varTheta_{00}(\tau)^2+\varTheta_{01}(\tau)^2\right)
\\ \varTheta_{01}(\tau)^2
 &= \varTheta_{00}(2\tau)^2-\varTheta_{10}(2\tau)^2
& \varTheta_{01}(2\tau)^2
 &= \varTheta_{00}(\tau)\,\varTheta_{01}(\tau)
\\ \varTheta_{10}(\tau)^2
 &= 2\,\varTheta_{00}(2\tau)\,\varTheta_{10}(2\tau)
& \varTheta_{10}(2\tau)^2
 &= \frac{1}{2}
 \left(\varTheta_{00}(\tau)^2-\varTheta_{01}(\tau)^2\right)
\end{align}$$
The middle left equation has been deduced in my answer to the question you
referenced.
The upper left then follows from replacing $\tau$ by $\tau+1$.
Addition/subtraction reveals the upper and lower right identities.
The middle right identity easily follows from its left neighbor
once you plug in
$$\begin{align}
    \varTheta_{00}(\tau)
 &= \varTheta_{00}(4\tau)+\varTheta_{10}(4\tau)
\\  \varTheta_{01}(\tau)
 &= \varTheta_{00}(4\tau)-\varTheta_{10}(4\tau)
\end{align}$$
which is just a splitting of $q$-series into odd and even terms.
Finally, plugging in the above two even/odd-splitting equations in the
lower right identity yields the lower left identity.
Anyway, once you have established the above set of identities, you can deduce
$$\begin{align}
    \varTheta_{10}(\tau)^4
 &= 4\,\varTheta_{00}(2\tau)^2\,\varTheta_{10}(2\tau)^2
\\ &= \left(\varTheta_{00}(\tau)^2+\varTheta_{01}(\tau)^2\right)
 \left(\varTheta_{00}(\tau)^2-\varTheta_{01}(\tau)^2\right)
\\ &= \varTheta_{00}(\tau)^4-\varTheta_{01}(\tau)^4
\end{align}$$
which is the Vierergleichung.


Q:

Fazer teste sem "sujar" (adicionar dados) o banco de dados

Estou tendo problema em fazer teste de integração. Testo minhas funções de banco de dados. Minha aplicação web não utiliza nenhum framework de conexão de banco de dados e não estou conseguindo fazer testes sem sujar o meu banco de dados.
Queria saber como fazer testes sem que eu insira dados no banco de dados e altere as informações da minha aplicação. Qual funções e classes devo utilizar?
Só estou achando soluções para hibernate.

A:

Você deve utilizar um database para produção e um outro para os seus testes. Coloque o nome do database em questão a ser utilizado em um arquivo de configuração, de forma a ter um arquivo de configuração para a sua base de produção e um para os seus testes. Também é possível colocar no arquivo de configuração, a URL do banco de dados, driver utilizado, nome de usuário, senha, etc.
Feito isso, antes de você iniciar os seus testes, você invoca algum método que seja responsável por criar ou limpar a base de dados (você pode utilizar as anotações @Before ou @BeforeClass caso esteja usando o JUnit 4 ou @BeforeEach ou @BeforeAll caso esteja usando o JUnit 5). Para isso, basta rodar algum script contendo todas as instruções DROP TABLE necessárias para se destruir qualquer banco de dados anterior existente e em seguida rodar o conjunto de instruções CREATE TABLE, ALTER TABLE, INSERT e UPDATE necessárias para se recriar e repopular a base de dados. Você também pode optar por usar um banco de dados em memória para os testes, o que melhora o desempenho e simplifica o processo de recriação deles. Entretanto, essas abordagens podem introduzir alguns problemas:

As diferenças entre o banco de dados em arquivos físicos e em memória podem comprometer os testes.
Caso utilize um banco de dados físico para os testes, o processo de destruir e recriar o banco de dados pode ser bastante oneroso (pode ser oneroso até mesmo em alguns casos com banco de dados em memória).

Por conta desse problemas, convém que você tente utilizar o banco de dados sujo entre um teste e outro se possível (apenas não use nunca o banco de dados de produção), limpando o banco de dados existente antes do primeiro teste e utilizando-o até o último. Por outro lado, esse procedimento de reutilizar o banco de dados sujo também tem o seu problema:

A independência e isolamento entre os seus testes pode ficar comprometida, fazendo com que um teste possa interferir no outro.

Essa perda de isolamento é o preço a se pagar para não ter os testes tão onerosos em termos de desempenho. E portanto, se for utilizada, deve ser feita com cuidado e de forma planejada, para não acabar por comprometer a qualidade dos testes.
Assim sendo, para garantir o melhor equilíbrio entre desempenho, independência dos testes e fidelidade com o banco de dados físico, convém você separar os testes em categorias. Aqueles que podem ser rodados em memória e aqueles que precisam do banco de dados em arquivos físicos. Aqueles que podem rodar em bases sujas por testes anteriores e aqueles que precisam da base zerada. Fica mais fácil de se lidar com todos esses diferentes casos ao utilizar-se múltiplas bases de testes distintas.


Q:

Checking user input with scanner

I am trying to implement a simulator that has certain commands the user can input.
One of these commands is "s" which when entered should step through one instruction of the assembly file. However there is another instruction with the format "s num" where the user can define just how many instructions they want to step through.
I check for this
    if(input.equals("s"))
    {
        //check for num next
        if(user.hasNextInt())
        {
            input = user.next();
            step(Integer.parseInt(input), assembler);
        }
        else
        {
            step(1, assembler);
        }
    }

However the problem is if the user only enters "s" the scanner will wait for the next input rather than just calling step. My idea is if there is an int after the s was input then proceed with the num step, other wise just call step.
Any help is greatly appreciated!

A:

I would split the input into two parts and then treat it. For example,
String input = user.nextLine();
String array[] = input.split(" ");
if(array.length<2){
    //check for `s`
}else{
    //check for `s num`
}


Q:

python subprocess never stops when called with -i argument

I'm writing a python script that calls another python script (script2).  I want to get the print statements from script2 during the process, not only at the end.  I have this code:
command = ['python', '-i', script2]
process = subprocess.Popen(command,
                       stderr=subprocess.STDOUT,
                       stdout = subprocess.PIPE)

print "process started"

while process.poll() is None:
    line = process.stdout.readline()
    if not line:
        break
    print line

This code does indeed print the output to the screen, but the subprocess never ends.
However, changing command to command = ['python', script2] ends the subprocess, but only prints the output to the screen AFTER the subprocess ended.
How can I get the desired behaviour?  Thanks on beforehand,
Roel

A:

Try invoking your subprocess with -u (and do not use -i). This will stop its output from being buffered. You don't see any output until it ends because it writes all its output into a buffer, which isn't flushed until it either fills up or the process finishes.


Q:

Webdriver logs for Firefox

Both Chrome and PhantomJS selenium drivers can log everything that is going on the browser side. By specifying the service log path while initializing the driver, you can control where the logs would be written to. E.g. for chrome (in Python):
from selenium import webdriver

driver = webdriver.Chrome(service_log_path="/tmp/log")
driver.get("http://www.google.com")
driver.close()

After executing the code, /tmp/log file would contain the service logs which is helpful for debugging:
[0.985][INFO]: Launching chrome: ...
[2.620][INFO]: RESPONSE InitSession {
   "acceptSslCerts": true,
   "applicationCacheEnabled": false,
   "browserConnectionEnabled": false,
   "browserName": "chrome",
   "chrome": {
      "userDataDir": "/var/folders/yy/ppdg927x4zv8b0rbzg1f_jzh0000gn/T/.org.chromium.Chromium.ibsof9"
   },
   "cssSelectorsEnabled": true,
   "databaseEnabled": false,
   "handlesAlerts": true,
   "javascriptEnabled": true,
   "locationContextEnabled": true,
   "nativeEvents": true,
   "platform": "Mac OS X",
   "rotatable": false,
   "takesHeapSnapshot": true,
   "takesScreenshot": true,
   "version": "37.0.2062.120",
   "webStorageEnabled": true
}
[2.677][INFO]: Waiting for pending navigations...
[2.696][INFO]: Done waiting for pending navigations
[3.290][INFO]: Waiting for pending navigations...
[4.338][INFO]: Done waiting for pending navigations
[4.338][INFO]: RESPONSE Navigate
[4.339][INFO]: COMMAND CloseWindow {

}
[4.451][INFO]: RESPONSE CloseWindow

Is there a way to get the same information but using Firefox web driver?
From what I see in the source code, both Chrome and PhantomJS fire up new services via subprocess and pass the --log-path argument to it. And these services are responsible for the logging. As for Firefox driver, it's implementation is quite different and is based on FirefoxBinary class.
Provided example and links are Python-related, but the question is pretty much generic and language-agnostic. Would appreciate any pointers.

A:

You have to set logging options in firefox profile as in developer tips link - https://code.google.com/p/selenium/wiki/DeveloperTips - for console log you should use:
FirefoxProfile p = new FirefoxProfile();
p.setPreference("webdriver.log.file", "/tmp/firefox_console");
WebDriver driver = new FirefoxDriver(p);

For browser log, you should use
webdriver.firefox.logfile

(https://code.google.com/p/selenium/wiki/FirefoxDriver)
Hope this helps.


Q:

Update a DataGridView column value in C#

I have created a grid with 6 columns all are of type string now my requirement is when the user double clicks on the 6th column a new form will open and return the value from the selected record in id, name variables.
It is opening the form and getting the values but when executing the following line
grdItemDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = id;

it is not updating the field give the error and close how to update the value for this column please help. The full code is as follows.
private void grdItemDetail_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
        if (e.ColumnIndex == 6)
        {
            frmWarehouseList frmWarehouseList = new frmWarehouseList();
            frmWarehouseList.ShowDialog();
            string id = frmWarehouseList.SelectedWarehouseID;
            string name = frmWarehouseList.SelectedWarehouseName;
            //MessageBox.Show(grdItemDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            grdItemDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = id;
        }

A:

The column index is zero based, so if you have six columns, the highest index is five.
Quick fix:
if (e.ColumnIndex == 5)
{
  // etc
}


Q:

How do I solve this error with Illegal Configuration?

I'm trying to connect an outlet from a view ,inside a cell ,inside a collection view , to my view controller file ,but I keep getting this error .
Illegal Configuration: The runningCard outlet from the HomeViewController to the UIView is invalid. Outlets cannot be connected to repeating content.
What should I do ?

A:

You have to do something like this, hope this helps.
import UIKit

class CustomCollection: UICollectionViewCell {
@IBOutlet var myView: UIView!
/*
 Please note you have to create the outlet yourself and then
 drag it to a view that you add to your cell, you cant use your view from your cell.
 */
}
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collection: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5//Number of rows in cell
}
var viewFromCell = [UIView()]//This array of views gets assigned by the collectionview method bellow.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collection.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! CustomCollection
    cell.myView = viewFromCell[indexPath.row]// This line of code gets the views from each cell and assigns them to the array of views declared above.
    return cell
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
 }
}

This is how you implement your storyboard with UICollectionView


Q:

Defining rotation without using angles, but as geometric transformations?

According to this article on angles, we can define rotation without using angles, and then use rotation to define angles. The relevant paragraph is at the very end:

But what is a rotation? Is it possible to define a rotation without
  first introducing the angle of rotation? Yes, this is possible based
  on the notion of geometric transformation. Rotation is a geometric
  transformation with a fixed point that preserves distances..

Question: May I have a reference (textbook or paper) regarding how this can be done? My background in this topic is just elementary geometry and linear algebra.

A:

Any non-zero angle less than $180^\circ$ can be the angle between two vectors, defined on a plane spanned by those vectors. The matrix of the linear transformation that represents rotation around such angle is the subject of this question. Then, this answer provides a neat way of finding such a matrix in $\mathbb{R}^3$.


Q:

Suppose $\int_{[a,b]}f=0,\text{ then }f(x)=0 \forall x\in[a,b]$

Let $a<b$ be real numbers. Let $f:[a,b]\to\mathbb{R}$ be a continuous non-negative function. Suppose $\int_{[a,b]}f=0,\text{ then }f(x)=0 \forall x\in[a,b]$

Proof:
Suppose for the sake of contradiction $\exists x_0\in[a,b] \text{ such that } f(x_0)= D> 0$
Since the function is continuous at $x_0$, we have
$$\forall \epsilon>0, \exists \delta>0 \text{ such that } |f(x)-f(x_0)|\leq\epsilon\text{ whenever } x\in[a,b]\cap(x_0-\delta,x_0+\delta)$$
choose $\delta=\delta_1$ such that $\epsilon=D/2$, then we can say:
$$-D/2 \leq f(x)-f(x_0)\leq D/2$$
$$-D/2 \leq f(x) - D$$
$$f(x)\geq D/2>0$$
This implies that $\int_{[a,b]\cap(x_0-\delta_1,x_0+\delta_1)}f >0$
Now since $\int_{[a,b]} f = 0$. we have
$$\int_{[a,b]}f=\int_{[a,x_0-\delta_1]}f+ \int_{(x_0-\delta_1, x_0+\delta_1)} f + \int_{[x_0+\delta_1,b]}f=0$$
$$\int_{[a,x_0-\delta_1]}f+\int_{[x_0+\delta_1,b]}f<-D/2,$$ but this is a contradiction since $f(x)\geq 0$ and hence $\int_{[a,x_0-\delta_1]}f+\int_{[x_0+\delta_1,b]}f\geq 0$
Is my proof correct?

A:

Your proof looks  completely right to me. In fact, it's the one I was planning to write if the question hadn't included a proof.
The only thing I'd change is to say that the integral, over the reduced interval, is at least $\frac{D}{2} 2\delta = \delta D > 0$. It's always nice to see a concrete estimate like that.
I might also simplify a little and start out by observing that $\int_{[0, a]} f = 0$ for any $0 < a < 1$ because $f$ is nonnegative, so the integrals from $0$ to $a$ and $a$ to $1$ must be nonnegative, but they sum to zero, and hence are both zero. Further such reasoining shows that $\int_I f = 0$ for any subtinterval of $[0, 1]$.
Once you've done that, you can stop your proof just before "This implies" by just saying "and now we've exhibited an interval over which the integral is positive, a contradiction."

A:

Yes, I think there's no problem with your solution. We can say in short: since $f\ge 0$, its graph lies above $Ox$. If $f(x_0)>0$ for some $x_0$, then there is a neighborhood of $x_0$ such that for all $x_1<x_2$ in that neighborhood, we have $f(x_1)>0,f(x_2)>0$. Then the area under the curve on the segment $[x_1,x_2]$ is greater than $0$, which is impossible.


Q:

Finding values from an ArrayList of ints in an ArrayList of objects with int fields without LINQ

I have two ArrayLists of different lengths. One contains ints, the other contains objects containing an int field. I want to check if any values from the list of ints appear as values of the int fields in any of the objects in the second list: eg. if
intList[i] == objList[j].value

for any i or j.
I'm using .NET 2.0, so I can't use LINQ. Thanks!

A:

Since HashSet<int> does not exists in 2.0 (if I remember correctly) use Dictionary.
Dictionary<int, object> dic = new Dictionary<int, object>(objList.Count);
foreach (object obj in objList)
    dic.Add(obj.value, null);
bool found = false;
foreach (int i in intList)
{
    if(dic.ContainsKey(i))
    {
        found = true;
        break;
    }
}


Q:

Validate that string doesn't contains any 3 characters sub-strings of lowercase that out of allowed set

I need to validate string of mixed upper and lower case characters [a-zA-Z] doesn't contain any lower case sub-strings of length 3 where every character is out of allowed set of characters.
For example, lets say that allowed set of characters that may repeat is [abc].
The list of allowed strings will looks like
abc
abcbcbcb
aaaaaaaa
AabcbaDEF
ABCDEFG
abcDEfgH
AbcDefG

and list of invalid strings
abcd
AbcdE
AabcbcdefgK

Is it possible to do it with regular expressions?

A:

Based on all the information in your question and comments, you're looking for strings that match the following requirements:

Any number of alpha characters so long as the following doesn't exist:

A substring of 3 lowercase letters containing a lowercase letter that is not in the set [abc]

Given those requirements (you definitely had me scratching my head for a bit there), the following regular expressions should work:
See regex in use here
^(?:(?!(?=[a-z]{3})[abc]{0,2}[^abc])[a-zA-Z])+$
^(?:(?!(?=[a-z]{3})[abc]{0,2}[d-z])[a-zA-Z])+$

Thanks to @anubhava in the comments below this answer for providing a faster alternative (doesn't use tempered greedy token):
See regex in use here
^(?!.*(?=[a-z]{3})[abc]{0,2}[d-z])[a-zA-Z]+$

^ Assert position at the start of the line
(?:(?!(?=[a-z]{3})[abc]{0,2}[^abc])[a-zA-Z])+ Tempered greedy token matching any ASCII alpha character ensuring the following doesn't exist:

(?=[a-z]{3}) Positive lookahead ensuring the following 3 characters are lowercase ASCII alpha characters
[abc]{0,2}[^abc] Matches between 0 and 2 characters from the set abc, followed by at least one character not in the set abc

The above basically ensures at least one lowercase letter not in our set abc exists within the lowercase substring of length 3

$ Assert position at the end of the line


Q:

Shell magic wanted: format output of hexdump in a pipe

I'm debugging the output of a program that transmits data via TCP.
For debugging purposes i've replaced the receiving program with netcat and hexdump:
netcat -l -p 1234 | hexdump -C

That outputs all data as a nice hexdump, almost like I want. Now the data is transmitted in fixed blocks which lengths are not multiples of 16, leading to shifted lines in the output that make spotting differences a bit difficult:
00000000  50 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |P...............|
00000010  00 50 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |.P..............|
00000020  00 00 50 00 00 00 00 00  00 00 00 00 00 00 00 00  |..P.............|

How do I reformat the output so that after 17 bytes a new line is started?
It should look something like this:
50 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |P...............|
00                                                |.               |
50 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |P...............|
00                                                |.               |
50 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |P...............|
00                                                |.               |

Using hexdumps -n parameter does not work since it will exit after reaching the number of bytes. (Unless there is a way to keep the netcat programm running and seamlessly piping the next bytes to a new instance of hexdump).
Also it would be great if I could use watch -d on the output to get a highlight of changes between lines.

A:

For hexdump without characters part.
hexdump -e '16/1 "%0.2x " "\n" 1/1 "%0.2x " "\n"'

A:

I use this:
use strict;
use warnings;
use bytes;

my $N = $ARGV[0];

$/ = \$N;

while (<STDIN>) {
    my @bytes = unpack("C*", $_);
    my $clean = $_;
    $clean =~ s/[[:^print:]]/./g;
    print join(' ', map {sprintf("%2x", $_)} @bytes),
    "  |", $clean, "|\n";
}

Run it as perl scriptname.pl N where N is the number of bytes in each chunk you want.


Q:

Different ways of animating between a series of images in Cocoa

I have a series of image (PNG) files, about 50 of them. If displayed quickly one after another they form a smooth animation.
How can I create this animation in Cocoa, within an NSView? What method would you suggest, and how would you go about doing it?
Most answers here seem to suggest Core Animation, but I need it to be in an NSView which accepts mouse events and drops, so I'm not sure if this will work.

A:

Core Animation is best way to display a smooth animation.
NSViewAnimation also can create a animation, but may not smooth as Core Animation.
NSView also can add Core Animation layer.
[NSView setWantLayer:YES]
In your question, You want accepts mouse events.So, I suggest to Use Core Animation to display animation at NSView,As NSView just accept events,and let layer to animation.
Sorry about my poor English,Hope I expression clearly. :)


Q:

How to generate binary variable according to the conditions of other variables?

Once again, I apologize for asking this type of question, but the R world is so large that sometime I feel lost, even if I have read some of the best book related with R.
I have the following DB
ID=rep((1:3),3)
x<-as.Date("2013-1-1")
y<-as.Date("2013-1-2")
z<-as.Date("2013-1-3")
DATE<-c(x,x,x,y,x,y,z,z,z)
TRAP<-c(1,1,1,3,2,3,2,1,3)
IN<-data.frame(ID,DATE,TRAP)

and I would like to produce a binary variable (RESULT) according to the following conditions: if the DATE and the TRAP is the same for the different ID, then RESULT>y otherwise RESULT>n, like this
RESULT<-c("y","y","y","y","n","y","n","n","n")
OUT<-cbind(IN,RESULT)

I think that the ifelse function should be used, but I don't know how to explicit the condition of equality controlling for each ID...
As always, every suggestion is greatly appreciated!

A:

Here is a way to do it with plyr :
R> ddply(IN, .(DATE,TRAP), transform, RESULT=ifelse(length(ID)>1,"y","n"))
  ID       DATE TRAP RESULT
1  1 2013-01-01    1      y
2  2 2013-01-01    1      y
3  3 2013-01-01    1      y
4  2 2013-01-01    2      n
5  1 2013-01-02    3      y
6  3 2013-01-02    3      y
7  2 2013-01-03    1      n
8  1 2013-01-03    2      n
9  3 2013-01-03    3      n

Note that the rows have been reordered.

Another solution with data.table :
R> DT <- data.table(IN)
R> DT[,RESULT:=ifelse(.N>1,"y","n"), by=list(DATE,TRAP)]
R> DT
   ID       DATE TRAP RESULT
1:  1 2013-01-01    1      y
2:  2 2013-01-01    1      y
3:  3 2013-01-01    1      y
4:  1 2013-01-02    3      y
5:  2 2013-01-01    2      n
6:  3 2013-01-02    3      y
7:  1 2013-01-03    2      n
8:  2 2013-01-03    1      n
9:  3 2013-01-03    3      n

There is no reordering here.

Or using base ave:
IN <- within(IN, { RESULT <- ave(TRAP, list(DATE, TRAP),
               FUN= function(x) ifelse(length(x) > 1, "y", "n"))})
#   ID       DATE TRAP RESULT
# 1  1 2013-01-01    1      y
# 2  2 2013-01-01    1      y
# 3  3 2013-01-01    1      y
# 4  1 2013-01-02    3      y
# 5  2 2013-01-01    2      n
# 6  3 2013-01-02    3      y
# 7  1 2013-01-03    2      n
# 8  2 2013-01-03    1      n
# 9  3 2013-01-03    3      n


Q:

Could medieval European merchants travel through the Islamic world?

I've heard that the Islamic world was closed to European merchants in the Middle Ages.  Is this true?  If so, when did it close and when did it open again?

A:

It's difficult to give a proper answer, because during any century of Middle Ages there could be many reasons for closing trading routes for European merchants as outsiders in various parts of Islamic world (which is huge). And it didn't need to have anything in common with religion - it could be the level of civilization (early medieval Europe), an economic matter in the particular case, or just a result of war.
But let's try to clarify few things.
First of all, Islamic world, in fact, wasn't that closed to Europeans as we think. Jews and Christians could live at Muslim lands if they paid special tax. The same with merchants from Europe. What's more, some Christians could even serve to Muslim rulers at important positions, such as revenue collectors or administrators of various types.
It's nicely described in the book "Daily Life In The Medieval Islamic World" by James E. Lindsay. You can find it's full text in the link, look for pages 120-121.
Also there's a good source for that in "Europe and the Islamic World: A History" by John Tolan, Henry Laurens and Gilles Veinstein, at pages 80-81. Unfortunately in both cases I'm not able to copy-paste it.
I believe that a bit about the overall history of the trade between Christians and Muslims during Middle Ages could help you solve the problem. I'll quote Jihoon Ko and his article "Economic Impact the Islamic World Had on Christian Europe (11th ~14th century)".

The conquest of Muslims of various regions of Europe had actually
  ceased the major long-distance trade of the Christian Europeans
  overseas for a while and the commerce of Christian Europe had been
  limited to the local ones. But the regions which were under Islamic
  rules were included in the commercial sphere of the Muslims—who were
  the most active adventurers and entrepreneurs at the time—saw the rise
  of international and complicated commercial activities. The
  international trades in Christian regions were late to appear. The
  crusade created a large influx of Eastern goods and luxuries into the
  Christian Europe. This created a large interest among rich Europeans
  for the Eastern goods, and the Christian merchants saw this to be an
  opportunity for a dramatic profit. As the merchants began to actively
  engage in the trade with the Islamic world, the trade of the Christian
  states overseas began to flourish. The leading states of the trade
  with the East were Italian city-states, most notably Genoa and Venice.
  The extent of the international trades before the 11th century,
  however, was nothing compared with those of the Muslim world. The case
  of Al-Andalus indicates how well established was the Andalusi
  merchants’ trades compared with the Europeans in the same era.

This way first, European (Christian) international trade wasn't well developed until 11th century, mainly due to the fall of ancient culture. It took European civilization a lot of time to get up after that.
But there were some smart merchants who made a fine business by initiating contacts between both worlds. They were, of course, Jews.

There were some global commercial activities going on in the Christian
  world, however, before the Christians began to trade over long
  distance, by the Jewish merchants. The Jews were also the first
  merchants in the Middle Ages to introduce goods from the East to the
  Christian Europeans. They supplied goods from the Islamic world as
  soon as the Carolingian era. The Jews could travel to Europe with
  relative ease. Some of them settled in Italy, but majority of them
  were those who based their commerce in the Muslim countries. The Jews
  from the Muslim world reached Western and Northern Europe through
  Spain. At first, they exclusively traded spices, pepper, manufactured
  goods, and other precious stuffs from Egypt, Syria, and Maghrib. They
  provided the goods to the churches which used the goods to make
  incense for religious activities, and to the selected nobility.

When European trade market became more international, the crusades started. One could imagine that it made the trade more difficult, from the most obvious reason which is "you don't go trading with your enemy if you don't want to be killed".
Somehow, in fact it helped to open both markets on each other.

The crusades, in turn, helped to change the economic activity of
  Christian Europe. The crusades “enabled Western Europe to monopolize
  the whole trade from the Bosphorus and Syria to the Straits of
  Gibraltar.”[10] Even if they failed to take the holy place from the
  hands of Muslims, they politically weakened the powers of the Islamic
  states and Byzantine Empire. The Byzantine Empire’s maritime power was
  weakened seriously and their merchants now could not compete with the
  Italian rivals, which now controlled the Byzantine Empire’s export and
  import trades. The crusades also caused the large influx of Eastern
  luxuries into Christian Europe, thus stimulating the interest of
  people for the trade with the Islamic world. So, it is no exaggeration
  to say that the crusades were crucial factor in the revival of
  extensive economic activities of Medieval Christian Europe.

As it's described later, the main European ports that were trading with Islamic World were Genoa and Venice. And even if there were some difficulties, a business is still a business.

The trades with the Islamic world at first time were limited because
  of religious reason, and because of technical reasons, but gradually
  the Italian merchants began to seek profits and the economic
  incentives were large enough to overcome religious obstacles for
  greater incomes. As a result, the Italian city-states rose as major
  maritime commercial centers from 11th century, and the scope of their
  trades even exceeded that of the Muslim ports.

I'll quote only two paragraphs more and I'll leave the rest to you, if you're more interested in the trade with Islamic World in overall, not only from the point of it's connection to religious problematic.

Christians and Muslims have been enemies by principles. Moreover, as
  the Middle Age was the time when the religion affected the lives of
  Christians most significantly, the Muslims were considered evil by
  Christians. This aversion of Christians toward Muslims, however, could
  not stop the economic interest of the Christian merchants, and the new
  pattern of global trade appeared.
The Muslim world indeed acted as an important trade partner of Europe
  in the Late Middle Age. They facilitated the European trade and thus
  strengthened its economy. Also, they provided the goods that were not
  available in Europe, and this fact made Europe a favorite place for
  European merchants. The religious principle could not separate the
  two. The trades between Europe and the Muslim World sometimes stopped
  because of political situations, and were greatly reduced when the
  Turkish soldiers occupied Constantinople and destroyed Byzantine
  Empire. However, it is evident that the two had long-time economic
  connections, and such connectivity helped the European economy a lot.


Q:

solr indexing custom json - creates empty documents

I am quite new to solr. I currently have it running in cloud mode using docker compose (my configuration can be seen at the end of the question)
I created a collection called audittrail using default configuration. The idea is that I'll send event logging info from another app to solr. It has a convenient looking schema full of dynamic fields by default. (I know I shouldn't just use default settings in production, right now I'm looking for a proof of concept).
Now I'm following this document in an attempt to index some of my data: https://lucene.apache.org/solr/guide/7_2/transforming-and-indexing-custom-json.html#mapping-parameters
> curl 'http://0.0.0.0:8983/api/collections/audittrail/update/json'\
  '?split=/events&'\
  'f=action_kind_s:/action_kind_s&'\
  'f=time_dt:/events/time_dt'\
  '&echo=true' \  ########## NOTE this means we're running in debug more. solr returns the documents it should be creating
  -H 'Content-type:application/json' -d '{
 "action_kind_s": "task_exec",
 "events": [
     {
         "event_kind_s": "start",
         "in_transaction_b": false,
         "time_dt": "2018-03-09T12:57:07Z"
     },
     {
         "event_kind_s": "start_txn",
         "in_transaction_b": true,
         "time_dt": "2018-03-09T12:57:07Z"
     },
     {
         "event_kind_s": "diff",
         "in_transaction_b": true,
         "key_s": "('MerchantWorkerProcess', 5819715045818368L)",
         "property_s": "claim_time",
         "time_dt": "2018-03-09T12:57:07Z",
         "value_dt": "2018-03-09T12:57:07Z"
     },
 ],
 "final_status_s": "COMPLETE",
 "request_s": "1dfda9955dac6f3cfd76fbedee98b15f6edc0db",
 "task_name_s": "0p5k20100CcnMVxaxoWl32WlfPixjV1OFKgv0k1KZ0m_acc_work"
}'

# response:

{
  "responseHeader":{
    "status":0,
    "QTime":1},
  "docs":[{},
    {},
    {}]}

That's three empty documents...
So I thought maybe it was because I wasn't specifying an id. So I gave each event a unique id and tried again with the added &f=id:/events/id. Same result
Originally I tried using wildcards (&f=/**) with the same effect.
There is obviously something missing in my understanding.
So my question is:
What should I do to get my documents populated correctly?
EDIT
Also, my solr node logs arent turnng up any errors. Here's a sample:
2018-03-09 14:30:50.770 INFO  (qtp257895351-21) [c:audittrail s:shard2 r:core_node4 x:audittrail_shard2_replica_n2] o.a.s.u.p.LogUpdateProcessorFactory [audittrail_shard2_replica_n2]  webapp=null path=/update/json params={split=/events}{add=[78953602-6b02-4948-8443-fd1ebc340921 (1594470800573857792)]} 0 3

2018-03-09 14:31:05.770 INFO  (commitScheduler-14-thread-1) [c:audittrail s:shard2 r:core_node4 x:audittrail_shard2_replica_n2] o.a.s.u.DirectUpdateHandler2 start commit{_version_=1594470816305643520,optimize=false,openSearcher=false,waitSearcher=true,expungeDeletes=false,softCommit=false,prepareCommit=false}

2018-03-09 14:31:05.770 INFO  (commitScheduler-14-thread-1) [c:audittrail s:shard2 r:core_node4 x:audittrail_shard2_replica_n2] o.a.s.u.SolrIndexWriter Calling setCommitData with IW:org.apache.solr.update.SolrIndexWriter@13d117d6 commitCommandVersion:1594470816305643520

2018-03-09 14:31:05.918 INFO  (commitScheduler-14-thread-1) [c:audittrail s:shard2 r:core_node4 x:audittrail_shard2_replica_n2] o.a.s.s.SolrIndexSearcher Opening [Searcher@4edc35b0[audittrail_shard2_replica_n2] realtime]

2018-03-09 14:31:05.921 INFO  (commitScheduler-14-thread-1) [c:audittrail s:shard2 r:core_node4 x:audittrail_shard2_replica_n2] o.a.s.u.DirectUpdateHandler2 end_commit_flush

docker-compose.yml
version: '3'
services:
  zookeeper:
    image: zookeeper:3.4.11
    ports:
     - "2181:2181"
    hostname: "zookeeper"
    container_name: "zookeeper"
  solr1:
    image: solr:7.2.1
    ports:
      - "8983:8983"
    container_name: solr1
    links:
      - zookeeper:ZK
    command: /opt/solr/bin/solr start -f -z zookeeper:2181
  solr2:
      image: solr:7.2.1
      ports:
        - "8984:8983"
      container_name: solr2
      links:
        - zookeeper:ZK
      command: /opt/solr/bin/solr start -f -z zookeeper:2181

Here are the exact steps I go through to index some data.
This does not actually index anything and I want to know why

docker-compose up
create the collection
curl -X POST 'http://0.0.0.0:8983/solr/admin/collections?action=CREATE&name=audittrail&numShards=2'

{
"responseHeader":{
"status":0,
"QTime":6178},
"success":{
"172.24.0.3:8983_solr":{
  "responseHeader":{
    "status":0,
    "QTime":3993},
  "core":"audittrail_shard1_replica_n1"},
"172.24.0.4:8983_solr":{
  "responseHeader":{
    "status":0,
    "QTime":4399},
  "core":"audittrail_shard2_replica_n2"}},
"warning":"Using _default configset. Data driven schema functionality is enabled by default, which is NOT RECOMMENDED for production use. To turn it off: curl http://{host:port}/solr/audittrail/config -d '{\"set-user-property\": {\"update.autoCreateFields\":\"false\"}}'"}

curl to create some data ( this is the same curl as in the main question. but not in debug mode:
curl 'http://0.0.0.0:8983/api/collections/audittrail/update/json?split=/events&f=action_kind_s:/action_kind_s&f=time_dt:/events/time_dt' -H 'Content-type:application/json' -d '{ "action_kind_s": "task_exec",  "events": [{"event_kind_s": "start","in_transaction_b": false,          "time_dt": "2018-03-09T12:57:07Z"},{"event_kind_s": "start_txn",          "in_transaction_b": true,"time_dt": "2018-03-09T12:57:07Z"},{"event_kind_s": "diff", "in_transaction_b": true,"key_s": "('MerchantWorkerProcess', 5819715045818368L)","property_s": "claim_time","time_dt": "2018-03-09T12:57:07Z","value_dt": "2018-03-09T12:57:07Z"},],  "final_status_s": "COMPLETE",  "request_s": "xxx",  "task_name_s": "xxx"}'

{
"responseHeader":{
"status":0,
"QTime":126}}

Do the query:
curl 'http://0.0.0.0:8983/solr/audittrail/select?q=*:*'
{
"responseHeader":{
"zkConnected":true,
"status":0,
"QTime":12,
"params":{
  "q":"*:*"}},
  "response":{"numFound":0,"start":0,"maxScore":0.0,"docs":[]
 }}

A:

It seems that it's only the echo parameter that doesn't do what you expect it to do - remove that, and add commit=true to your URL to make Solr commit the documents to the index as soon as possible before returning, and you can then find documents (by searching for *:* in the admin interface under collection -> query with your fields present in the index:
{
  "action_kind_s":"task_exec",
  "time_dt":"2018-03-09T12:57:07Z",
  "id":"b56100f5-ff61-45e7-8d6b-8072bac6c952",
  "_version_":1594486636806144000},
{
  "action_kind_s":"task_exec",
  "time_dt":"2018-03-09T12:57:07Z",
  "id":"f49fc3cb-eac6-4d02-bcdf-b7c1a34782e3",
  "_version_":1594486636807192576}


Q:

Comparison among NIO webservers

We need to put in our architecture a server for streaming contents to (potentially) millions of phones.
Here the architects and operations people know only about Java, but I'd really to propose something faster and easier to maintain.
My list of candidates currently is: Lift, Node.js, Yaws.
The server should serve static content (videos, games, xml descriptions) after authenticating user credentials and charging the user. So a nosql db (couchdb or mongodb) will be used as well.
No need to produce dynamic content or html.
The pure speed is important but not the only parameter, also operational ease to use is important.
From a development point of view I really like all 3 in their own way.

All other things being equal Lift would be my first choice because of compatibility between Scala and Java.
Second one is node.js because everybody understand Javascript.
Erlang is a bit hard to learn and teach, so Yaws would be my last choice, although I personally like it.

So the question is: in your experience, what would you recommend me? Could be also another one.

A:

difficult comparision because of your requirements, but I like node better. But then again for your requirements maybe java is a better fit.

The server should serve static content
  (videos, games, xml descriptions)
  after authenticating user credentials
  and charging the user. So a nosql db
  (couchdb or mongodb) will be used as
  well.

node.js is/was(3.x solves this better) not so good at handling large requests => Watch this roadmap talk from ryan dahls about large requests problem(35:36 and onwards you see a diagram which is unacceptable, both is being solved in 3.x).
Can only compare node vs java, because I don't have any experience with erlang.

npm vs maven => npm much nicer.
some very nice libraries in node.js and a lot created all the time at github.com. To name some: express, socket.io, npm, node_redis
very fast prototyping in node.js.
People should learn to use javascript anyway if webprogrogramming.
IDE for java are much better, but you need to type much less in node.js. You could even reduce your typing by using coffeescript(maybe zappa). For example I also like the Junit integration in netbeans vs node.js unit testing support in IDE(non existing?).


Q:

Pass array from URL to javascript

How can i pass an array from a GET request like this:
[x, y], [x, y]...

Into the second part of this google visualization API call.
var data = google.visualization.arrayToDataTable([
['Initial', 'Second'],
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);

Currently i have the values pre-set, but i would like to pass them from a GET request.
I have tried using PHP for this however failed using methods like this passing arrays as url parameter as i am not quite sure how to set the x value properly.
Below is the script i use to generate the chart:
  <script>
    google.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Initial', 'Second'],
        [8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);

      var options = {
        width: 420,
        height: 420,
        legend: 'none',
        trendlines: { 0: {} },
        colors: ['#FE2E2E'],
        hAxis: {
            textPosition: 'none',
            gridlines: {
                color: "#CCCCCC"
            },
            baselineColor: '#CCCCCC'
        },
        vAxis: {
            textPosition: 'none',
            gridlines: {
                color: "#CCCCCC"
            },
            baselineColor: '#CCCCCC'
        },
        enableInteractivity: false
      };

      var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
  </script>

A:

Once you have the response from the GET request:-
 var myArrayData = JSON.parse(responseData);

Now your data will be of the form
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]

Then do:
myArrayData.unshift(['Initial', 'Second']);

Now you can try:
var data = google.visualization.arrayToDataTable(myArrayData);