问:
Spark SQL error read JSON file : java.lang.ClassNotFoundException: scala.collection.GenTraversableOnce$class
i am trying to read JSON file using Spark SQL in Java.
this is my code

```<code>import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.SQLContext;
...
JavaSparkContext jsc = new JavaSparkContext(sparkConf);
SQLContext sqlContext = new SQLContext(jsc);
DataFrame df = sqlContext.jsonFile("~/test.json");
df.printSchema();
df.registerTempTable("test");
...
</code>```

i made simple JSON "test.json", to make it simple:

```<code>{
   "name": "myname"
}
</code>```

and when i tried to run the code, it comes error message:

```<code>efg
17/03/30 10:02:26 INFO BlockManagerMasterEndpoint: Registering block manager 10.6.86.82:36824 with 1948.2 MB RAM, BlockManagerId(driver, 10.6.86.82, 36824)
17/03/30 10:02:26 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 10.6.86.82, 36824)
17/03/30 10:02:26 INFO StandaloneSchedulerBackend: SchedulerBackend is ready for scheduling beginning after reached minRegisteredResourcesRatio: 0.0
Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce$class
at org.apache.spark.sql.sources.CaseInsensitiveMap.<init>(ddl.scala:344)
at org.apache.spark.sql.sources.ResolvedDataSource$.apply(ddl.scala:219)
at org.apache.spark.sql.SQLContext.load(SQLContext.scala:697)
at org.apache.spark.sql.SQLContext.jsonFile(SQLContext.scala:572)
at org.apache.spark.sql.SQLContext.jsonFile(SQLContext.scala:553)
at sugi.kau.sparkonjava.SparkSQL.main(SparkSQL.java:32)
Caused by: java.lang.ClassNotFoundException: scala.collection.GenTraversableOnce$class
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 6 more
17/03/30 10:02:26 INFO SparkContext: Invoking stop() from shutdown hook
...
</code>```

thanks

答:
in the docs spark for the function jsonFile(String path):
Loads a JSON file (one object per line), returning the result as a DataFrame. (Note tha jsonFile is replaced by read().json())

so you should have an object per line and your source file should be like this :

```<code>  {"name": "myname"}
  {"name": "myname2"}
  .....
</code>```

Body:
i am trying to read JSON file using Spark SQL in Java.
this is my code

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.SQLContext;
...
JavaSparkContext jsc = new JavaSparkContext(sparkConf);
SQLContext sqlContext = new SQLContext(jsc);
DataFrame df = sqlContext.jsonFile("~/test.json");
df.printSchema();
df.registerTempTable("test");
...

i made simple JSON "test.json", to make it simple:

{
   "name": "myname"
}

and when i tried to run the code, it comes error message:

efg
17/03/30 10:02:26 INFO BlockManagerMasterEndpoint: Registering block manager 10.6.86.82:36824 with 1948.2 MB RAM, BlockManagerId(driver, 10.6.86.82, 36824)
17/03/30 10:02:26 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 10.6.86.82, 36824)
17/03/30 10:02:26 INFO StandaloneSchedulerBackend: SchedulerBackend is ready for scheduling beginning after reached minRegisteredResourcesRatio: 0.0
Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce$class
at org.apache.spark.sql.sources.CaseInsensitiveMap.<init>(ddl.scala:344)
at org.apache.spark.sql.sources.ResolvedDataSource$.apply(ddl.scala:219)
at org.apache.spark.sql.SQLContext.load(SQLContext.scala:697)
at org.apache.spark.sql.SQLContext.jsonFile(SQLContext.scala:572)
at org.apache.spark.sql.SQLContext.jsonFile(SQLContext.scala:553)
at sugi.kau.sparkonjava.SparkSQL.main(SparkSQL.java:32)
Caused by: java.lang.ClassNotFoundException: scala.collection.GenTraversableOnce$class
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 6 more
17/03/30 10:02:26 INFO SparkContext: Invoking stop() from shutdown hook
...

thanks

Body:
in the docs spark for the function jsonFile(String path):
Loads a JSON file (one object per line), returning the result as a DataFrame. (Note tha jsonFile is replaced by read().json())

so you should have an object per line and your source file should be like this :

  {"name": "myname"}
  {"name": "myname2"}
  .....


来源: stackexchange

问:
if condition is not working properly it is not checking properly
I have created a function to create automatic username on the bassis of name if name already exist then username will be creted on the basis of user id but when I created a user and tested if the name is already not present into the database it is creating username alongwith user id as it shouldn't be because test name is not already in the database. here is my code</p>

```<code>// $user_id is the last inserted id
$check_username = $this->db->where('name', $name);
        $check_username = $this->db->where('id !=', $user_id);
        $check_username = $this->db->get('users');

        if($check_username >= 1) {
            $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
        } else {
            $username = strtolower(str_replace(" ", ".", $name));
        }

        $this->db->where('id', $user_id);
        $this->db->update('users', array("username" => $username));
</code>```

答:
You could use $this->db->num_rows() or try below code

```<code>$check_username = $this->db->where('name', $name)->where('id !=', $user_id)->get('users')->num_rows();

if($check_username > 0) {
    $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
} else {
    $username = strtolower(str_replace(" ", ".", $name));
}

$this->db->where('id', $user_id);
$this->db->update('users', array("username" => $username));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a function to create automatic username on the bassis of name if name already exist then username will be creted on the basis of user id but when I created a user and tested if the name is already not present into the database it is creating username alongwith user id as it shouldn't be because test name is not already in the database. here is my code

// $user_id is the last inserted id
$check_username = $this->db->where('name', $name);
        $check_username = $this->db->where('id !=', $user_id);
        $check_username = $this->db->get('users');

        if($check_username >= 1) {
            $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
        } else {
            $username = strtolower(str_replace(" ", ".", $name));
        }

        $this->db->where('id', $user_id);
        $this->db->update('users', array("username" => $username));

Body:
You could use $this->db->num_rows() or try below code

$check_username = $this->db->where('name', $name)->where('id !=', $user_id)->get('users')->num_rows();

if($check_username > 0) {
    $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
} else {
    $username = strtolower(str_replace(" ", ".", $name));
}

$this->db->where('id', $user_id);
$this->db->update('users', array("username" => $username));


问:
Collapse with label in stata
I want to keep my variable labels after collapsing in stata. I found Nick Cox's solution not working for me. The code looks like this:
Before -collapse-, copy the variable labels to local macros:

```<code>foreach v of var * {
    local l`v' : variable label `v'
}
</code>```

After -collapse-, use the old labels:

```<code>foreach v of var * {
    label var `v' "`l`v''"
}
</code>```

All my variables after collapsing still have no labels.

答:
This post extensively tackles the problem, but:

before collapse you need:

```<code>foreach v of var * {
 local l`v' : variable label `v'
       if `"`l`v''"' == "" {
    local l`v' "`v'"
    }
}
</code>```

after collapse you need:

```<code>foreach v of var * {
label var `v' "`l`v''"
}
</code>```

Title: Collapse with label in stata

Body:
I want to keep my variable labels after collapsing in stata. I found Nick Cox's solution not working for me. The code looks like this:
Before -collapse-, copy the variable labels to local macros:

foreach v of var * {
    local l`v' : variable label `v'
}

After -collapse-, use the old labels:

foreach v of var * {
    label var `v' "`l`v''"
}

All my variables after collapsing still have no labels.

Body:
This post extensively tackles the problem, but:

before collapse you need:

foreach v of var * {
 local l`v' : variable label `v'
       if `"`l`v''"' == "" {
    local l`v' "`v'"
    }
}

after collapse you need:

foreach v of var * {
label var `v' "`l`v''"
}


问:
Laravel: Undefined variable in blade view
This is AdminController.php:

<?php

namespace App\Http\Controllers;

use Response;

use Illuminate\Support\Facades\DB;
use App\Caption;
use App\Image;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function admin() {
        $images = Image::paginate();

        return view('admin',[ '$images' => $images]);
    }
}
```

<p>And this is <code>admin.blade.php</code>:</p>

```@extends('template')

@section('title')
    Admin Page
@endsection

@section('header')
@endsection

@section('main')
    @if (Auth::check())
        @foreach ($images as $image)

id}}'>{{$image->content}}

            <form action="image/{{$image->id}}/delete" method="post">
                <button type="submit">Delete caption</button>
            </form>
            <form action="image/{{$image->id}}/approve" method="post">
                <button type="submit">Accept image</button>
            </form>
        @endforeach
    @else

Login first

    @endif
@endsection

@section('footer')
@endsection
```

Why do I get the following error?

ErrorException in 408148d5409ae6eebf768dc5721bd0d1d9af48af.php line 9:
  Undefined variable: images (View: /Users/sahandz/Documents/School/Singapore/CS3226/backend/resources/views/admin.blade.php)

$imagesis clearly defined in my controller.

答:
Try passing data like this.

```<code>$images = Image::paginate();
return view("admin")->with('images',$images);
</code>```

Basically,you need not use $ in the variable name.

ContentLicense: CC BY-SA 4.0

Body:
This is AdminController.php:

<?php

namespace App\Http\Controllers;

use Response;

use Illuminate\Support\Facades\DB;
use App\Caption;
use App\Image;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function admin() {
        $images = Image::paginate();

        return view('admin',[ '$images' => $images]);
    }
}

And this is admin.blade.php:

@extends('template')

@section('title')
    Admin Page
@endsection

@section('header')
@endsection

@section('main')
    @if (Auth::check())
        @foreach ($images as $image)

id}}'>{{$image->content}}

            <form action="image/{{$image->id}}/delete" method="post">
                <button type="submit">Delete caption</button>
            </form>
            <form action="image/{{$image->id}}/approve" method="post">
                <button type="submit">Accept image</button>
            </form>
        @endforeach
    @else

Login first

    @endif
@endsection

@section('footer')
@endsection

Why do I get the following error?

ErrorException in 408148d5409ae6eebf768dc5721bd0d1d9af48af.php line 9:
  Undefined variable: images (View: /Users/sahandz/Documents/School/Singapore/CS3226/backend/resources/views/admin.blade.php)

$imagesis clearly defined in my controller.

Body:
Try passing data like this.

$images = Image::paginate();
return view("admin")->with('images',$images);

Basically,you need not use $ in the variable name.


问:
Ember Data - Serialization Options
I have a model with a hasMany realtionship.

I currently use the EmbeddedRecordsMixin to include the JSONAPI in my payload that is then sent to the server.

My problem is that I wish to send only the JSON representation of this object. i.e without type and attributes hash. Instead I wish to the send the payload as simply JSON  { id: 1, Name: 'Darren', Surname: 'Blh' ... }

How is it possible to convert the JSONAPI to JSON?

Thanks

Darren

答:
I solved this by overriding the serialize() method on the serializer.</p>

```<code>serialize(snapshot, options) {
   var json = this._super(...arguments);

   for (let i = 0; i < json.passengers.length; i++ ) {
     console.log('Converting Person JSON:API to JSON');
     json.passengers[i].id           = json.passengers[i].data.id;
     json.passengers[i].firstName    = json.passengers[i].data.attributes.firstName;
     json.passengers[i].lastName     = json.passengers[i].data.attributes.lastName;

     delete json.passengers[i].data;
   }
   return json;
}
</code>```

Title: Ember Data - Serialization Options

Body:
I solved this by overriding the serialize() method on the serializer.

serialize(snapshot, options) {
   var json = this._super(...arguments);

   for (let i = 0; i < json.passengers.length; i++ ) {
     console.log('Converting Person JSON:API to JSON');
     json.passengers[i].id           = json.passengers[i].data.id;
     json.passengers[i].firstName    = json.passengers[i].data.attributes.firstName;
     json.passengers[i].lastName     = json.passengers[i].data.attributes.lastName;

     delete json.passengers[i].data;
   }
   return json;
}


问:
How to change header color (contextPopupMenuStyle)
I want to change the header color of(title)

the content color is changed by itemTextAppearance attribute.

how to change header, title color?

contextPopupMenuStyle attribute is supported API 24. Please help!

答:
I had the same problem, I dont know how do this in xml files, but you can do this programmicaly from code by using SpannableString in onCreateContextMenu.

For example :

```<code>SpannableString spannableString = new SpannableString("my_string"));
spannableString.setSpan(new FregroundColorSpan(Color.parseColor("#D1BA88")), 0, spannableString.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    menu.setHeaderTitle(spannableString);
</code>```

Body:
I had the same problem, I dont know how do this in xml files, but you can do this programmicaly from code by using SpannableString in onCreateContextMenu.

For example :

SpannableString spannableString = new SpannableString("my_string"));
spannableString.setSpan(new FregroundColorSpan(Color.parseColor("#D1BA88")), 0, spannableString.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    menu.setHeaderTitle(spannableString);


问:
Datagridview check box checked is not working
I added checkbox in datagridview and trying to put default value as checked but it is showing checkbox unchecked, here is my code:

```<code>OracleDataAdapter da = new OracleDataAdapter(qry, myConnection);
OracleCommandBuilder cmdBuilder = new OracleCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
dgv.DataSource = ds.Tables[0];

DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;

dgv.Columns.Insert(8, checkColumn);

foreach (DataGridViewRow row in dgv.Rows)
{
   DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[dgv.Columns.Count - 1];
   chk.Value = chk.TrueValue;
}
</code>```

I tried the following code also but still not showing as "CHECKED":

```<code>chk.Value = true;
</code>```

Please help me solve this issue, thanks

答:
default value of DataGridViewCheckBoxCell.TrueValue is null. Set the TrueValue property of the owning column:

```<code>checkColumn.TrueValue = true;
</code>```

Body:
I added checkbox in datagridview and trying to put default value as checked but it is showing checkbox unchecked, here is my code:

OracleDataAdapter da = new OracleDataAdapter(qry, myConnection);
OracleCommandBuilder cmdBuilder = new OracleCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
dgv.DataSource = ds.Tables[0];

DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;

dgv.Columns.Insert(8, checkColumn);

foreach (DataGridViewRow row in dgv.Rows)
{
   DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[dgv.Columns.Count - 1];
   chk.Value = chk.TrueValue;
}

I tried the following code also but still not showing as "CHECKED":

chk.Value = true;

Please help me solve this issue, thanks

Body:
default value of DataGridViewCheckBoxCell.TrueValue is null. Set the TrueValue property of the owning column:

checkColumn.TrueValue = true;


Title: How to remove duplicate elements based date

Body:
I am having dictinoary which contains list of list

find_dup = {"one":[["1654","raj","425","16-02-2017"],["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"],["1654","ss","425","14-02-2017"]]}

I want to find duplicated based in list of first and third element

eg

["1654","raj","425","16-02-2017"] -> 1654,425
["1654","mo","426","20-02-2017"] -> 1654,426
["1654","ss","425","20-02-2017"] -> 1654,425
["1654","vs","427","20-02-2017"] -> 1654,427
["1654","ss","425","14-02-2017"] -> 1654,425

From the above elements it shows 1654,425 are duplicates (since i want to find duplicates based on first and third elements)

So from the above list this list are duplicates

["1654","raj","425","16-02-2017"] -> 1654,425
["1654","ss","425","20-02-2017"] -> 1654,425
["1654","ss","425","14-02-2017"] -> 1654,425

now from this list we have to remove 2 elements which has older date (last element of list is date)

This 2 list has older date so this should be removed

["1654","raj","425","16-02-2017"] -> 1654,425
["1654","ss","425","14-02-2017"] -> 1654,425

Results should be this

find_dup = {"one":[["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"]]}

I have python script which iterates through lists but i could not find logic on how to do pop an element if i find duplicate and replace the latest date

This is my script which failed

find_dup = {"one":[["1654","raj","425","16-02-2017"],["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"],["1654","ss","425","14-02-2017"]]}

for d in find_dup:
    len_d = len(find_dup[d])
    store_array_dup = []
    store_array_ele = {}
    for i in find_dup[d]:

        val = i[0]+"-"+i[1]"-"+i[2]"-"+i[3]
        val_1 = i[0]+"-"+i[2]
        if val_1 in store_array_dup:
            store_array_ele.append(val_1)
        else:
            arrs = []
            arrs.append(val)
            store_array_ele[d] = arrs

How could i produce this results

find_dup = {"one":[["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"]]}

Body:
This is your dataset:

find_dup = {"one":[
                      ["1654","raj","425","16-02-2017"],
                      ["1654","mo","426","20-02-2017"],
                      ["1654","ss","425","20-02-2017"],
                      ["1654","vs","427","20-02-2017"],
                      ["1654","ss","425","14-02-2017"]
                   ]
            }

You can make a new dict base on your dataset with new key based on first and third element and sort it by date:

from datetime import datetime
lst = sorted(find_dup['one'] , key=lambda x: datetime.strptime(x[3], "%d-%m-%Y"))

new_dict = {(item[0], item[2]): item for item in lst}

print(new_dict)

Output:

>>> print(new_dict.values())
[['1654', 'vs', '427', '20-02-2017'], ['1654', 'mo', '426', '20-02-2017'], ['1654', 'ss', '425', '20-02-2017']]


问:
angular code is not working properly

```
</div>
</div>

This div tag i have written in my index.html file from there so can display details.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><div class="col-md-9 col-sm-11 cTwo">
                <div class="navbar navbar-default">
                    <div class="container">
                        <!-- Brand and toggle get grouped for better mobile display -->
                        <div class="navbar-header">
                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="true">
                                <span class="sr-only">Toggle navigation</span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                        </div>

                        <!-- Collect the nav links, forms, and other content for toggling -->
                        <div class="collapse navbar-collapse">
                            <ul class="nav navbar-nav">
                                <li>Venue Details</li>
                                <li>Batch Details</li>
                                <li>Student Details</li>
                                <li>Trainer Details</li>
                            </ul>
                        </div>

                    </div>
                </div>
<!--                <div ui-view></div>-->

            </div>
        </div></code>```

This is my dashboard.html file which is coming when ui-view is called in index.html page but I want to display different html pages when click on link as shown in this code. Html detail should come in the place where I have commented the div tag with ui-view.

angular.module("activeCubs", ["signUp","login","dashboard","venueGet", "editVenue", "myListApp", "studentApp", "batchApp", "trainerDet", "ui.router", "xeditable", "ngDialog"])
       .config(function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise("/login");
        $stateProvider

            .state("signUp",{
            url:"/register",
            templateUrl: "forms/signup.html",
            controller:"myCtrl"
            })
            .state("login",{
                   url:"/login",
                   templateUrl:"forms/login.html",
                   controller:"loginCtrl"
                   })
            .state("dashboard", {
            url:"/dashboard/:token",
            templateUrl:"dashboard.html",
            controller:"dashboard"
        })

            .state("venueList", {
                url: "/venueList",
                templateUrl: "venue/venueDetailsListView.html",
                controller: "venueGetCtrl"
            })
            .state("venueDetails", {
                url: "/venueDetails",
                templateUrl: "venue/venueDetails.html",
                controller: "venueDetailCtrl"
            })
            .state("editVenueDetails", {
                url: "/editVenueDetails",
                templateUrl: "venue/venueDetailsEdit.html",
                controller: "editCtrl"
            })
            .state("batchList", {
                url: "/batchList",
                templateUrl: "batch/batchlist.html",
                controller: "myListCtrl"
            })
            .state("batchDetails", {
                url: "/batchDetails",
                templateUrl: "batch/batchdetails.html",
                controller: "batchCtrl"
            })
            .state("studentDetails", {
                url: "/studentDetails",
                templateUrl: "student/stdtwo.html",
                controller: ""
            })
            .state("studentData", {
                url: "/studentData",
                templateUrl: "student/stdone.html",
                controller: ""
            })
            .state("trainerDetails", {
                url: "/trainerDetails",
                templateUrl: "trainer/trainerDetails.html",
                controller: "trainerCtrl"
            })
            .state("index", {
                url: "/index",
                templateUrl: "index.html",
                controller: ""
            })
            .state("editTrainer", {
                url: "/editTrainer",
                templateUrl: "trainer/traineredit.html",
                controller: "trainerCtrl"
            })
    });```

This my app.js file .

答: I think you have one div extra which is not opened..Please check you have 5 open div But 6 close div.Hope this help.</p>

Title: angular code is not working properly

Body:
This div tag i have written in my index.html file from there so can display details.

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="true">
                                Toggle navigation

                            </button>

Venue Details

Batch Details

Student Details

Trainer Details

This is my dashboard.html file which is coming when ui-view is called in index.html page but I want to display different html pages when click on link as shown in this code. Html detail should come in the place where I have commented the div tag with ui-view.

angular.module("activeCubs", ["signUp","login","dashboard","venueGet", "editVenue", "myListApp", "studentApp", "batchApp", "trainerDet", "ui.router", "xeditable", "ngDialog"])
       .config(function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise("/login");
        $stateProvider

            .state("signUp",{
            url:"/register",
            templateUrl: "forms/signup.html",
            controller:"myCtrl"
            })
            .state("login",{
                   url:"/login",
                   templateUrl:"forms/login.html",
                   controller:"loginCtrl"
                   })
            .state("dashboard", {
            url:"/dashboard/:token",
            templateUrl:"dashboard.html",
            controller:"dashboard"
        })

            .state("venueList", {
                url: "/venueList",
                templateUrl: "venue/venueDetailsListView.html",
                controller: "venueGetCtrl"
            })
            .state("venueDetails", {
                url: "/venueDetails",
                templateUrl: "venue/venueDetails.html",
                controller: "venueDetailCtrl"
            })
            .state("editVenueDetails", {
                url: "/editVenueDetails",
                templateUrl: "venue/venueDetailsEdit.html",
                controller: "editCtrl"
            })
            .state("batchList", {
                url: "/batchList",
                templateUrl: "batch/batchlist.html",
                controller: "myListCtrl"
            })
            .state("batchDetails", {
                url: "/batchDetails",
                templateUrl: "batch/batchdetails.html",
                controller: "batchCtrl"
            })
            .state("studentDetails", {
                url: "/studentDetails",
                templateUrl: "student/stdtwo.html",
                controller: ""
            })
            .state("studentData", {
                url: "/studentData",
                templateUrl: "student/stdone.html",
                controller: ""
            })
            .state("trainerDetails", {
                url: "/trainerDetails",
                templateUrl: "trainer/trainerDetails.html",
                controller: "trainerCtrl"
            })
            .state("index", {
                url: "/index",
                templateUrl: "index.html",
                controller: ""
            })
            .state("editTrainer", {
                url: "/editTrainer",
                templateUrl: "trainer/traineredit.html",
                controller: "trainerCtrl"
            })
    });

This my app.js file .


问:
How to achieve Asynchrony instead of Parallelism in F#
(Sticking to a common example with async fetch of many web pages)

How would I spin off multiple (hundreds) of web page requests asynchronously, and then wait for all requests to complete before going to the next step?  Async.AsParallel processes a few requests at a time, controlled by number of cores on the CPU.  Grabbing a web page is not a CPU-bound operation.  Not satisfied with the speedup of Async.AsParallel, I am looking for alternatives.

I tried to connect the dots between Async.StartAsTask and Task[].WaitAll.  Instinctively, I wrote the following code, but it does not compile.

```<code>let processItemsConcurrently (items : int seq) =
  let tasks = items |> Seq.map (fun item -> Async.StartAsTask(fetchAsync item))
  Tasks.Task.WaitAll(tasks)
</code>```

How would you approach this?

答: Using the Reactive Extensions for .NET combined with F#, you can write a very elegant solution - check out the sample at http://blog.paulbetts.org/index.php/2010/11/16/making-async-io-work-for-you-reactive-style/ (this uses C#, but using F# is easy too; the key is using the Begin/End methods instead of the sync method, which even if you can make it compile, it will block up n ThreadPool threads unnecessarily, instead of the Threadpool just picking up completion routines as they come in)

ContentLicense: CC BY-SA 2.5

Body:
(Sticking to a common example with async fetch of many web pages)

How would I spin off multiple (hundreds) of web page requests asynchronously, and then wait for all requests to complete before going to the next step?  Async.AsParallel processes a few requests at a time, controlled by number of cores on the CPU.  Grabbing a web page is not a CPU-bound operation.  Not satisfied with the speedup of Async.AsParallel, I am looking for alternatives.

I tried to connect the dots between Async.StartAsTask and Task[].WaitAll.  Instinctively, I wrote the following code, but it does not compile.

let processItemsConcurrently (items : int seq) =
  let tasks = items |> Seq.map (fun item -> Async.StartAsTask(fetchAsync item))
  Tasks.Task.WaitAll(tasks)

How would you approach this?


问:
Proguard doesnt obfuscate Class name, only methods are obfuscated
I try using Proguard in android studio, but seems like Proguard is not obfuscating the class name, for example, my app structure, and the config:

and config

but when i try trigger the exception in the app:

the exception is listed in ADB console:

only the methods are obfuscated, the MainActivity.class is not

答:
I was facing the same problems,

After updating my Android plugin for Gradle, Proguard stop obfuscating my utility and other class files.

After few searching, I found that Android studio gradle now uses newer version of Proguard.

And according to this stack-overflow answer, which stated that:
proguard automatically add rules specific for android/google package.

Therefore, After few rule changes in my app, Proguard obfuscated the class names again.

Old proguard-rules.pro:

```<code>#support-v4
#@link https://stackoverflow.com/questions/18978706/obfuscate-android-support-v7-widget-gridlayout-issue
-dontwarn android.support.v4.**
-keep class android.support.v4.** { *; }
-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }

#support-v7
-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
#https://stackoverflow.com/a/34895791/4754141
-keep class !android.support.v7.view.menu.**
-keep interface android.support.v7.* { *; }

#support design
#@link https://stackoverflow.com/a/31028536
-dontwarn android.support.design.**
-keep class android.support.design.** { *; }
-keep interface android.support.design.** { *; }
-keep public class android.support.design.R$* { *; }

#error : Note: the configuration refers to the unknown class 'com.google.vending.licensing.ILicensingService'
#solution : @link https://stackoverflow.com/a/14463528
-dontnote com.google.vending.licensing.ILicensingService
-dontnote **ILicensingService

#updating to Gradle 2.14.1 caused error :         https://stackoverflow.com/q/17141832/4754141
-keepattributes EnclosingMethod

#render script
#@link https://stackoverflow.com/questions/22161832/renderscript-support-library-crashes-on-x86-devices
-keepclasseswithmembernames class * { native <methods>; }
-keep class android.support.v8.renderscript.** { *; }
</code>```

New proguard-rules.pro:

```<code>#https://stackoverflow.com/a/41901653/4754141
#https://stackoverflow.com/a/23840049/4754141
-keep class android.support.** { *; }
-keep interface android.support.** { *; }
</code>```

Body:
I was facing the same problems,

After updating my Android plugin for Gradle, Proguard stop obfuscating my utility and other class files.

After few searching, I found that Android studio gradle now uses newer version of Proguard.

And according to this stack-overflow answer, which stated that:
proguard automatically add rules specific for android/google package.

Therefore, After few rule changes in my app, Proguard obfuscated the class names again.

Old proguard-rules.pro:

#support-v4
#@link https://stackoverflow.com/questions/18978706/obfuscate-android-support-v7-widget-gridlayout-issue
-dontwarn android.support.v4.**
-keep class android.support.v4.** { *; }
-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }

#support-v7
-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
#https://stackoverflow.com/a/34895791/4754141
-keep class !android.support.v7.view.menu.**
-keep interface android.support.v7.* { *; }

#support design
#@link https://stackoverflow.com/a/31028536
-dontwarn android.support.design.**
-keep class android.support.design.** { *; }
-keep interface android.support.design.** { *; }
-keep public class android.support.design.R$* { *; }

#error : Note: the configuration refers to the unknown class 'com.google.vending.licensing.ILicensingService'
#solution : @link https://stackoverflow.com/a/14463528
-dontnote com.google.vending.licensing.ILicensingService
-dontnote **ILicensingService

#updating to Gradle 2.14.1 caused error :         https://stackoverflow.com/q/17141832/4754141
-keepattributes EnclosingMethod

#render script
#@link https://stackoverflow.com/questions/22161832/renderscript-support-library-crashes-on-x86-devices
-keepclasseswithmembernames class * { native <methods>; }
-keep class android.support.v8.renderscript.** { *; }

New proguard-rules.pro:

#https://stackoverflow.com/a/41901653/4754141
#https://stackoverflow.com/a/23840049/4754141
-keep class android.support.** { *; }
-keep interface android.support.** { *; }


问:
Java Testing for Maps
I've created a List<Map<String, String>> for a source file.  I've succeeded in creating a Map with the header values as keys and the information below them as values.  I've tested and verified everything in that method works.

In my next method I've implemented an iterator that will grab the next mapping for processing in a different class.  I'm trying to test to make sure that it's doing what I think it's doing and to verify what I want it to do.

Here's the code of the method:

```<code>  public Map contact(List<Map<String, String>> list) {
return list.iterator().next();
}
</code>```

And here's my test code in the testing class:

```<code>  @Test
public void contact() throws Exception {

List<Map<String, String>> list = this.main.sourceToMap(source1.readLine());
Map nextContact = this.main.contact(list);

System.out.println(list.get(0));

Assert.assertEquals(nextContact,
    "zip=70116, address=6649 N Blue Gum St, city=New Orleans, " +
        "web=http://www.bentonjohnbjr.com, company_name=\"Benton, John B Jr\", " +
        "county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, " +
        "email=jbutt@gmail.com, phone1=504-621-8927");
}
</code>```

Finally, here's the error i'm getting:

java.lang.AssertionError: Expected :{zip=70116, address=6649 N Blue Gum St,city=New Orleans, web=http://www.bentonjohnbjr.com, company_name="Benton, John B Jr", county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, email=jbutt@gmail.com, phone1=504-621-8927}

Actual :zip=70116, address=6649 N Blue Gum St, city=New Orleans, web=http://www.bentonjohnbjr.com, company_name="Benton, John B Jr", county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, email=jbutt@gmail.com, phone1=504-621-8927

The expected and actual are exactly the same with one one difference.  A "{ }" is in front and behind the string.

I think it's because it's expecting a Map instead of a String but I can't figure out what to type in to make it a Map instead of a string.

This is an assignment but not THE assignment.  This is just one small test that i'm trying to prove before moving on.

Thanks!  :D

答:
You assertion is comparing a Map with a String. This fails of course, because the two aren't even the same type. In the error message you see a textual representation of your nextContact object. This seems to be created by invoking the toString() method of Map, which produces the result with the {} around the content.

To fix this you should compare the actual values in the map, e.g.

```<code>Assert.assertEquals(nextContact.get("zip"), "70116");
</code>```

Title: Java Testing for Maps

Body:
I've created a List<Map<String, String>> for a source file.  I've succeeded in creating a Map with the header values as keys and the information below them as values.  I've tested and verified everything in that method works.

In my next method I've implemented an iterator that will grab the next mapping for processing in a different class.  I'm trying to test to make sure that it's doing what I think it's doing and to verify what I want it to do.

Here's the code of the method:

  public Map contact(List<Map<String, String>> list) {
return list.iterator().next();
}

And here's my test code in the testing class:

  @Test
public void contact() throws Exception {

List<Map<String, String>> list = this.main.sourceToMap(source1.readLine());
Map nextContact = this.main.contact(list);

System.out.println(list.get(0));

Assert.assertEquals(nextContact,
    "zip=70116, address=6649 N Blue Gum St, city=New Orleans, " +
        "web=http://www.bentonjohnbjr.com, company_name=\"Benton, John B Jr\", " +
        "county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, " +
        "email=jbutt@gmail.com, phone1=504-621-8927");
}

Finally, here's the error i'm getting:

java.lang.AssertionError: Expected :{zip=70116, address=6649 N Blue Gum St,city=New Orleans, web=http://www.bentonjohnbjr.com, company_name="Benton, John B Jr", county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, email=jbutt@gmail.com, phone1=504-621-8927}

Actual :zip=70116, address=6649 N Blue Gum St, city=New Orleans, web=http://www.bentonjohnbjr.com, company_name="Benton, John B Jr", county=Orleans, phone2=504-845-1427, last_name=Butt, state=LA, first_name=James, email=jbutt@gmail.com, phone1=504-621-8927

The expected and actual are exactly the same with one one difference.  A "{ }" is in front and behind the string.

I think it's because it's expecting a Map instead of a String but I can't figure out what to type in to make it a Map instead of a string.

This is an assignment but not THE assignment.  This is just one small test that i'm trying to prove before moving on.

Thanks!  :D

Body:
You assertion is comparing a Map with a String. This fails of course, because the two aren't even the same type. In the error message you see a textual representation of your nextContact object. This seems to be created by invoking the toString() method of Map, which produces the result with the {} around the content.

To fix this you should compare the actual values in the map, e.g.

Assert.assertEquals(nextContact.get("zip"), "70116");


问:
Update a $scope object from run function in AngularJS
I have my notification listener in the run function. When a notification is received I need to update a object present in $scope with a parameter present in notification object.

```<code>angular.module('app', ['ionic', 'chatsCtrl'])
.run(function($state, $ionicPlatform) {
  window.FirebasePlugin.onNotificationOpen(function(notification) {
    // Need to append this notification.parameter to a scope variable present in a controller
  }
}
.controller('chatsCtrl', function($scope) {
  // $scope.chats
});
</code>```

How can I go about doing this? I don't want to use $rootScope object as $scope.chat object will get very heavy.

Thanks

答:
you can't call scope variables/functions inside run block. since you don't want to use rootscope my suggestion is to create a service and assign values to a particular method in that service from the run block. Then get that value from the controller using the same service.

```<code>angular.module('app', ['ionic', 'chatsCtrl'])
.run(function($state, $ionicPlatform) {
  window.FirebasePlugin.onNotificationOpen(function(notification) {
     sampleService.setData(notification)
  }
}
.controller('chatsCtrl', function($scope,sampleService) {
   $scope.chats =  sampleService.getData()
});
.factory('sampleService', function() {
   var data;
   return {
     getData : function(){ return data},
     setData: function(param){ data = param},
   }
});
</code>```

Body:
I have my notification listener in the run function. When a notification is received I need to update a object present in $scope with a parameter present in notification object.

angular.module('app', ['ionic', 'chatsCtrl'])
.run(function($state, $ionicPlatform) {
  window.FirebasePlugin.onNotificationOpen(function(notification) {
    // Need to append this notification.parameter to a scope variable present in a controller
  }
}
.controller('chatsCtrl', function($scope) {
  // $scope.chats
});

How can I go about doing this? I don't want to use $rootScope object as $scope.chat object will get very heavy.

Thanks

Body:
you can't call scope variables/functions inside run block. since you don't want to use rootscope my suggestion is to create a service and assign values to a particular method in that service from the run block. Then get that value from the controller using the same service.

angular.module('app', ['ionic', 'chatsCtrl'])
.run(function($state, $ionicPlatform) {
  window.FirebasePlugin.onNotificationOpen(function(notification) {
     sampleService.setData(notification)
  }
}
.controller('chatsCtrl', function($scope,sampleService) {
   $scope.chats =  sampleService.getData()
});
.factory('sampleService', function() {
   var data;
   return {
     getData : function(){ return data},
     setData: function(param){ data = param},
   }
});


答:
You have used $images as your variable name when passing the data to the view. This results in blade creating a variable called $$images.

```<code>return view('admin',[ 'images' => $images]);
</code>```

will result in the view creating a variable called $images

Title: Laravel: Undefined variable in blade view

Body:
You have used $images as your variable name when passing the data to the view. This results in blade creating a variable called $$images.

return view('admin',[ 'images' => $images]);

will result in the view creating a variable called $images


问:
Angular 2: Redirect on page load
When my Angular 2 (v2.4) application loads I am trying to redirect the user to a certain page regardless of the URL they have entered. For example, if the user loads the app using http://www.myapp.com/somepage or http://www.myapp.com/anotherpage the app will automatically redirect to http://www.myapp.com/entrypage.

To this I have the following code in my AppComponent (which is the first component loaded):

```<code>export class AppComponent implements OnInit {

    constructor(private router: Router) {

    }

    ngOnInit() {
        console.log(this.router);
        this.router.navigateByUrl("/", { skipLocationChange: true });
    }

}
</code>```

However when the app loads the redirect is not working. It appears to quickly redirect before going back to the original requested route.

How can I get this working? Is there a "correct" way to get this working?

JT

答: Why don't you set your application routes in app.routing.ts ? You can set default value for all urls there, regardless of the URL they have entered.</p>

Title: Angular 2: Redirect on page load

Body:
When my Angular 2 (v2.4) application loads I am trying to redirect the user to a certain page regardless of the URL they have entered. For example, if the user loads the app using http://www.myapp.com/somepage or http://www.myapp.com/anotherpage the app will automatically redirect to http://www.myapp.com/entrypage.

To this I have the following code in my AppComponent (which is the first component loaded):

export class AppComponent implements OnInit {

    constructor(private router: Router) {

    }

    ngOnInit() {
        console.log(this.router);
        this.router.navigateByUrl("/", { skipLocationChange: true });
    }

}

However when the app loads the redirect is not working. It appears to quickly redirect before going back to the original requested route.

How can I get this working? Is there a "correct" way to get this working?

JT


答:
I'm not an F# guy, but from a pure .NET perspective what you're looking for is TaskFactory::FromAsync where the asynchronous call you'd be wrapping in a Task would be something like HttpRequest::BeginGetResponse. You could also wrap up the EAP model that WebClient exposes using a TaskCompletionSource. More on both of these topics here on MSDN.

Hopefully with this knowledge you can find the nearest native F# approach to accomplish what you're trying to do.

Title: How to achieve Asynchrony instead of Parallelism in F#


问:
WCF channelfactory with settings from the config file?
I have a server&client solution that are using WCF. The client will ask a service about the URL to an active server at runtime and to be able to set this I use ChannelFactory. I however still needs to use all other WCF settings from the config file. This is how I do it :

```<code>var clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

            var address = string.Empty;
            for(int i = 0; i < clientSection.Endpoints.Count; i++)
            {
                if(clientSection.Endpoints[i].Name == endpointConfigurationName)
                {
                    var endpointAddress = new EndpointAddress(clientSection.Endpoints[i].Address.ToString());
                    var netHttpBinding = new NetHttpBinding(clientSection.Endpoints[i].BindingConfiguration);
                    var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), netHttpBinding, endpointAddress);

                    var channelFactory = new ChannelFactory<T>(serviceEndpoint);

                    break;
                }
            }
</code>```

The problem is that I got 2 BehaviorExtensions that are used by some of the endpoints like this.

```<code><services>
<endpoint binding="netHttpBinding" behaviorConfiguration="protoEndpointBehavior" address="BinaryHttpProto" bindingNamespace="http://MyApp.ServiceContracts/2007/11" contract="MyApp.ServiceContracts.IMyAppClientService" />
</services>

<behaviors>
<endpointBehaviors>
        <behavior name="protoEndpointBehavior">
          <protobuf />
        </behavior>
      </endpointBehaviors>
    </behaviors>

<extensions>
      <behaviorExtensions>
        <add name="protobuf" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67" />
      </behaviorExtensions>
    </extensions>
</code>```

The question is how I read this from the clientSection.Endpoints? and sets it on the channelFactory? I know that I could create then manually like this :

```<code>serviceEndpoint.EndpointBehaviors.Add(new ProtoEndpointBehavior());
            serviceEndpoint.EndpointBehaviors.Add(new CustomMessageInspectorBehavior());
</code>```

But then this will be a hard coded static and it will apply to all endpoints, I need to be able to change it from the config.

答: I hade to create everything in code, a mixed solution was no good, not in my case where I use alot of custom stuff.</p>

Body:
I have a server&client solution that are using WCF. The client will ask a service about the URL to an active server at runtime and to be able to set this I use ChannelFactory. I however still needs to use all other WCF settings from the config file. This is how I do it :

var clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

            var address = string.Empty;
            for(int i = 0; i < clientSection.Endpoints.Count; i++)
            {
                if(clientSection.Endpoints[i].Name == endpointConfigurationName)
                {
                    var endpointAddress = new EndpointAddress(clientSection.Endpoints[i].Address.ToString());
                    var netHttpBinding = new NetHttpBinding(clientSection.Endpoints[i].BindingConfiguration);
                    var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), netHttpBinding, endpointAddress);

                    var channelFactory = new ChannelFactory<T>(serviceEndpoint);

                    break;
                }
            }

The problem is that I got 2 BehaviorExtensions that are used by some of the endpoints like this.

<services>
<endpoint binding="netHttpBinding" behaviorConfiguration="protoEndpointBehavior" address="BinaryHttpProto" bindingNamespace="http://MyApp.ServiceContracts/2007/11" contract="MyApp.ServiceContracts.IMyAppClientService" />
</services>

<behaviors>
<endpointBehaviors>
        <behavior name="protoEndpointBehavior">
          <protobuf />
        </behavior>
      </endpointBehaviors>
    </behaviors>

<extensions>
      <behaviorExtensions>
        <add name="protobuf" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67" />
      </behaviorExtensions>
    </extensions>

The question is how I read this from the clientSection.Endpoints? and sets it on the channelFactory? I know that I could create then manually like this :

serviceEndpoint.EndpointBehaviors.Add(new ProtoEndpointBehavior());
            serviceEndpoint.EndpointBehaviors.Add(new CustomMessageInspectorBehavior());

But then this will be a hard coded static and it will apply to all endpoints, I need to be able to change it from the config.


问:
how to stop ngOnChanges Called before ngOnInit()
In my angular application, I came up with a situation where ngOnchanges should only be called when the inputs are bound to changes. So, is there a way to stop the execution of ngOnChanges before ngOnInit. Is there a way to accomplish this?
Thanks in Advance.</p>

答:
You cannot prevent this behavior, but you can:

Use a Subject :

class Foo implements OnChanges,OnInit,OnDestroy{

  onChanges = new Subject<SimpleChanges>();

  ngOnInit(){
    this.onChanges.subscribe((data:SimpleChanges)=>{
      // only when inited
    });
  }
  ngOnDestroy(){
    this.onChanges.complete();
  }

  ngOnChanges(changes:SimpleChanges){
    this.onChanges.next(changes);
  }

}
```

<h3>Use a boolean property:</h3>

<pre class="lang-js prettyprint-override"><code>class Foo implements OnChanges,OnInit{

  initialized=false;

  ngOnInit(){
    // do stuff
    this.initialized = true;
  }

  ngOnChanges(changes:SimpleChanges){
    if(this.initialized){
      // do stuff when ngOnInit has been called
    }
  }

}
</code>```

Use the SimpleChanges API

You can also check the SimpleChange.isFirstChange() method :

isFirstChange() : boolean
  Check whether the new value is the first value assigned.

class Foo implements OnChanges,OnInit{

  @Input()
  bar:any;

  ngOnInit(){
    // do stuff
  }

  ngOnChanges(changes:SimpleChanges){
    if(!changes["bar"].isFirstChange()){
      // do stuff if this is not the initialization of "bar"
    }
  }

}
```

Body:
You cannot prevent this behavior, but you can:

Use a Subject :

class Foo implements OnChanges,OnInit,OnDestroy{

  onChanges = new Subject<SimpleChanges>();

  ngOnInit(){
    this.onChanges.subscribe((data:SimpleChanges)=>{
      // only when inited
    });
  }
  ngOnDestroy(){
    this.onChanges.complete();
  }

  ngOnChanges(changes:SimpleChanges){
    this.onChanges.next(changes);
  }

}

Use a boolean property:

class Foo implements OnChanges,OnInit{

  initialized=false;

  ngOnInit(){
    // do stuff
    this.initialized = true;
  }

  ngOnChanges(changes:SimpleChanges){
    if(this.initialized){
      // do stuff when ngOnInit has been called
    }
  }

}

Use the SimpleChanges API

You can also check the SimpleChange.isFirstChange() method :

isFirstChange() : boolean
  Check whether the new value is the first value assigned.

class Foo implements OnChanges,OnInit{

  @Input()
  bar:any;

  ngOnInit(){
    // do stuff
  }

  ngOnChanges(changes:SimpleChanges){
    if(!changes["bar"].isFirstChange()){
      // do stuff if this is not the initialization of "bar"
    }
  }

}


问:
MySQL Replication - one website, many servers, different continents
Consider a reasonably large website (2M+ pageviews / m, lots of users) with 2 frontend servers: one front server in the US, and one in Europe. Two dedicated URL bring the visitors on one of the server, one in the french language, the other one in english. Both sites share exactly the same data.

What would be the most cost effective solution? (DB used at my company: MySQL)

1/ A single Master server on Amazon EC2 (US), and slaves on the frontend servers?

Advantages: no master-master rep, meaning no risk of data conflict with autoincrement and duplicates on unique columns, etc..

Drawbacks: The lag! Won't there be too much lagging for writing in the US when you are in Europe?
Another drawback could be the lack of quick n dirty solution in case the master dies. And what about having slaves on same server as front?

2/ Two Amazon EC2 instances, one in the US, one in Europe, acting as master-master replication servers. Plus two slaves on each of the frontends?

Adv: Speed, and security of data. Of course there is no load balancer, but making a hack to switch the master to the other one seems pretty trivial.

Drwbcks: Price. And the risk of corruption on the DB

3/ Any other solution ?

As it is my first time working with servers in 2 continents, I would really appreciate learning from you experience in that area, including MySQL or not, including EC2 or not.

Thanks
Marshall

答:
As usual, what I'm about to say depends on your app, how it uses the database, etc. You need to ask yourself:

If you're using off the shelf software, what have other people done in this situation?

Does the app need to work on the entire dataset, or can you partition?

Is your app built to handle multi-master replication (usually means uses autoincrement pk's)

What are the chances of update/delete collisions? What are the costs?

What's the read:write ratio? What's the nature of the writes? Are they typically update or append operations?

I'm assuming the french server is in Europe, while the English server is in the US? If you can partition your data so that the french site uses one DB and the english site uses the other, you're better off. Even if both sites access both DB's, since you don't have to worry about collisions. You can even run two mysql instances on each master server and do multimaster replication for both.

If you can't partition, I'd probably go with #2, but I'd designate one of the machines as the 'true' master and send all the writes to it to help avoid data clobber. This way it's easy to switch in a pinch.

If you're cost sensitive and you're going to run replicas on your front end servers anyway, just run the master databases on the front end servers. You can always pull it off later. Replicas can often have higher CPU/IO costs than masters taking the same read load: they have to execute their writes in serial, which can really screw things up.

Also, don't use m1.small instances for your DB. Or at least keep an eye on your performance. m1.smalls are significantly under powered, and if you watch top, you'll notice a significant percentage of your CPU time being stolen by the hypervisor. I recommend c1.medium's.

OwnerDisplayName: marshallcooper

OwnerDisplayName: Gary Richardson


问:
boost asio multithreaded tcp server with synchronous I/O on a given thread
Basically, what I'm trying to achieve is to implement a generic multithreaded TCP server that can handle arbitrary requests for usage by 2 different servers with slightly different needs.

My requirements are:

A request cannot begin to be processed until an entire initial request has been received. (Essentially, I have a request header of a fixed size that among other things, includes the size of the entire request).

Handling a request may result in multiple response messages to the requesting client. I.E., normally, requests can be handled in a single response, but at times, in response to long running database transactions, I need to ping back to the client, letting them know that I'm still working and to not time out the connection.

To achieve this, I've been following fairly closely the HTTP server example #2 from boost v1.44. In general, the example has worked for simple cases. What I've noticed is that when I scale up to handling multiple requests concurrently, the changes I've made have somehow resulted in all request being handled serially, by a single thread. Obviously, I'm doing something wrong.

I cannot post the entirety of the actual code I'm using, due to employer restrictions, but suffice it to say, I've kept the async calls to accept new connections, but have replaced the async read/writes with synchronous calls. If there are specific pieces that you think you need to see, I can see what I can do.

Essentially, what I'm looking for are pointers in how to use boost::asio for a multithreaded TCP server where individual connections are handled by a single thread with synchronous I/O. Again, keep in mind, my abstraction is based upon the http server example #2 (one io_service per CPU), but I am flexible to altern

答:
If you are doing lots of synchronous I/O, your concurrency is limited to the number of threads you have. I would suggest having one io_service for all your asynchronous I/O (ie: all the comms, timers) as you have now, and then decide on how to deal with the synchronous I/O.

For the synchronous I/O you need to decide what your peak concurrency will be. Because it is synchronous and it is I/O, you will want more threads that CPUs, and the decision will be based on how much I/O concurrency you want. Use a separate io_service, and then use io_service::dispatch() to distribute work into the threads doing the synchronous workload.

Doing it this way avoids the problem of a blocking I/O call stopping processing on other asynchronous events.


问:
Yarn using error: how to use yarn on git bash
After installed the yarn dependency management by npm , and I have got the success info on cmd version 0.21.3.
When I turn on the git bash to use yarn command, failed with those errors:</p>

```<code>  module.js:471
    throw err;
    ^
Error: Cannot find module 'D:\c\Program Files (x86)\Yarn\bin\yarn.js'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
</code>```

答:
Try the npm link command to create the symlink to your yarn module. You can use the below command.

```<code>npm link yarn
</code>```

After that try executing the yarn command in your git bash.

Hope this helps!

Body:
After installed the yarn dependency management by npm , and I have got the success info on cmd version 0.21.3.
When I turn on the git bash to use yarn command, failed with those errors:

  module.js:471
    throw err;
    ^
Error: Cannot find module 'D:\c\Program Files (x86)\Yarn\bin\yarn.js'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3

Body:
Try the npm link command to create the symlink to your yarn module. You can use the below command.

npm link yarn

After that try executing the yarn command in your git bash.

Hope this helps!


问:
Windows, XAMPP, PHP 7 and opcache
I've installed latest XAMPP server with PHP 7 (update: checked also PHP 7.1) (on my Windows 10 system). Wanted to use opcache, so I enabled it in php.ini.

```<code>[opcache]
zend_extension=php_opcache.dll
opcache.enable=1
opcache.enable_cli=0
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
</code>```

With that change now, and with almost every page refresh, I'm getting this error from Apache:

```<code>AH00428: Parent: child process 3748 exited with status 3221226356 -- Restarting.
</code>```

So, page is loading, and loading... waiting to Apache start again. When I'm turning opcache off (by setting opcache.enable=0), Apache is not restarting and everything works fine (omitting the slower web application topic, of course).

Everything works fine while loading app on XAMPP having PHP 5.6 with enabled opcache.

EDIT (added GIF image):

As you can see, sometimes page refreshes like it should. But sometimes it's refreshing much longer, and Apache is restarting in that moment.

EDIT:

To be honest, I gave up with this application and working with PHP on Windows (was working on it for around 10 years with PHP <= 5.6). It's very hard/impossible (for now) to make PHP 7.x work on that OS (with Opcache). Decided to go with Ubuntu and server created with Docker. Everything is easier to configure (especially with Docker) and works faster. I advise everyone to do the same ;).

答:
To be honest - do not use xammp. Right now we have a bit better tech stack, to run PHP on Linux servers.
Docker
https://docs.docker.com/docker-for-windows/

Vagrant:
https://www.vagrantup.com/

Both of them are based on linux systems, where most of xammp problems will not have place.

Title: Windows, XAMPP, PHP 7 and opcache

Body:
I've installed latest XAMPP server with PHP 7 (update: checked also PHP 7.1) (on my Windows 10 system). Wanted to use opcache, so I enabled it in php.ini.

[opcache]
zend_extension=php_opcache.dll
opcache.enable=1
opcache.enable_cli=0
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000

With that change now, and with almost every page refresh, I'm getting this error from Apache:

AH00428: Parent: child process 3748 exited with status 3221226356 -- Restarting.

So, page is loading, and loading... waiting to Apache start again. When I'm turning opcache off (by setting opcache.enable=0), Apache is not restarting and everything works fine (omitting the slower web application topic, of course).

Everything works fine while loading app on XAMPP having PHP 5.6 with enabled opcache.

EDIT (added GIF image):

As you can see, sometimes page refreshes like it should. But sometimes it's refreshing much longer, and Apache is restarting in that moment.

EDIT:

To be honest, I gave up with this application and working with PHP on Windows (was working on it for around 10 years with PHP <= 5.6). It's very hard/impossible (for now) to make PHP 7.x work on that OS (with Opcache). Decided to go with Ubuntu and server created with Docker. Everything is easier to configure (especially with Docker) and works faster. I advise everyone to do the same ;).


问:
ModbusTCP - wrong ID in generated frame
I have weird problem. I try to communicate with ifm AY1020 via modbusTCP using libmodbus from PC.

My code looks as follow:

```<code>#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus/modbus.h>

int main()
{
  modbus_t *ctx;
  uint16_t *tab_reg;
  int rc;
  int i;

  ctx = modbus_new_tcp("192.168.1.250", 502);
  modbus_set_debug(ctx, TRUE);

  tab_reg = (uint16_t *) malloc(5 * sizeof(uint16_t));
  memset(tab_reg, 0, 5 * sizeof(uint16_t));

  if (modbus_connect(ctx) == -1)
  {
    fprintf(stderr, "Connection failed: %s\n",modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
  }

  rc = modbus_read_registers(ctx, 3002, 2, tab_reg);

  if (rc == -1)
  {
    fprintf(stderr, "%s\n", modbus_strerror(errno));
    return -1;
  }

  for (i=0; i < rc; i++) {
    printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
   }

  modbus_close(ctx);
  modbus_free(ctx);
}
</code>```

Thanks to debug I was able to get the frame that is generated in  modbus_read_registers function:

[00][01][00][00][00][06][FF][03][0B][BA][00][02]

And I get this

ERROR Gateway path unavailable
  Gateway path unavailable

After analysis you can find that device id in that frame is FF, but according to this error PLC expects 1.

Going further if during debugging I force change this value from FF to 01 everything works fine. It looks like it assign wrong ID.

I would be grateful for any help, advice, solution.

Best,

Paweł

答:
Looking at the Man

You should call modbus_set_slave to set a specific destination device.

TCP

The slave number is only required in TCP if the message must reach a device on a serial network. The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to restore the default value.

Emphasis mine

Your code should be

```<code>modbus_set_slave(ctx, 1);
rc = modbus_read_registers(ctx, 3002, 2, tab_reg);
</code>```

Title: ModbusTCP - wrong ID in generated frame

Body:
I have weird problem. I try to communicate with ifm AY1020 via modbusTCP using libmodbus from PC.

My code looks as follow:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus/modbus.h>

int main()
{
  modbus_t *ctx;
  uint16_t *tab_reg;
  int rc;
  int i;

  ctx = modbus_new_tcp("192.168.1.250", 502);
  modbus_set_debug(ctx, TRUE);

  tab_reg = (uint16_t *) malloc(5 * sizeof(uint16_t));
  memset(tab_reg, 0, 5 * sizeof(uint16_t));

  if (modbus_connect(ctx) == -1)
  {
    fprintf(stderr, "Connection failed: %s\n",modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
  }

  rc = modbus_read_registers(ctx, 3002, 2, tab_reg);

  if (rc == -1)
  {
    fprintf(stderr, "%s\n", modbus_strerror(errno));
    return -1;
  }

  for (i=0; i < rc; i++) {
    printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
   }

  modbus_close(ctx);
  modbus_free(ctx);
}

Thanks to debug I was able to get the frame that is generated in  modbus_read_registers function:

[00][01][00][00][00][06][FF][03][0B][BA][00][02]

And I get this

ERROR Gateway path unavailable
  Gateway path unavailable

After analysis you can find that device id in that frame is FF, but according to this error PLC expects 1.

Going further if during debugging I force change this value from FF to 01 everything works fine. It looks like it assign wrong ID.

I would be grateful for any help, advice, solution.

Best,

Paweł

Body:
Looking at the Man

You should call modbus_set_slave to set a specific destination device.

TCP

The slave number is only required in TCP if the message must reach a device on a serial network. The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to restore the default value.

Emphasis mine

Your code should be

modbus_set_slave(ctx, 1);
rc = modbus_read_registers(ctx, 3002, 2, tab_reg);


答:
If I am understanding your problem correctly, you can solve like this:

```<code>from datetime import datetime,timedelta

def get_daily_slots(start, end, slot, date):
    # combine start time to respective day
    dt = datetime.combine(date, datetime.strptime(start,"%H:%M").time())
    slots = [dt]
    # increment current time by slot till the end time
    while (dt.time() < datetime.strptime(end,"%H:%M").time()):
        dt = dt + timedelta(minutes=slot)
        slots.append(dt)
    return slots

# Some Dummy values
start_time = '9:00'
end_time = '15:00'
slot_time = 30
days = 2
start_date = datetime.now().date()

for i in range(days):
    date_required = datetime.now().date() + timedelta(days=1)
    print get_daily_slots(start=start_time, end=end_time, slot=slot_time, date=date_required)
</code>```

Output will look like:

```<code>[datetime.datetime(2017, 3, 31, 9, 0), datetime.datetime(2017, 3, 31, 9, 30), datetime.datetime(2017, 3, 31, 10, 0), datetime.datetime(2017, 3, 31, 10, 30), datetime.datetime(2017, 3, 31, 11, 0), datetime.datetime(2017, 3, 31, 11, 30), datetime.datetime(2017, 3, 31, 12, 0), datetime.datetime(2017, 3, 31, 12, 30), datetime.datetime(2017, 3, 31, 13, 0), datetime.datetime(2017, 3, 31, 13, 30), datetime.datetime(2017, 3, 31, 14, 0), datetime.datetime(2017, 3, 31, 14, 30), datetime.datetime(2017, 3, 31, 15, 0)]
[datetime.datetime(2017, 3, 31, 9, 0), datetime.datetime(2017, 3, 31, 9, 30), datetime.datetime(2017, 3, 31, 10, 0), datetime.datetime(2017, 3, 31, 10, 30), datetime.datetime(2017, 3, 31, 11, 0), datetime.datetime(2017, 3, 31, 11, 30), datetime.datetime(2017, 3, 31, 12, 0), datetime.datetime(2017, 3, 31, 12, 30), datetime.datetime(2017, 3, 31, 13, 0), datetime.datetime(2017, 3, 31, 13, 30), datetime.datetime(2017, 3, 31, 14, 0), datetime.datetime(2017, 3, 31, 14, 30), datetime.datetime(2017, 3, 31, 15, 0)]
</code>```

Or you can output as you like.

Title: Python create a list of time slot between start time to end time

Body:
I have start_date, end_date, from time, end time, and slot in min details, I need to create a list of time slot as per following expected

import datetime

start_time = '9:00'
end_time = '18:00'
slot_time = 10

# Start date from today to next 5 day
start_date = datetime.datetime.now().date()
end_date = datetime.datetime.now().date() + datetime.timedelta(days=5)

expected output (start_date to end_date = total 5 days)

['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']
['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']
['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']
['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']
['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']

My slot time was not fixed it can be 10, 15, 20, 30 minute base on output list of slot create

If my slot time = 15

Expected output (start_date to end_date = total 5 days)

['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']
['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']
['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']
['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']
['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']

Body:
If I am understanding your problem correctly, you can solve like this:

from datetime import datetime,timedelta

def get_daily_slots(start, end, slot, date):
    # combine start time to respective day
    dt = datetime.combine(date, datetime.strptime(start,"%H:%M").time())
    slots = [dt]
    # increment current time by slot till the end time
    while (dt.time() < datetime.strptime(end,"%H:%M").time()):
        dt = dt + timedelta(minutes=slot)
        slots.append(dt)
    return slots

# Some Dummy values
start_time = '9:00'
end_time = '15:00'
slot_time = 30
days = 2
start_date = datetime.now().date()

for i in range(days):
    date_required = datetime.now().date() + timedelta(days=1)
    print get_daily_slots(start=start_time, end=end_time, slot=slot_time, date=date_required)

Output will look like:

[datetime.datetime(2017, 3, 31, 9, 0), datetime.datetime(2017, 3, 31, 9, 30), datetime.datetime(2017, 3, 31, 10, 0), datetime.datetime(2017, 3, 31, 10, 30), datetime.datetime(2017, 3, 31, 11, 0), datetime.datetime(2017, 3, 31, 11, 30), datetime.datetime(2017, 3, 31, 12, 0), datetime.datetime(2017, 3, 31, 12, 30), datetime.datetime(2017, 3, 31, 13, 0), datetime.datetime(2017, 3, 31, 13, 30), datetime.datetime(2017, 3, 31, 14, 0), datetime.datetime(2017, 3, 31, 14, 30), datetime.datetime(2017, 3, 31, 15, 0)]
[datetime.datetime(2017, 3, 31, 9, 0), datetime.datetime(2017, 3, 31, 9, 30), datetime.datetime(2017, 3, 31, 10, 0), datetime.datetime(2017, 3, 31, 10, 30), datetime.datetime(2017, 3, 31, 11, 0), datetime.datetime(2017, 3, 31, 11, 30), datetime.datetime(2017, 3, 31, 12, 0), datetime.datetime(2017, 3, 31, 12, 30), datetime.datetime(2017, 3, 31, 13, 0), datetime.datetime(2017, 3, 31, 13, 30), datetime.datetime(2017, 3, 31, 14, 0), datetime.datetime(2017, 3, 31, 14, 30), datetime.datetime(2017, 3, 31, 15, 0)]

Or you can output as you like.


问:
Docker-Compose pass IP of services
My docker-compose.yml file looks something like this:

```<code>version: "3"
services:

  redis:
    networks:
      - backend
     ....

  activemq:
    networks:
      - backend
    ....

  mainapp:
    build: .
    networks:
      - backend
    depends_on:
      - redis
      - activemq
    .....

networks:
  backend:
</code>```

My mainapp is a scala app which needs IP of Redis & ActiveMq, how can i pass IP of these services to my mainapp?

答:
You can directly use the name of the service you created, Docker will automatically resolve the corresponding IP.

In your case you can use redis(defined on ln 4) in your configuration instead of the real IP. For example: REDIS_HOST=redis, depending on your configuration structure.

Title: Docker-Compose pass IP of services

Body:
My docker-compose.yml file looks something like this:

version: "3"
services:

  redis:
    networks:
      - backend
     ....

  activemq:
    networks:
      - backend
    ....

  mainapp:
    build: .
    networks:
      - backend
    depends_on:
      - redis
      - activemq
    .....

networks:
  backend:

My mainapp is a scala app which needs IP of Redis & ActiveMq, how can i pass IP of these services to my mainapp?


问:
Transformation taking too long to execute
with the reference to my previous post,here is the link

I have 130000 records in my source. When I tried running the transformation it was still running after 16 hours.

Will increasing the memory heap of spoon.bat script file help reduce the execution time of my transformation? (Changed from PENTAHO_DI_JAVA_OPTIONS="-Xmx256m -XX:MaxPermSize=256m TO PENTAHO_DI_JAVA_OPTIONS="-Xmx2g -XX:MaxPermSize=256m).

What are other ways to increase performance of the transformation?

答:
Avoid sort operation

Avoid Java Script,If possible

One large JavaScript step runs faster than three consecutive smaller steps.So try to combine

Tick "Manage thread priorities" in Misc tab of transformation settings

If possible, don't remove fields in Select Value

Apply no of copies to start
refernce:- http://help.pentaho.com/Documentation/5.4/0L0/0Y0/070/030


问:
How should I set up mutable test fixtures in Spek?
I'm trying to get my head around fixtures in Spek. The Calculator example in the docs is easy to follow, but I'm not sure how to go about structuring setup/teardown when some of the fixtures are stateful. For example, if I was testing a list:

```<code>describe("a list") {
    val list = arrayListOf<Int>() // Only instantiated once

    on("adding an item") {
        list.add(123)

        it("has a size of one") {
            list.size.should.equal(1)
        }
    }

    on("adding 2 items") {
        list.add(1)
        list.add(2)

        it("has a size of 2") {
            list.size.should.equal(2) // Fails, 3 != 2
        }
    }
}
</code>```

From what I understand, in Spek the describe block is only evaluated once, so there is only ever one instance of List. The docs helpfully suggest using test fixtures, but then unhelpfully fail to give an example!

I assume the following doesn't work because Kotlin doesn't understand that Spek will definitely call beforeEachTest before on

```<code>describe("a list") {
    var list : MutableList<Int>

    beforeEachTest {
        list = arrayListOf()
    }

    on("adding an item") {
        list.add(123) // Compile error, list must be initialised
</code>```

I can get around that by making the variable nullable, but then I have to use nullsafe operators everywhere, which sucks because I know it's never null:

```<code>describe("a list") {
    var list : MutableList<Int>? = null

    beforeEachTest {
        list = arrayListOf()
    }

    on("adding an item") {
        list?.add(123) // Bleh
</code>```

This also works, but means that every bit of setup code now needs to be duplicated in two places

```<code>describe("a list") {
    var list = arrayListOf<Int>()

    beforeEachTest {
        list = arrayListOf() // Bleh
    }

    on("adding an item") {
        list.add(123)
</code>```

Excuse me if any of this is obvious, but I'm coming from JUnit world where absolutely everything (bar statics) is torn down and rebuilt before every test, so this all seems rather alien!

答:
If you're using Kotlin 1.1 and Spek 1.1.0 you could use memoized.

```<code>describe("a list") {
    val list by memoized { arrayListOf<Int>() }

    on("adding an item") {
        list.add(123)

        it("has a size of one") {
            list.size.should.equal(1)
        }
    }

    on("adding 2 items") {
        list.add(1)
        list.add(2)

        it("has a size of 2") {
            list.size.should.equal(2)
        }
    }
}
</code>```

Every on will have a unique instance of list. You can pass a CachingMode to memoized to control how Spek caches the values.

CachingMode.TEST (default) - each test will have a unique instance (on here is a special case and treated as a test)

CachingMode.SCOPE - there will be one unique instance, effectively a singleton.

CachingMode.GROUP - each group will have a unique instance.

memoized is still available pre Kotlin 1.1 and at least Spek 1.1.0-beta3, but the syntax is a bit clunky.

```<code>describe("a list") {
    val list = memoized { arrayListOf<Int>() }

    on("adding an item") {
        list().add(123)

        it("has a size of one") {
            list().size.should.equal(1)
        }
    }

    on("adding 2 items") {
        list().add(1)
        list().add(2)

        it("has a size of 2") {
            list().size.should.equal(2)
        }
    }
}
</code>```

Body:
I'm trying to get my head around fixtures in Spek. The Calculator example in the docs is easy to follow, but I'm not sure how to go about structuring setup/teardown when some of the fixtures are stateful. For example, if I was testing a list:

describe("a list") {
    val list = arrayListOf<Int>() // Only instantiated once

    on("adding an item") {
        list.add(123)

        it("has a size of one") {
            list.size.should.equal(1)
        }
    }

    on("adding 2 items") {
        list.add(1)
        list.add(2)

        it("has a size of 2") {
            list.size.should.equal(2) // Fails, 3 != 2
        }
    }
}

From what I understand, in Spek the describe block is only evaluated once, so there is only ever one instance of List. The docs helpfully suggest using test fixtures, but then unhelpfully fail to give an example!

I assume the following doesn't work because Kotlin doesn't understand that Spek will definitely call beforeEachTest before on

describe("a list") {
    var list : MutableList<Int>

    beforeEachTest {
        list = arrayListOf()
    }

    on("adding an item") {
        list.add(123) // Compile error, list must be initialised

I can get around that by making the variable nullable, but then I have to use nullsafe operators everywhere, which sucks because I know it's never null:

describe("a list") {
    var list : MutableList<Int>? = null

    beforeEachTest {
        list = arrayListOf()
    }

    on("adding an item") {
        list?.add(123) // Bleh

This also works, but means that every bit of setup code now needs to be duplicated in two places

describe("a list") {
    var list = arrayListOf<Int>()

    beforeEachTest {
        list = arrayListOf() // Bleh
    }

    on("adding an item") {
        list.add(123)

Excuse me if any of this is obvious, but I'm coming from JUnit world where absolutely everything (bar statics) is torn down and rebuilt before every test, so this all seems rather alien!

Body:
If you're using Kotlin 1.1 and Spek 1.1.0 you could use memoized.

describe("a list") {
    val list by memoized { arrayListOf<Int>() }

    on("adding an item") {
        list.add(123)

        it("has a size of one") {
            list.size.should.equal(1)
        }
    }

    on("adding 2 items") {
        list.add(1)
        list.add(2)

        it("has a size of 2") {
            list.size.should.equal(2)
        }
    }
}

Every on will have a unique instance of list. You can pass a CachingMode to memoized to control how Spek caches the values.

CachingMode.TEST (default) - each test will have a unique instance (on here is a special case and treated as a test)

CachingMode.SCOPE - there will be one unique instance, effectively a singleton.

CachingMode.GROUP - each group will have a unique instance.

memoized is still available pre Kotlin 1.1 and at least Spek 1.1.0-beta3, but the syntax is a bit clunky.

describe("a list") {
    val list = memoized { arrayListOf<Int>() }

    on("adding an item") {
        list().add(123)

        it("has a size of one") {
            list().size.should.equal(1)
        }
    }

    on("adding 2 items") {
        list().add(1)
        list().add(2)

        it("has a size of 2") {
            list().size.should.equal(2)
        }
    }
}


问:
How to attach Mpdf output as email attachment with Codeigniter?
In my controller generating pdf layout and then attaching it as Pdf and with a custom filename. Here is the code

```<code>$this->load->library('mpdf');
$mpdf = new Mpdf('L', 'A4', 0, 'Trebuchet MS', 6, 6, 9, 9, 3, 3, 'L');
ob_start();
echo $this->generateFoodReport($inspectionId);
$html = ob_get_contents();
ob_end_clean();
$mpdf->WriteHTML(utf8_encode($html));
$content = chunk_split(base64_encode($mpdf->Output('', 'S')));
$filename = "inspection-report.pdf";

$this->load->library('email');
$this->email->set_mailtype("html");
$this->email->set_newline("\r\n");
$this->email->from($fromMail, $fromName);
$this->email->to($mailTo);
$this->email->subject($subject);
$this->email->attach($content):
$this->email->send();
</code>```

How to attach the file with email.

答:
Send plain PDF buffer to the mail class.

```<code>$content = $mpdf->Output('', 'S');
$this->email->attach($content, 'attachment', $filename, 'application/pdf');
</code>```

See Email Class Codeigniter documentation.

Body:
In my controller generating pdf layout and then attaching it as Pdf and with a custom filename. Here is the code

$this->load->library('mpdf');
$mpdf = new Mpdf('L', 'A4', 0, 'Trebuchet MS', 6, 6, 9, 9, 3, 3, 'L');
ob_start();
echo $this->generateFoodReport($inspectionId);
$html = ob_get_contents();
ob_end_clean();
$mpdf->WriteHTML(utf8_encode($html));
$content = chunk_split(base64_encode($mpdf->Output('', 'S')));
$filename = "inspection-report.pdf";

$this->load->library('email');
$this->email->set_mailtype("html");
$this->email->set_newline("\r\n");
$this->email->from($fromMail, $fromName);
$this->email->to($mailTo);
$this->email->subject($subject);
$this->email->attach($content):
$this->email->send();

How to attach the file with email.

Body:
Send plain PDF buffer to the mail class.

$content = $mpdf->Output('', 'S');
$this->email->attach($content, 'attachment', $filename, 'application/pdf');

See Email Class Codeigniter documentation.


问:
How to perform range comparison for integer in java eg .x>a<y
How to perform range comparison for integer in java eg .x>a

eg . i want to check if my integer a falls between range x and y

a>30 and a<40

Thanks in advance

答:
You said that! You must use the logical AND operator like this:

```<code>if(a > x && a > y)
{
    // do something;
}
</code>```

Hope this helps ;)

Body:
You said that! You must use the logical AND operator like this:

if(a > x && a > y)
{
    // do something;
}

Hope this helps ;)


问:
Remove an 'Equals' symbol from text string
I'm running a WMIC lookup against a series of remote client machines, pulling in Model and serial number.

For /F "tokens=*" %%b in ('wmic /node:%device% computersystem get Model /value^|find "Model"') do Set model=%%b

FOR /F "tokens=*" %%c in ('wmic /node:%device% bios GET serialnumber /value^|find "SerialNumber=" ') do set Serialnumber=%%c

The problem I have is that (for example) %serialnumber% is set to:SerialNumber=CNU8424GP3

I don't want the 'Serialnumber=', I just want the Serial number itself.

The only way I've found of stripping this is:

set SerialNumber=!serialnumber:SerialNumber=!

but this leaves an equals sign at the beginning of the line. So the final output is =CNUBFZXXY, what I would like to do is to remove the leading =, and I haven't been able to.

Any Suggestions?

答:
The snippet below will allow you to remove the first and last character. I've played a trick here and added a matching '=' at the end of the string (NOTE: I could have used any character). I couldn't find a way to get up to the last character, so the trick is to just add on any character at the end of the variable and then strip it with the 1,-1 which means skip the first charcter and the negative value for the right side means 'counting back from the right'.

```<code>set serialnumber=%serialnumber%=
set serialnumber=%serialnumber:1-1%
</code>```

Hope this helps people looking to hack DOS batch scripts in the future. A good short description of string manipulation can be found here:
DOS String Manipulation

Body:
The snippet below will allow you to remove the first and last character. I've played a trick here and added a matching '=' at the end of the string (NOTE: I could have used any character). I couldn't find a way to get up to the last character, so the trick is to just add on any character at the end of the variable and then strip it with the 1,-1 which means skip the first charcter and the negative value for the right side means 'counting back from the right'.

set serialnumber=%serialnumber%=
set serialnumber=%serialnumber:1-1%

Hope this helps people looking to hack DOS batch scripts in the future. A good short description of string manipulation can be found here:
DOS String Manipulation


问:
Postgres Non-overlapping time period using Gist with constraints
I have a twist on the usual "non-overlapping" time periods using Gist

```<code>CREATE TABLE foo(
id serial,
company_id int NOT NULL,
primarylisting boolean NOT NULL,
validrange daterange NOT NULL,
CONSTRAINT foo_primarykey PRIMARY KEY (id)
) WITH ( OIDS=FALSE);
</code>```

I have the table above which has (foreign key) company_ids and I am creating securityids.

Each company can have many securities at any time, but only one security can be the primary security. I suspect its something like the following but can't find an example to follow:

```<code>ALTER TABLE foo ADD CONSTRAINT unique_primarylisting_daterange
EXCLUDE USING gist (company_id WITH =,validrange WITH &&) where primarylisting=1;
</code>```

or

```<code>ALTER TABLE foo ADD CONSTRAINT unique_primarylisting_daterange
EXCLUDE USING gist (company_id WITH =,validrange WITH &&, primarylisting WITH =1);
</code>```

note that it can't be primarylisting WITH = because while I can't have multiple primary securities at any one point, I can have multiple non-primary securities.

thanks

答:
You almost got the right syntax first time.

But WHERE predicate for partial constraints (and indexes) needs to be in parenthesis. Also, you shouldn't compare a BOOLEAN column to 1 (you could use bool_col = TRUE, bool_col IS TRUE or just bool_col):

```<code>ALTER TABLE foo
  ADD CONSTRAINT unique_primarylisting_daterange
  EXCLUDE USING gist (company_id WITH =, validrange WITH &&) WHERE (primarylisting);
</code>```

Body:
I have a twist on the usual "non-overlapping" time periods using Gist

CREATE TABLE foo(
id serial,
company_id int NOT NULL,
primarylisting boolean NOT NULL,
validrange daterange NOT NULL,
CONSTRAINT foo_primarykey PRIMARY KEY (id)
) WITH ( OIDS=FALSE);

I have the table above which has (foreign key) company_ids and I am creating securityids.

Each company can have many securities at any time, but only one security can be the primary security. I suspect its something like the following but can't find an example to follow:

ALTER TABLE foo ADD CONSTRAINT unique_primarylisting_daterange
EXCLUDE USING gist (company_id WITH =,validrange WITH &&) where primarylisting=1;

or

ALTER TABLE foo ADD CONSTRAINT unique_primarylisting_daterange
EXCLUDE USING gist (company_id WITH =,validrange WITH &&, primarylisting WITH =1);

note that it can't be primarylisting WITH = because while I can't have multiple primary securities at any one point, I can have multiple non-primary securities.

thanks

Body:
You almost got the right syntax first time.

But WHERE predicate for partial constraints (and indexes) needs to be in parenthesis. Also, you shouldn't compare a BOOLEAN column to 1 (you could use bool_col = TRUE, bool_col IS TRUE or just bool_col):

ALTER TABLE foo
  ADD CONSTRAINT unique_primarylisting_daterange
  EXCLUDE USING gist (company_id WITH =, validrange WITH &&) WHERE (primarylisting);


问:
Qt Installer Framework: How to add my program to Windows system variable PATH?
After my program installed I need installer to add program path to Windows system variable PATH. How to make this?

Installer must do this not me.

UPD:

And program path must be removed with uninstallation too.

UPD2:

Now I'm trying to do like this:

```<code>function Component()
{
    installer.installationFinished.connect(this, Component.prototype.installationFinishedPageIsShown);
    installer.uninstallationFinished.connect(this, Component.prototype.uninstallationFinishedPageIsShown);
}

Component.prototype.installationFinishedPageIsShown = function()
{
    try {
        if (installer.isInstaller() && installer.status == QInstaller.Success) {
            installer.executeDetached("set", "PATH=%PATH%;@TargetDir@");
        }
    } catch(e) {
        console.log(e);
    }
}

Component.prototype.uninstallationFinishedPageIsShown = function()
{
    try {
        if (installer.isUninstaller() && installer.status == QInstaller.Success) {
            installer.executeDetached("set", "PATH=%PATH:;@TargetDir@=%");
        }
    } catch(e) {
        console.log(e);
    }
}
</code>```

but it doesn't work :(

答:
From the desktop, right click the Computer icon.
Choose Properties from the context menu.
Click the Advanced system settings link.
Click Environment Variables. ...
In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable.</p>

Body:
After my program installed I need installer to add program path to Windows system variable PATH. How to make this?

Installer must do this not me.

UPD:

And program path must be removed with uninstallation too.

UPD2:

Now I'm trying to do like this:

function Component()
{
    installer.installationFinished.connect(this, Component.prototype.installationFinishedPageIsShown);
    installer.uninstallationFinished.connect(this, Component.prototype.uninstallationFinishedPageIsShown);
}

Component.prototype.installationFinishedPageIsShown = function()
{
    try {
        if (installer.isInstaller() && installer.status == QInstaller.Success) {
            installer.executeDetached("set", "PATH=%PATH%;@TargetDir@");
        }
    } catch(e) {
        console.log(e);
    }
}

Component.prototype.uninstallationFinishedPageIsShown = function()
{
    try {
        if (installer.isUninstaller() && installer.status == QInstaller.Success) {
            installer.executeDetached("set", "PATH=%PATH:;@TargetDir@=%");
        }
    } catch(e) {
        console.log(e);
    }
}

but it doesn't work :(


问:
Export an excel file using a variable name in Python
I am new to python, trying to figure out dynamic naming of exported files. Right now, I am exporting an xlsx file in a traditional way:

data_subset.to_csv('Destination/existing_process.csv')

I have a string called 'user_name' and the resultant tuple for every user is exported into an excel file called existing_process. Instead of the name existing_process, I would like to rename the file dynamically using the string user_name.

For instance, for a given user_name 'Matt' I would like the exported file to be named as Matt.csv. Thanks!

答:
Here is the solution:</p>

```<code>inv.name = 'Rem_inv'

dataframe_list = [inv]
for dataframe in dataframe_list:
    dataframe.to_csv(df.name + '.csv')
</code>```

Body:
Here is the solution:

inv.name = 'Rem_inv'

dataframe_list = [inv]
for dataframe in dataframe_list:
    dataframe.to_csv(df.name + '.csv')