问:
golang GC profiling? runtime.mallocgc appears to be top one; then is moving to sync.Pool the solution?
i have an application written in Go is doing message processing, need to pick up message from network (UDP) at a rate of 20K/second (potentially more), and each message can be up to UDP packet's maximum length (64KB-headersize), the program needs to decode this incoming packet and encode into another format and send to another network;

right now on a 24core+64GB RAM machine it runs ok, but occasionally lost some packets, the programming pattern is already following the pipelines using multiple go-routines / channels and it takes 10% of whole machine cpu load; so it has potential to use more CPU% or RAM to handle all 20K/s messages without losing any one; then i started profiling, following this profiling I found in cpu profile the runtime.mallocgc appears the top one, that is garbage collector runtime, I suspect this GC could be the culprit it hangs for a few millisecond (or some microseconds) and lost some packets, and some best practices says switch to sync.Pool might help, but my switch to pool seemingly results more CPU contention and lost even more packets and more often

```<code>(pprof) top20 -cum (sync|runtime)
245.99s of 458.81s total (53.61%)
Dropped 487 nodes (cum <= 22.94s)
Showing top 20 nodes out of 22 (cum >= 30.46s)
      flat  flat%   sum%        cum   cum%
         0     0%     0%    440.88s 96.09%  runtime.goexit
     1.91s  0.42%  1.75%    244.87s 53.37%  sync.(*Pool).Get
    64.42s 14.04% 15.79%    221.57s 48.29%  sync.(*Pool).getSlow
    94.29s 20.55% 36.56%    125.53s 27.36%  sync.(*Mutex).Lock
     1.62s  0.35% 36.91%     72.85s 15.88%  runtime.systemstack
    22.43s  4.89% 41.80%     60.81s 13.25%  runtime.mallocgc
    22.88s  4.99% 46.79%     51.75s 11.28%  runtime.scanobject
     1.78s  0.39% 47.17%     49.15s 10.71%  runtime.newobject
    26.72s  5.82% 53.00%     39.09s  8.52%  sync.(*Mutex).Unlock
     0.76s  0.17% 53.16%     33.74s  7.35%  runtime.gcDrain
         0     0% 53.16%     33.70s  7.35%  runtime.gcBgMarkWorker
         0     0% 53.16%     33.69s  7.34%  runtime.gcBgMarkWorker.func2
</code>```

the use of pool is the standard

```<code>// create this one globally at program init
var rfpool = &sync.Pool{New: func() interface{} { return new(aPrivateStruct); }}

// get
rf := rfpool.Get().(*aPrivateStruct)

// put after done processing this message
rfpool.Put(rf)
</code>```

not sure am I doing wrong?
or wonder what are the other ways could tune the GC to use less CPU%? the go version is 1.8

the list shows a lot of lock contention happened in the pool.getSlow src to pool.go at golang.org

```<code>(pprof) list sync.*.getSlow
Total: 7.65mins
ROUTINE ======================== sync.(*Pool).getSlow in /opt/go1.8/src/sync/pool.go
  1.07mins   3.69mins (flat, cum) 48.29% of Total
         .          .    144:       x = p.New()
         .          .    145:   }
         .          .    146:   return x
         .          .    147:}
         .          .    148:
      80ms       80ms    149:func (p *Pool) getSlow() (x interface{}) {
         .          .    150:   // See the comment in pin regarding ordering of the loads.
      30ms       30ms    151:   size := atomic.LoadUintptr(&p.localSize) // load-acquire
     180ms      180ms    152:   local := p.local                         // load-consume
         .          .    153:   // Try to steal one element from other procs.
      30ms      130ms    154:   pid := runtime_procPin()
      20ms       20ms    155:   runtime_procUnpin()
     730ms      730ms    156:   for i := 0; i < int(size); i++ {
    51.55s     51.55s    157:       l := indexLocal(local, (pid+i+1)%int(size))
     580ms   2.01mins    158:       l.Lock()
    10.65s     10.65s    159:       last := len(l.shared) - 1
      40ms       40ms    160:       if last >= 0 {
         .          .    161:           x = l.shared[last]
         .          .    162:           l.shared = l.shared[:last]
         .       10ms    163:           l.Unlock()
         .          .    164:           break
         .          .    165:       }
     490ms     37.59s    166:       l.Unlock()
         .          .    167:   }
      40ms       40ms    168:   return x
         .          .    169:}
         .          .    170:
         .          .    171:// pin pins the current goroutine to P, disables preemption and returns poolLocal pool for the P.
         .          .    172:// Caller must call runtime_procUnpin() when done with the pool.
         .          .    173:func (p *Pool) pin() *poolLocal {
</code>```

答:
https://golang.org/pkg/sync/#Pool

a free list maintained as part of a short-lived object is not a
  suitable use for a Pool, since the overhead does not amortize well in
  that scenario. It is more efficient to have such objects implement
  their own free list

You may try to set GOGC value to greater then 100.

https://dave.cheney.net/2015/11/29/a-whirlwind-tour-of-gos-runtime-environment-variables

Or, implement your own free list.

http://golang-jp.org/doc/effective_go.html#leaky_buffer

Body:
i have an application written in Go is doing message processing, need to pick up message from network (UDP) at a rate of 20K/second (potentially more), and each message can be up to UDP packet's maximum length (64KB-headersize), the program needs to decode this incoming packet and encode into another format and send to another network;

right now on a 24core+64GB RAM machine it runs ok, but occasionally lost some packets, the programming pattern is already following the pipelines using multiple go-routines / channels and it takes 10% of whole machine cpu load; so it has potential to use more CPU% or RAM to handle all 20K/s messages without losing any one; then i started profiling, following this profiling I found in cpu profile the runtime.mallocgc appears the top one, that is garbage collector runtime, I suspect this GC could be the culprit it hangs for a few millisecond (or some microseconds) and lost some packets, and some best practices says switch to sync.Pool might help, but my switch to pool seemingly results more CPU contention and lost even more packets and more often

(pprof) top20 -cum (sync|runtime)
245.99s of 458.81s total (53.61%)
Dropped 487 nodes (cum <= 22.94s)
Showing top 20 nodes out of 22 (cum >= 30.46s)
      flat  flat%   sum%        cum   cum%
         0     0%     0%    440.88s 96.09%  runtime.goexit
     1.91s  0.42%  1.75%    244.87s 53.37%  sync.(*Pool).Get
    64.42s 14.04% 15.79%    221.57s 48.29%  sync.(*Pool).getSlow
    94.29s 20.55% 36.56%    125.53s 27.36%  sync.(*Mutex).Lock
     1.62s  0.35% 36.91%     72.85s 15.88%  runtime.systemstack
    22.43s  4.89% 41.80%     60.81s 13.25%  runtime.mallocgc
    22.88s  4.99% 46.79%     51.75s 11.28%  runtime.scanobject
     1.78s  0.39% 47.17%     49.15s 10.71%  runtime.newobject
    26.72s  5.82% 53.00%     39.09s  8.52%  sync.(*Mutex).Unlock
     0.76s  0.17% 53.16%     33.74s  7.35%  runtime.gcDrain
         0     0% 53.16%     33.70s  7.35%  runtime.gcBgMarkWorker
         0     0% 53.16%     33.69s  7.34%  runtime.gcBgMarkWorker.func2

the use of pool is the standard

// create this one globally at program init
var rfpool = &sync.Pool{New: func() interface{} { return new(aPrivateStruct); }}

// get
rf := rfpool.Get().(*aPrivateStruct)

// put after done processing this message
rfpool.Put(rf)

not sure am I doing wrong?
or wonder what are the other ways could tune the GC to use less CPU%? the go version is 1.8

the list shows a lot of lock contention happened in the pool.getSlow src to pool.go at golang.org

(pprof) list sync.*.getSlow
Total: 7.65mins
ROUTINE ======================== sync.(*Pool).getSlow in /opt/go1.8/src/sync/pool.go
  1.07mins   3.69mins (flat, cum) 48.29% of Total
         .          .    144:       x = p.New()
         .          .    145:   }
         .          .    146:   return x
         .          .    147:}
         .          .    148:
      80ms       80ms    149:func (p *Pool) getSlow() (x interface{}) {
         .          .    150:   // See the comment in pin regarding ordering of the loads.
      30ms       30ms    151:   size := atomic.LoadUintptr(&p.localSize) // load-acquire
     180ms      180ms    152:   local := p.local                         // load-consume
         .          .    153:   // Try to steal one element from other procs.
      30ms      130ms    154:   pid := runtime_procPin()
      20ms       20ms    155:   runtime_procUnpin()
     730ms      730ms    156:   for i := 0; i < int(size); i++ {
    51.55s     51.55s    157:       l := indexLocal(local, (pid+i+1)%int(size))
     580ms   2.01mins    158:       l.Lock()
    10.65s     10.65s    159:       last := len(l.shared) - 1
      40ms       40ms    160:       if last >= 0 {
         .          .    161:           x = l.shared[last]
         .          .    162:           l.shared = l.shared[:last]
         .       10ms    163:           l.Unlock()
         .          .    164:           break
         .          .    165:       }
     490ms     37.59s    166:       l.Unlock()
         .          .    167:   }
      40ms       40ms    168:   return x
         .          .    169:}
         .          .    170:
         .          .    171:// pin pins the current goroutine to P, disables preemption and returns poolLocal pool for the P.
         .          .    172:// Caller must call runtime_procUnpin() when done with the pool.
         .          .    173:func (p *Pool) pin() *poolLocal {


来源: stackexchange

问:
Filter the query and refresh the recycler view using firebase in android
```<code>@Override
protected void onStart() {
    super.onStart();

    mAuth.addAuthStateListener(mAuthListener);

    FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setTitle(model.getName());
            viewHolder.setDesc(model.getDesc());
            viewHolder.setImage(getApplicationContext(), model.getImage());
            viewHolder.setUsername(model.getUsername());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);
}
</code>```

The above is the code that I use to get the data from the firebase realtime database. How can I change the query (mDatabase in my code) and refresh the recyclerview to filter the data? How to set a new adapter? Please give me some helps.Thank you.

答:
Try this:</p>

```<code>FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

        Product.class,
        R.layout.product_row,
        ProductViewHolder.class,
        mDatabase.orderByChild("KeyName").equalTo("Value") //add this line
)
 mProductList.setAdapter(firebaseRecyclerAdapter);
  firebaseRecyclerAdapter.notifyDataSetChanged();  // also add this line
</code>```

ContentLicense: CC BY-SA 3.0

Body:
@Override
protected void onStart() {
    super.onStart();

    mAuth.addAuthStateListener(mAuthListener);

    FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setTitle(model.getName());
            viewHolder.setDesc(model.getDesc());
            viewHolder.setImage(getApplicationContext(), model.getImage());
            viewHolder.setUsername(model.getUsername());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);
}

The above is the code that I use to get the data from the firebase realtime database. How can I change the query (mDatabase in my code) and refresh the recyclerview to filter the data? How to set a new adapter? Please give me some helps.Thank you.

Body:
Try this:

FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

        Product.class,
        R.layout.product_row,
        ProductViewHolder.class,
        mDatabase.orderByChild("KeyName").equalTo("Value") //add this line
)
 mProductList.setAdapter(firebaseRecyclerAdapter);
  firebaseRecyclerAdapter.notifyDataSetChanged();  // also add this line


问:
Loopback: Event resetPasswordRequest not called after reset
I am trying to tap into the password reset process on Loopback, so I can send an e-mail with the instructions to the user. I created a custom model called 'user' that extends 'User'. Then I added "User.on('resetPasswordRequest'...", but it never gets executed. Please check the console.log on the user.js

model-config.json

```<code>{
...

  "user": {
    "dataSource": "mysqlDs",
    "public": true,
    "options": {
      "emailVerificationRequired": false
    }
  },
...
}
</code>```

user.json

```<code>{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "accessType": "READ",
      "permission": "ALLOW"
    }
  ],
  "methods": []
}
</code>```

user.js

```<code>module.exports = function(User) {

  console.log('It prints this log here.');

  User.on('resetPasswordRequest', function(info) {

    console.log('But it does not print this log here ever.');

    var url = 'http://www.example.com/reset-password';
    var html = 'Click <a href="' + url + '?access_token=' + info.accessToken.id + '">here</a>';
    loopback.Email.send({
      to: info.email,
      from: 'mail@example.com',
      subject: 'My Subject',
      html: html
    }, function() {
      console.log('> sending password reset email to:', info.email);
      if (err) return console.log('> error sending password reset email');
    });
  });

};
</code>```

答:
Don't you simply miss to define a remote method in order to call your code?
This is what I would do:

user.js

```<code>    module.exports = function(User) {

      console.log('It prints this log here.');

      User.resetPasswordRequest = function (info, cb) {

        console.log('But it does not print this log here ever.');

        var url = 'http://www.example.com/reset-password';
        var html = 'Click <a href="' + url + '?access_token=' + info.accessToken + '">here</a>';
        loopback.Email.send({
          to: info.email,
          from: 'mail@example.com',
          subject: 'My Subject',
          html: html
        }, function() {
          console.log('> sending password reset email to:', info.email);
          if (err) {
             cb(err, false);
             return console.log('> error sending password reset email');
          }
          cb(err, true):
        });
      });

    User.remoteMethod('resetPasswordRequest', {
            description: 'Send a mail to an User to permit him to reset his password',
            accepts: {arg: 'info', type: 'object', required: true},
            returns: {arg: 'mailSend', type: 'boolean'},
            http: {verb: 'post'}
        });

};
</code>```

Then, using the Explorer or calling the API via REST while posting a your info json like:

```<code>{
 accessToken: xxx,
 email: xxx
}
</code>```

And don't forget to update your ACLs in user.json so you can call the method from remote:

```<code>{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    },
    {
      "accessType": "READ",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW"
    },
    {
      "accessType": "WRITE",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW"
    },
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW",
      "property": "resetPasswordRequest"
    }
  ],
  "methods": []
}
</code>```

Body:
I am trying to tap into the password reset process on Loopback, so I can send an e-mail with the instructions to the user. I created a custom model called 'user' that extends 'User'. Then I added "User.on('resetPasswordRequest'...", but it never gets executed. Please check the console.log on the user.js

model-config.json

{
...

  "user": {
    "dataSource": "mysqlDs",
    "public": true,
    "options": {
      "emailVerificationRequired": false
    }
  },
...
}

user.json

{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "accessType": "READ",
      "permission": "ALLOW"
    }
  ],
  "methods": []
}

user.js

module.exports = function(User) {

  console.log('It prints this log here.');

  User.on('resetPasswordRequest', function(info) {

    console.log('But it does not print this log here ever.');

    var url = 'http://www.example.com/reset-password';
    var html = 'Click here';
    loopback.Email.send({
      to: info.email,
      from: 'mail@example.com',
      subject: 'My Subject',
      html: html
    }, function() {
      console.log('> sending password reset email to:', info.email);
      if (err) return console.log('> error sending password reset email');
    });
  });

};

Body:
Don't you simply miss to define a remote method in order to call your code?
This is what I would do:

user.js

    module.exports = function(User) {

      console.log('It prints this log here.');

      User.resetPasswordRequest = function (info, cb) {

        console.log('But it does not print this log here ever.');

        var url = 'http://www.example.com/reset-password';
        var html = 'Click <a href="' + url + '?access_token=' + info.accessToken + '">here</a>';
        loopback.Email.send({
          to: info.email,
          from: 'mail@example.com',
          subject: 'My Subject',
          html: html
        }, function() {
          console.log('> sending password reset email to:', info.email);
          if (err) {
             cb(err, false);
             return console.log('> error sending password reset email');
          }
          cb(err, true):
        });
      });

    User.remoteMethod('resetPasswordRequest', {
            description: 'Send a mail to an User to permit him to reset his password',
            accepts: {arg: 'info', type: 'object', required: true},
            returns: {arg: 'mailSend', type: 'boolean'},
            http: {verb: 'post'}
        });

};

Then, using the Explorer or calling the API via REST while posting a your info json like:

{
 accessToken: xxx,
 email: xxx
}

And don't forget to update your ACLs in user.json so you can call the method from remote:

{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    },
    {
      "accessType": "READ",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW"
    },
    {
      "accessType": "WRITE",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW"
    },
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW",
      "property": "resetPasswordRequest"
    }
  ],
  "methods": []
}


问:
Drupal search theme form - Change input type?
For the theme search box used in Drupal, the text-field is as follows:

```<code><input type="text" class="form-text" id="edit-search-theme-form-1">
</code>```

As I am developing a site for mobile, I want to change the input type of the text-field to search.

Would anybody know how to go about making this change?

Thanks, Mark.

答: You would have to do HTML5, which actually has a input type "search", but I don't know what the current HTML5 compatibility state of mobile browsers is. You could try to change the input type with theming.</p>

ContentLicense: CC BY-SA 2.5

Body:
For the theme search box used in Drupal, the text-field is as follows:

<input type="text" class="form-text" id="edit-search-theme-form-1">

As I am developing a site for mobile, I want to change the input type of the text-field to search.

Would anybody know how to go about making this change?

Thanks, Mark.


问:
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.

答:
Your code should be like this

```<code>public function admin() {
    $images = Image::paginate();

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

}

Why you use [ '$images' => $images]. that is the problem.

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:
Your code should be like this

public function admin() {
    $images = Image::paginate();

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

}

Why you use [ '$images' => $images]. that is the problem.


问:
Creating stored procedure in SQL Server 2008 with Begin and End
Example:

```<code>ALTER PROCEDURE [dbo].[SampleTable]
AS
BEGIN
    BEGIN
    WITH 'Test' AS
    (
        SELECT * FROM dario1
        UNION ALL
        SELECT * FROM dario2
        UNION ALL
        SELECT * FROM dario3
    )
    END

    IF select Column1 = 1 FROM Test
    BEGIN
      --another commands.. etc..
    END

    IF select Column1 = 2 FROM Test
    BEGIN
         --another commands.. etc..
    END

    IF select Column1 = 3 FROM Test
    BEGIN
         --another commands.. etc..
    END
END
</code>```

Please don't bother with my codes, this is only just a sample.

My questions are: do the BEGIN and END help to optimize the memory consumption? Even if I have 3 tables and my records are about millions?

I am still confused using BEGIN and END.

Any answer will be appreciated.. :)

答: BEGIN and END are similar to the open braces and closing braces in C# ({}) used to indicate logical code blocks. It doesn't affect memory consumption.

Body:
Example:

ALTER PROCEDURE [dbo].[SampleTable]
AS
BEGIN
    BEGIN
    WITH 'Test' AS
    (
        SELECT * FROM dario1
        UNION ALL
        SELECT * FROM dario2
        UNION ALL
        SELECT * FROM dario3
    )
    END

    IF select Column1 = 1 FROM Test
    BEGIN
      --another commands.. etc..
    END

    IF select Column1 = 2 FROM Test
    BEGIN
         --another commands.. etc..
    END

    IF select Column1 = 3 FROM Test
    BEGIN
         --another commands.. etc..
    END
END

Please don't bother with my codes, this is only just a sample.

My questions are: do the BEGIN and END help to optimize the memory consumption? Even if I have 3 tables and my records are about millions?

I am still confused using BEGIN and END.

Any answer will be appreciated.. :)


问:
How to read .txt file with Chinese characters?
I have a subroutine that reads text files and extracts certain data from them. Here is an example:

```<code>NamePrefix = "Example"
OutputPath = "C:\Example"
DbSize = 65536

LstStr = ""
Dim Success() As Boolean
Dim Value() As Double
ReDim Success(1 to DbSize)
ReDim Value(1 to DbSize)
For ID = 1 to DbSize
  'Read string
    FileName = NamePrefix & Format(ID,"000000") & ".lst"
    FilePath = OutputPath & "\" & FileName
    Open FilePath For Input As 1
    LstStr = Input(LOF(1),1)
    Close 1
  'Extract data
    If InStr(1, LstStr, "SUCCESS") <> 0 Then Success(i) = True Else Success(i) = False
    Pos1 = InStr(1, LstStr, "TH 1 value: ") 'Position varies for each file
    Value(i) = Val(Mid(LstStr, Pos1 + 13, 10)) 'Value in scientific notation
Next ID
</code>```

The use of InStr to locate strings by position works perfectly when there are just alphabets, numbers and symbols. However, sometimes the files contain Chinese characters and the Input function returns an empty string "" to LstStr. I tried to use some other suggested methods but in vain (e.g. Extract text from a text file with Chinese characters using vba). How should I read files with Chinese characters successfully, in a way that I do not need to modify other parts of the code which extract data by position? Thanks!

答:
This would be an alternative way to read the string. Make sure that the .Charset is set to the charset of the file you want to read.

To use ADOBD you will need to add the reference Microsoft ActiveX Data Objects 6.1 Library (Version can be different) in VBA Menu › Extras › References

```<code>Dim adoStream As ADODB.Stream
Set adoStream = New ADODB.Stream

adoStream.Charset = "UTF-8" 'set the correct charset
adoStream.Open
adoStream.LoadFromFile FilePath

LstStr = adoStream.ReadText

adoStream.Close
Set adoStream = Nothing
</code>```

Body:
I have a subroutine that reads text files and extracts certain data from them. Here is an example:

NamePrefix = "Example"
OutputPath = "C:\Example"
DbSize = 65536

LstStr = ""
Dim Success() As Boolean
Dim Value() As Double
ReDim Success(1 to DbSize)
ReDim Value(1 to DbSize)
For ID = 1 to DbSize
  'Read string
    FileName = NamePrefix & Format(ID,"000000") & ".lst"
    FilePath = OutputPath & "\" & FileName
    Open FilePath For Input As 1
    LstStr = Input(LOF(1),1)
    Close 1
  'Extract data
    If InStr(1, LstStr, "SUCCESS") <> 0 Then Success(i) = True Else Success(i) = False
    Pos1 = InStr(1, LstStr, "TH 1 value: ") 'Position varies for each file
    Value(i) = Val(Mid(LstStr, Pos1 + 13, 10)) 'Value in scientific notation
Next ID

The use of InStr to locate strings by position works perfectly when there are just alphabets, numbers and symbols. However, sometimes the files contain Chinese characters and the Input function returns an empty string "" to LstStr. I tried to use some other suggested methods but in vain (e.g. Extract text from a text file with Chinese characters using vba). How should I read files with Chinese characters successfully, in a way that I do not need to modify other parts of the code which extract data by position? Thanks!

Body:
This would be an alternative way to read the string. Make sure that the .Charset is set to the charset of the file you want to read.

To use ADOBD you will need to add the reference Microsoft ActiveX Data Objects 6.1 Library (Version can be different) in VBA Menu › Extras › References

Dim adoStream As ADODB.Stream
Set adoStream = New ADODB.Stream

adoStream.Charset = "UTF-8" 'set the correct charset
adoStream.Open
adoStream.LoadFromFile FilePath

LstStr = adoStream.ReadText

adoStream.Close
Set adoStream = Nothing


问:
Android Close Second activity and move to first activity
I am in Second activity, doing uninstall other app works fine.

But when Uninstall finished, I want to kill the second activity and move to previous(First) activity. I don't Know how to do it.

Please He

```<code>btnUninstall.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri packageURI = Uri.parse("package:" + packageInfo.packageName);
            Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
            startActivityForResult(uninstallIntent, 1);
        }
    });
</code>```

答:
How I Implemented at the time of calling the Uninstall Intent i have saved the package name in a preferences file by using

```<code>SharedPreferences prefs;
prefs.edit().putString(DELETE_PACKAGE_NAME, packageName).commit();
</code>```

And what i have done in OnActivityresult i have just checked whether the application with saved package name still present if it is means user has clicked on Cancel else he clicked Ok.

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

 if(requestCode==DELETE_APP){

    String requestedPackageName=prefs.getString(DELETE_PACKAGE_NAME, "");

    boolean isPresent=GCMIntentService.isAppPresent(requestedPackageName, this);

    if(isPresent){

      //user Clicked on Cancel
    }else{

      //user Clicked on Ok
    }

 }

}
</code>```

Code for Checking the application presence

```<code>public static boolean  isAppPresent(String packageName,Context context) {

  try{
    ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, 0 );
    return true;

} catch( PackageManager.NameNotFoundException e ){

   return false;
}

 }
</code>```

Thanks.

Body:
I am in Second activity, doing uninstall other app works fine.

But when Uninstall finished, I want to kill the second activity and move to previous(First) activity. I don't Know how to do it.

Please He

btnUninstall.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri packageURI = Uri.parse("package:" + packageInfo.packageName);
            Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
            startActivityForResult(uninstallIntent, 1);
        }
    });

Body:
How I Implemented at the time of calling the Uninstall Intent i have saved the package name in a preferences file by using

SharedPreferences prefs;
prefs.edit().putString(DELETE_PACKAGE_NAME, packageName).commit();

And what i have done in OnActivityresult i have just checked whether the application with saved package name still present if it is means user has clicked on Cancel else he clicked Ok.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

 if(requestCode==DELETE_APP){

    String requestedPackageName=prefs.getString(DELETE_PACKAGE_NAME, "");

    boolean isPresent=GCMIntentService.isAppPresent(requestedPackageName, this);

    if(isPresent){

      //user Clicked on Cancel
    }else{

      //user Clicked on Ok
    }

 }

}

Code for Checking the application presence

public static boolean  isAppPresent(String packageName,Context context) {

  try{
    ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, 0 );
    return true;

} catch( PackageManager.NameNotFoundException e ){

   return false;
}

 }

Thanks.


问:
Recognize if not enough resources during timeframe
i need an idea how to solve the following problem.

Lets say i have one group with given timeframe (8:00-12:00) and i can assign resources (people) to it. Each resource can have a custom timeframe (like 9-10, 9-12,8-12 etc.) and could be assigned multiple times.

Tables

Groups

ID,
TITLE,
START_TIME,
END_TIME,
REQUIRED_PEOPLE:INTEGER

PeopleAssignments

ID,
USER_ID,
GROUP_ID,
START_TIME,
END_TIME

Now i have the rule that at any given time during the group timeframe that there have to be like like 4 people assigned. Otherwise i want to get a warning.

I am working with ruby & sql (Postgres) here.

is there an elegant way without iterating through the whole timeframe and checking if count(assignments) > REQUIRED_PEOPLE

答:
In any case you need to query number of assignment in DB. There is no other way to find how many times a group assign to people.

There might be ways to find number of assignment but in the end you have to fire a query to DB.

```<code>@group = Group.find(id)
if @group.people_assignments.count >= REQUIRED_PEOPLE
  pus 'warning'
end
</code>```

You can add extra column in group that hold information how many times that group assign to people. In this way one query to server reduced.

```<code>@group = Group.find(id)
if @group.count_people_assigned >= REQUIRED_PEOPLE
  puts 'warning'
end
</code>```

In second case count_people_assigned is column so no extra query will execute while in first case people_assignments is association so one extra query will fire.

But in second case you have you update group each time you assign group to people. Ultimately extra query. Your choice where you want to reduce query.

My opinion is second case, It will happen rare than first.

Body:
In any case you need to query number of assignment in DB. There is no other way to find how many times a group assign to people.

There might be ways to find number of assignment but in the end you have to fire a query to DB.

@group = Group.find(id)
if @group.people_assignments.count >= REQUIRED_PEOPLE
  pus 'warning'
end

You can add extra column in group that hold information how many times that group assign to people. In this way one query to server reduced.

@group = Group.find(id)
if @group.count_people_assigned >= REQUIRED_PEOPLE
  puts 'warning'
end

In second case count_people_assigned is column so no extra query will execute while in first case people_assignments is association so one extra query will fire.

But in second case you have you update group each time you assign group to people. Ultimately extra query. Your choice where you want to reduce query.

My opinion is second case, It will happen rare than first.


问:
Using XSLT merge 2 XML, which come from PHP transformToXML
I am beginner in PHP, XSLT.  Found solution for transform XML using XSLT:

```<code>$xml = Array2XML::createXML('Document', $result);
$xsl = new DOMDocument;
$xsl->load('Teema.xsl');
$processor = new XSLTProcessor();
$processor->importStyleSheet($xsl);
$results=$processor->transformToXML($xml);
$results=$processor->transformToUri($xml,"NewTeema.xml" );
</code>```

But, what to do if I have 2 or more XMLs?
This $xml is not file, and I dont want to save each xml, like file on server (because it is was converted response json). Any ideas?

答:
In the XSLT you can load additional document using the document() function.

Another possibility is to register a PHP function that loads the file and returns the value or DOM node.

Body:
I am beginner in PHP, XSLT.  Found solution for transform XML using XSLT:

$xml = Array2XML::createXML('Document', $result);
$xsl = new DOMDocument;
$xsl->load('Teema.xsl');
$processor = new XSLTProcessor();
$processor->importStyleSheet($xsl);
$results=$processor->transformToXML($xml);
$results=$processor->transformToUri($xml,"NewTeema.xml" );

But, what to do if I have 2 or more XMLs?
This $xml is not file, and I dont want to save each xml, like file on server (because it is was converted response json). Any ideas?


问:
Connect to Server Db using msql command prompt
I am using mySql command prompt. A username and password is created(root,root), in my local.Now i want to coonect to server db(existing one) which has different username and password.How?

Thanks

答:
At the command line, type the following command, replacing USERNAME with your username:

mysql -u USERNAME -p

At the Enter Password prompt, type your password. When you type the correct password, the mysql> prompt appears.
To display a list of databases, type the following command at the mysql> prompt:

show databases;

To access a specific database, type the following command at the mysql> prompt, replacing DBNAME with the database that you want to access:

use DBNAME;


问:
How to train SVM using python?
I'm trying to train SVM on dataset with only two column like:

1 4.5456436

0 2.4353453

1 3.5435636

1 5.4235354

0 1.4235345

I have tried:

```<code>x = np.array([[1],[0],[1],[1]])
y = np.array([[4.5456436],[2.4353453],[3.5435636],[5.4235354]])

clf = svm.SVC()
clf.fit(y,x)
</code>```

for these lines it works correctly, but the problem occurs when I import the array from dataset file, I got an error:

```<code>ValueError: The number of classes has to be greater than one; got 1
</code>```

although the output and the type in the two cases are the same.

imported data from the dataset code is:

```<code>def read(dir):
    x = []
    y = []
    with open(dir) as f:
        lines = f.readlines()
    for i in range(len(lines)):
        x.append(lines[i][0]);y.append(lines[i][1:])
    x = np.array([[int(i)] for i in x])
    y = np.array([[float(i)] for i in y])
</code>```

any suggestion, thanks in advance.

答:
Posting the comment as answer to just close the question.

The error is that there is only one type of class (label) in target. See, in the example you posted above (x = np.array([[1],[0],[1],[1]])), there are two categories to classify (0 and 1).

But when you import the dataset from file, target has only type of category for all available samples. Please check the arrays loaded from your file.

Title: How to train SVM using python?

Body:
I'm trying to train SVM on dataset with only two column like:

1 4.5456436

0 2.4353453

1 3.5435636

1 5.4235354

0 1.4235345

I have tried:

x = np.array([[1],[0],[1],[1]])
y = np.array([[4.5456436],[2.4353453],[3.5435636],[5.4235354]])

clf = svm.SVC()
clf.fit(y,x)

for these lines it works correctly, but the problem occurs when I import the array from dataset file, I got an error:

ValueError: The number of classes has to be greater than one; got 1

although the output and the type in the two cases are the same.

imported data from the dataset code is:

def read(dir):
    x = []
    y = []
    with open(dir) as f:
        lines = f.readlines()
    for i in range(len(lines)):
        x.append(lines[i][0]);y.append(lines[i][1:])
    x = np.array([[int(i)] for i in x])
    y = np.array([[float(i)] for i in y])

any suggestion, thanks in advance.


问:
How to get each specific value in an array?
I'm looking to be able to extract each 'hire_address' value from the following array and add it to a separate array.

```<code>var addr =
{
   "status":"success",
   "data":[
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};
</code>```

I currently have

```<code>var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);
</code>```

But not having any luck. Any suggestions?

Thank you for the replies.

I now have

```<code>var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);
</code>```

But can't seem to get it to work. Do I need the if statement? I added this because the first item is 'status' and was running into errors if I tried to add a 'hire_address' property of this because it doesn't exists.

答:
You can do it using Array#map()

var addr = {
  "status": "success",
  "data": [{
      "start": "2017-01-26 12:30:00",
      "hire_oucu": "ac2",
      "hire_address": "Glasgow",
      "offer_oucu": "ac1",
      "offer_address": "Glasgow"
    },
    {
      "start": "2017-01-26 12:30:00",
      "hire_oucu": "ac2",
      "hire_address": "Poole",
      "offer_oucu": "ac1",
      "offer_address": "Poole"
    }, {
      "start": "2017-01-26 12:30:00",
      "hire_oucu": "ac2",
      "hire_address": "Hastings",
      "offer_oucu": "ac1",
      "offer_address": "Hastings"
    }, {
      "start": "2017-01-26 12:30:00",
      "hire_oucu": "ac2",
      "hire_address": "London",
      "offer_oucu": "ac1",
      "offer_address": "London"
    }
  ]
};

let myArray = addr.data.map(d => d["hire_address"]);
console.log(myArray);```

Body:
I'm looking to be able to extract each 'hire_address' value from the following array and add it to a separate array.

var addr =
{
   "status":"success",
   "data":[
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};

I currently have

var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);

But not having any luck. Any suggestions?

Thank you for the replies.

I now have

var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);

But can't seem to get it to work. Do I need the if statement? I added this because the first item is 'status' and was running into errors if I tried to add a 'hire_address' property of this because it doesn't exists.


问:
D3 dashboard chart data bind from json or csv
I am new to D3 charts

i am using D3 dashboard chart following link

http://bl.ocks.org/diethardsteiner/3287802

here the datas are given by variables.

I don't want to get the value from variable and i want to get the value from json file.

Before the data are stored in a variable.

```<code>################ FORMATS ##################
-------------------------------------------
*/

var     formatAsPercentage = d3.format("%"),
        formatAsPercentage1Dec = d3.format(".1%"),
        formatAsInteger = d3.format(","),
        fsec = d3.time.format("%S s"),
        fmin = d3.time.format("%M m"),
        fhou = d3.time.format("%H h"),
        fwee = d3.time.format("%a"),
        fdat = d3.time.format("%d d"),
        fmon = d3.time.format("%b")
        ;

/*
############# PIE CHART ###################
-------------------------------------------
*/

function dsPieChart(){

    var dataset = [
            {category: "ACC", measure: 0.30},
          {category: "B56", measure: 0.25},
          {category: "MAB", measure: 0.15},

          ]
          ;

    var     width = 400,
           height = 400,
           outerRadius = Math.min(width, height) / 2,
           innerRadius = outerRadius * .999,

           innerRadiusFinal = outerRadius * .5,
           innerRadiusFinal3 = outerRadius* .45,
           color = d3.scale.category20()
           ;

    var vis = d3.select("#pieChart")
         .append("svg:svg")
         .data([dataset])
             .attr("width", width)
             .attr("height", height)
                .append("svg:g")
             .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")")
                ;

   var arc = d3.svg.arc()
            .outerRadius(outerRadius).innerRadius(innerRadius);

   var arcFinal = d3.svg.arc().innerRadius(innerRadiusFinal).outerRadius(outerRadius);
    var arcFinal3 = d3.svg.arc().innerRadius(innerRadiusFinal3).outerRadius(outerRadius);

   var pie = d3.layout.pie()
        .value(function(d) { return d.measure; });

   var arcs = vis.selectAll("g.slice")
        .data(pie)
        .enter()
            .append("svg:g")
               .attr("class", "slice")
               .on("mouseover", mouseover)
                    .on("mouseout", mouseout)
                    .on("click", up)
                    ;

        arcs.append("svg:path")
               .attr("fill", function(d, i) { return color(i); } )
               .attr("d", arc)
                    .append("svg:title")
                   .text(function(d) { return d.data.category + ": " + formatAsPercentage(d.data.measure); });

        d3.selectAll("g.slice").selectAll("path").transition()
                .duration(750)
                .delay(10)
                .attr("d", arcFinal )
                ;

      arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; })
            .append("svg:text")
          .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .attr("transform", function(d) { return "translate(" + arcFinal.centroid(d) + ")rotate(" + angle(d) + ")"; })

          .text(function(d) { return d.data.category; })
          ;

        function angle(d) {
            var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
            return a > 90 ? a - 180 : a;
        }

        // Pie chart title
        vis.append("svg:text")
            .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .text("Building")
          .attr("class","title")
          ;

    function mouseover() {
      d3.select(this).select("path").transition()
          .duration(750)

                    .attr("d", arcFinal3)
                    ;
    }

    function mouseout() {
      d3.select(this).select("path").transition()
          .duration(750)

                    .attr("d", arcFinal)
                    ;
    }

    function up(d, i) {

                updateBarChart(d.data.category, color(i));
                updateLineChart(d.data.category, color(i));

    }
}

dsPieChart();
</code>```

now i am trying to get the data by folowing way.

I dont know this is correct way or not can anyone help me

```<code>################ FORMATS ##################
-------------------------------------------
*/

var     formatAsPercentage = d3.format("%"),
        formatAsPercentage1Dec = d3.format(".1%"),
        formatAsInteger = d3.format(","),
        fsec = d3.time.format("%S s"),
        fmin = d3.time.format("%M m"),
        fhou = d3.time.format("%H h"),
        fwee = d3.time.format("%a"),
        fdat = d3.time.format("%d d"),
        fmon = d3.time.format("%b")
        ;

/*
############# PIE CHART ###################
-------------------------------------------
*/

function dsPieChart(){

    var     width = 400,
           height = 400,
           outerRadius = Math.min(width, height) / 2,
           innerRadius = outerRadius * .999,
           // for animation
           innerRadiusFinal = outerRadius * .5,
           innerRadiusFinal3 = outerRadius* .45,
           color = d3.scale.category20()    //builtin range of colors
           ;

});

    var vis = d3.select("#pieChart")
         .append("svg")
        d3.json("readme.json", function(error, root) {
  if (error) throw error;
.data([root])
             .attr("width", width)
             .attr("height", height)
                .append("g")
             .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")")

})

                ;

   var arc = d3.svg.arc()
            .outerRadius(outerRadius).innerRadius(innerRadius);

   var arcFinal = d3.svg.arc().innerRadius(innerRadiusFinal).outerRadius(outerRadius);
    var arcFinal3 = d3.svg.arc().innerRadius(innerRadiusFinal3).outerRadius(outerRadius);

   var pie = d3.layout.pie()
        .value(function(d) { return d.measure; });

   var arcs = vis.selectAll("g.slice")
        .data(pie)
        .enter()
            .append("g")
               .attr("class", "slice")
               .on("mouseover", mouseover)
                    .on("mouseout", mouseout)
                    .on("click", up)
                    ;

        arcs.append("path")
               .attr("fill", function(d, i) { return color(i); } )
               .attr("d", arc)
                    .append("title")
                   .text(function(d) { return d.data.category + ": " + formatAsPercentage(d.data.measure); });

        d3.selectAll("g.slice").selectAll("path").transition()
                .duration(750)
                .delay(10)
                .attr("d", arcFinal )
                ;

      arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; })
            .append("text")
          .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .attr("transform", function(d) { return "translate(" + arcFinal.centroid(d) + ")rotate(" + angle(d) + ")"; })

          .text(function(d) { return d.data.category; })
          ;

        function angle(d) {
            var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
            return a > 90 ? a - 180 : a;
        }

        vis.append("text")
            .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .text("Building")
          .attr("class","title")
          ;

    function mouseover() {
      d3.select(this).select("path").transition()
          .duration(750)

                    .attr("d", arcFinal3)
                    ;
    }

    function mouseout() {
      d3.select(this).select("path").transition()
          .duration(750)

                    .attr("d", arcFinal)
                    ;
    }

    function up(d, i) {

                updateBarChart(d.data.category, color(i));
                updateLineChart(d.data.category, color(i));

    }
}

dsPieChart();
</code>```

can any one give a correct solution

Thanks,

Vinoth

答:
Just create a JSON file with this structure:

```<code>[{
    "category": "ACC",
    "measure": 0.30
}, {
    "category": "B56",
    "measure": 0.25
}, {
    "category": "MAB",
    "measure": 0.15
}]
</code>```

And use d3.json:

```<code>d3.json("data.json", function(dataset){
    //code here
});
</code>```

Here is a plunker showing it: https://plnkr.co/edit/OUjPNY3W2aXXCSxvm4tZ?p=preview

Body:
I am new to D3 charts

i am using D3 dashboard chart following link

http://bl.ocks.org/diethardsteiner/3287802

here the datas are given by variables.

I don't want to get the value from variable and i want to get the value from json file.

Before the data are stored in a variable.

################ FORMATS ##################
-------------------------------------------
*/

var     formatAsPercentage = d3.format("%"),
        formatAsPercentage1Dec = d3.format(".1%"),
        formatAsInteger = d3.format(","),
        fsec = d3.time.format("%S s"),
        fmin = d3.time.format("%M m"),
        fhou = d3.time.format("%H h"),
        fwee = d3.time.format("%a"),
        fdat = d3.time.format("%d d"),
        fmon = d3.time.format("%b")
        ;

/*
############# PIE CHART ###################
-------------------------------------------
*/

function dsPieChart(){

    var dataset = [
            {category: "ACC", measure: 0.30},
          {category: "B56", measure: 0.25},
          {category: "MAB", measure: 0.15},

          ]
          ;

    var     width = 400,
           height = 400,
           outerRadius = Math.min(width, height) / 2,
           innerRadius = outerRadius * .999,

           innerRadiusFinal = outerRadius * .5,
           innerRadiusFinal3 = outerRadius* .45,
           color = d3.scale.category20()
           ;

    var vis = d3.select("#pieChart")
         .append("svg:svg")
         .data([dataset])
             .attr("width", width)
             .attr("height", height)
                .append("svg:g")
             .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")")
                ;

   var arc = d3.svg.arc()
            .outerRadius(outerRadius).innerRadius(innerRadius);

   var arcFinal = d3.svg.arc().innerRadius(innerRadiusFinal).outerRadius(outerRadius);
    var arcFinal3 = d3.svg.arc().innerRadius(innerRadiusFinal3).outerRadius(outerRadius);

   var pie = d3.layout.pie()
        .value(function(d) { return d.measure; });

   var arcs = vis.selectAll("g.slice")
        .data(pie)
        .enter()
            .append("svg:g")
               .attr("class", "slice")
               .on("mouseover", mouseover)
                    .on("mouseout", mouseout)
                    .on("click", up)
                    ;

        arcs.append("svg:path")
               .attr("fill", function(d, i) { return color(i); } )
               .attr("d", arc)
                    .append("svg:title")
                   .text(function(d) { return d.data.category + ": " + formatAsPercentage(d.data.measure); });

        d3.selectAll("g.slice").selectAll("path").transition()
                .duration(750)
                .delay(10)
                .attr("d", arcFinal )
                ;

      arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; })
            .append("svg:text")
          .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .attr("transform", function(d) { return "translate(" + arcFinal.centroid(d) + ")rotate(" + angle(d) + ")"; })

          .text(function(d) { return d.data.category; })
          ;

        function angle(d) {
            var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
            return a > 90 ? a - 180 : a;
        }

        // Pie chart title
        vis.append("svg:text")
            .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .text("Building")
          .attr("class","title")
          ;

    function mouseover() {
      d3.select(this).select("path").transition()
          .duration(750)

                    .attr("d", arcFinal3)
                    ;
    }

    function mouseout() {
      d3.select(this).select("path").transition()
          .duration(750)

                    .attr("d", arcFinal)
                    ;
    }

    function up(d, i) {

                updateBarChart(d.data.category, color(i));
                updateLineChart(d.data.category, color(i));

    }
}

dsPieChart();

now i am trying to get the data by folowing way.

I dont know this is correct way or not can anyone help me

################ FORMATS ##################
-------------------------------------------
*/

var     formatAsPercentage = d3.format("%"),
        formatAsPercentage1Dec = d3.format(".1%"),
        formatAsInteger = d3.format(","),
        fsec = d3.time.format("%S s"),
        fmin = d3.time.format("%M m"),
        fhou = d3.time.format("%H h"),
        fwee = d3.time.format("%a"),
        fdat = d3.time.format("%d d"),
        fmon = d3.time.format("%b")
        ;

/*
############# PIE CHART ###################
-------------------------------------------
*/

function dsPieChart(){

    var     width = 400,
           height = 400,
           outerRadius = Math.min(width, height) / 2,
           innerRadius = outerRadius * .999,
           // for animation
           innerRadiusFinal = outerRadius * .5,
           innerRadiusFinal3 = outerRadius* .45,
           color = d3.scale.category20()    //builtin range of colors
           ;

});

    var vis = d3.select("#pieChart")
         .append("svg")
        d3.json("readme.json", function(error, root) {
  if (error) throw error;
.data([root])
             .attr("width", width)
             .attr("height", height)
                .append("g")
             .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")")

})

                ;

   var arc = d3.svg.arc()
            .outerRadius(outerRadius).innerRadius(innerRadius);

   var arcFinal = d3.svg.arc().innerRadius(innerRadiusFinal).outerRadius(outerRadius);
    var arcFinal3 = d3.svg.arc().innerRadius(innerRadiusFinal3).outerRadius(outerRadius);

   var pie = d3.layout.pie()
        .value(function(d) { return d.measure; });

   var arcs = vis.selectAll("g.slice")
        .data(pie)
        .enter()
            .append("g")
               .attr("class", "slice")
               .on("mouseover", mouseover)
                    .on("mouseout", mouseout)
                    .on("click", up)
                    ;

        arcs.append("path")
               .attr("fill", function(d, i) { return color(i); } )
               .attr("d", arc)
                    .append("title")
                   .text(function(d) { return d.data.category + ": " + formatAsPercentage(d.data.measure); });

        d3.selectAll("g.slice").selectAll("path").transition()
                .duration(750)
                .delay(10)
                .attr("d", arcFinal )
                ;

      arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; })
            .append("text")
          .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .attr("transform", function(d) { return "translate(" + arcFinal.centroid(d) + ")rotate(" + angle(d) + ")"; })

          .text(function(d) { return d.data.category; })
          ;

        function angle(d) {
            var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
            return a > 90 ? a - 180 : a;
        }

        vis.append("text")
            .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .text("Building")
          .attr("class","title")
          ;

    function mouseover() {
      d3.select(this).select("path").transition()
          .duration(750)

                    .attr("d", arcFinal3)
                    ;
    }

    function mouseout() {
      d3.select(this).select("path").transition()
          .duration(750)

                    .attr("d", arcFinal)
                    ;
    }

    function up(d, i) {

                updateBarChart(d.data.category, color(i));
                updateLineChart(d.data.category, color(i));

    }
}

dsPieChart();

can any one give a correct solution

Thanks,

Vinoth

Body:
Just create a JSON file with this structure:

[{
    "category": "ACC",
    "measure": 0.30
}, {
    "category": "B56",
    "measure": 0.25
}, {
    "category": "MAB",
    "measure": 0.15
}]

And use d3.json:

d3.json("data.json", function(dataset){
    //code here
});

Here is a plunker showing it: https://plnkr.co/edit/OUjPNY3W2aXXCSxvm4tZ?p=preview


问:
Hadoop Streaming Job Failed (Unsuccessful) in Python
So my scripts work perfectly when I run:
cat England.txt | ./mapperEngl.py | sort | ./reducerEngl.py

However when I run:

/shared/hadoop/cur/bin/hadoop jar /shared/hadoop/cur/share/hadoop/tools/lib/hadoop-streaming-2.6.0.jar -file /home/hadoop/mapperEngl.py -mapper /home/hadoop/mapperEngl.py -file  /home/hadoop/reducerEngl.py  -reducer /home/hadoop/reducerEngl.py -input /datadir/England.txt -output /outputdir/climateresults3.txt

I get the following error:

```<code>16/05/03 09:27:15 WARN streaming.StreamJob: -file option is deprecated, please use generic option -files instead.
16/05/03 09:27:15 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
packageJobJar: [/home/hadoop/mapperEngl.py, /home/hadoop/reducerEngl.py, /tmp/hadoop-unjar6814867016081507297/] [] /tmp/streamjob1585723008278678599.jar tmpDir=null
16/05/03 09:27:16 INFO client.RMProxy: Connecting to ResourceManager at mgmt-florida-poly-eth0/10.200.209.10:8032
16/05/03 09:27:16 INFO client.RMProxy: Connecting to ResourceManager at mgmt-florida-poly-eth0/10.200.209.10:8032
16/05/03 09:27:17 INFO mapred.FileInputFormat: Total input paths to process : 1
16/05/03 09:27:17 INFO mapreduce.JobSubmitter: number of splits:2
16/05/03 09:27:17 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1459438007195_0006
16/05/03 09:27:17 INFO impl.YarnClientImpl: Submitted application application_1459438007195_0006
16/05/03 09:27:17 INFO mapreduce.Job: The url to track the job: http://mgmt-florida-poly-eth0:8088/proxy/application_1459438007195_0006/
16/05/03 09:27:17 INFO mapreduce.Job: Running job: job_1459438007195_0006
16/05/03 09:27:25 INFO mapreduce.Job: Job job_1459438007195_0006 running in uber mode : false
16/05/03 09:27:25 INFO mapreduce.Job:  map 0% reduce 0%
16/05/03 09:27:31 INFO mapreduce.Job:  map 50% reduce 0%
16/05/03 09:27:32 INFO mapreduce.Job:  map 100% reduce 0%
16/05/03 09:27:38 INFO mapreduce.Job: Task Id : attempt_1459438007195_0006_r_000000_0, Status : FAILED
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
        at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322)
        at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535)
        at org.apache.hadoop.streaming.PipeReducer.close(PipeReducer.java:134)
        at org.apache.hadoop.io.IOUtils.cleanup(IOUtils.java:237)
        at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:459)
        at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)

16/05/03 09:27:45 INFO mapreduce.Job: Task Id : attempt_1459438007195_0006_r_000000_1, Status : FAILED
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
        at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322)
        at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535)
        at org.apache.hadoop.streaming.PipeReducer.close(PipeReducer.java:134)
        at org.apache.hadoop.io.IOUtils.cleanup(IOUtils.java:237)
        at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:459)
        at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)

16/05/03 09:27:51 INFO mapreduce.Job: Task Id : attempt_1459438007195_0006_r_000000_2, Status : FAILED
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
        at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322)
        at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535)
        at org.apache.hadoop.streaming.PipeReducer.close(PipeReducer.java:134)
        at org.apache.hadoop.io.IOUtils.cleanup(IOUtils.java:237)
        at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:459)
        at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)

16/05/03 09:27:58 INFO mapreduce.Job:  map 100% reduce 100%
16/05/03 09:27:58 INFO mapreduce.Job: Job job_1459438007195_0006 failed with state FAILED due to: Task failed task_1459438007195_0006_r_000000
Job failed as tasks failed. failedMaps:0 failedReduces:1

16/05/03 09:27:58 INFO mapreduce.Job: Counters: 37
        File System Counters
                FILE: Number of bytes read=0
                FILE: Number of bytes written=228560
                FILE: Number of read operations=0
                FILE: Number of large read operations=0
                FILE: Number of write operations=0
                HDFS: Number of bytes read=29265
                HDFS: Number of bytes written=0
                HDFS: Number of read operations=6
                HDFS: Number of large read operations=0
                HDFS: Number of write operations=0
        Job Counters
                Failed reduce tasks=4
                Launched map tasks=2
                Launched reduce tasks=4
                Rack-local map tasks=2
                Total time spent by all maps in occupied slots (ms)=134880
                Total time spent by all reduces in occupied slots (ms)=242432
                Total time spent by all map tasks (ms)=8430
                Total time spent by all reduce tasks (ms)=15152
                Total vcore-seconds taken by all map tasks=8430
                Total vcore-seconds taken by all reduce tasks=15152
                Total megabyte-seconds taken by all map tasks=17264640
                Total megabyte-seconds taken by all reduce tasks=31031296
        Map-Reduce Framework
                Map input records=107
                Map output records=223
                Map output bytes=9014
                Map output materialized bytes=9472
                Input split bytes=202
                Combine input records=0
                Spilled Records=223
                Failed Shuffles=0
                Merged Map outputs=0
                GC time elapsed (ms)=0
                CPU time spent (ms)=1540
                Physical memory (bytes) snapshot=1305165824
                Virtual memory (bytes) snapshot=5482422272
                Total committed heap usage (bytes)=2022440960
        File Input Format Counters
                Bytes Read=29063
16/05/03 09:27:58 ERROR streaming.StreamJob: Job not successful!
Streaming Command Failed!
[hadoop@mgmt-florida-poly ~]$
</code>```

I've tried solution from other questions and it doesn't seem to work.

Yeah, just completely stuck here.

答:
Crazy as but I fixed mine with #!/usr/bin/python rather than #!/usr/bin/python3

I think there is a problem with our Hadoop cluster config.

Body:
So my scripts work perfectly when I run:
cat England.txt | ./mapperEngl.py | sort | ./reducerEngl.py

However when I run:

/shared/hadoop/cur/bin/hadoop jar /shared/hadoop/cur/share/hadoop/tools/lib/hadoop-streaming-2.6.0.jar -file /home/hadoop/mapperEngl.py -mapper /home/hadoop/mapperEngl.py -file  /home/hadoop/reducerEngl.py  -reducer /home/hadoop/reducerEngl.py -input /datadir/England.txt -output /outputdir/climateresults3.txt

I get the following error:

16/05/03 09:27:15 WARN streaming.StreamJob: -file option is deprecated, please use generic option -files instead.
16/05/03 09:27:15 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
packageJobJar: [/home/hadoop/mapperEngl.py, /home/hadoop/reducerEngl.py, /tmp/hadoop-unjar6814867016081507297/] [] /tmp/streamjob1585723008278678599.jar tmpDir=null
16/05/03 09:27:16 INFO client.RMProxy: Connecting to ResourceManager at mgmt-florida-poly-eth0/10.200.209.10:8032
16/05/03 09:27:16 INFO client.RMProxy: Connecting to ResourceManager at mgmt-florida-poly-eth0/10.200.209.10:8032
16/05/03 09:27:17 INFO mapred.FileInputFormat: Total input paths to process : 1
16/05/03 09:27:17 INFO mapreduce.JobSubmitter: number of splits:2
16/05/03 09:27:17 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1459438007195_0006
16/05/03 09:27:17 INFO impl.YarnClientImpl: Submitted application application_1459438007195_0006
16/05/03 09:27:17 INFO mapreduce.Job: The url to track the job: http://mgmt-florida-poly-eth0:8088/proxy/application_1459438007195_0006/
16/05/03 09:27:17 INFO mapreduce.Job: Running job: job_1459438007195_0006
16/05/03 09:27:25 INFO mapreduce.Job: Job job_1459438007195_0006 running in uber mode : false
16/05/03 09:27:25 INFO mapreduce.Job:  map 0% reduce 0%
16/05/03 09:27:31 INFO mapreduce.Job:  map 50% reduce 0%
16/05/03 09:27:32 INFO mapreduce.Job:  map 100% reduce 0%
16/05/03 09:27:38 INFO mapreduce.Job: Task Id : attempt_1459438007195_0006_r_000000_0, Status : FAILED
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
        at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322)
        at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535)
        at org.apache.hadoop.streaming.PipeReducer.close(PipeReducer.java:134)
        at org.apache.hadoop.io.IOUtils.cleanup(IOUtils.java:237)
        at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:459)
        at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)

16/05/03 09:27:45 INFO mapreduce.Job: Task Id : attempt_1459438007195_0006_r_000000_1, Status : FAILED
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
        at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322)
        at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535)
        at org.apache.hadoop.streaming.PipeReducer.close(PipeReducer.java:134)
        at org.apache.hadoop.io.IOUtils.cleanup(IOUtils.java:237)
        at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:459)
        at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)

16/05/03 09:27:51 INFO mapreduce.Job: Task Id : attempt_1459438007195_0006_r_000000_2, Status : FAILED
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
        at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322)
        at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535)
        at org.apache.hadoop.streaming.PipeReducer.close(PipeReducer.java:134)
        at org.apache.hadoop.io.IOUtils.cleanup(IOUtils.java:237)
        at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:459)
        at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)

16/05/03 09:27:58 INFO mapreduce.Job:  map 100% reduce 100%
16/05/03 09:27:58 INFO mapreduce.Job: Job job_1459438007195_0006 failed with state FAILED due to: Task failed task_1459438007195_0006_r_000000
Job failed as tasks failed. failedMaps:0 failedReduces:1

16/05/03 09:27:58 INFO mapreduce.Job: Counters: 37
        File System Counters
                FILE: Number of bytes read=0
                FILE: Number of bytes written=228560
                FILE: Number of read operations=0
                FILE: Number of large read operations=0
                FILE: Number of write operations=0
                HDFS: Number of bytes read=29265
                HDFS: Number of bytes written=0
                HDFS: Number of read operations=6
                HDFS: Number of large read operations=0
                HDFS: Number of write operations=0
        Job Counters
                Failed reduce tasks=4
                Launched map tasks=2
                Launched reduce tasks=4
                Rack-local map tasks=2
                Total time spent by all maps in occupied slots (ms)=134880
                Total time spent by all reduces in occupied slots (ms)=242432
                Total time spent by all map tasks (ms)=8430
                Total time spent by all reduce tasks (ms)=15152
                Total vcore-seconds taken by all map tasks=8430
                Total vcore-seconds taken by all reduce tasks=15152
                Total megabyte-seconds taken by all map tasks=17264640
                Total megabyte-seconds taken by all reduce tasks=31031296
        Map-Reduce Framework
                Map input records=107
                Map output records=223
                Map output bytes=9014
                Map output materialized bytes=9472
                Input split bytes=202
                Combine input records=0
                Spilled Records=223
                Failed Shuffles=0
                Merged Map outputs=0
                GC time elapsed (ms)=0
                CPU time spent (ms)=1540
                Physical memory (bytes) snapshot=1305165824
                Virtual memory (bytes) snapshot=5482422272
                Total committed heap usage (bytes)=2022440960
        File Input Format Counters
                Bytes Read=29063
16/05/03 09:27:58 ERROR streaming.StreamJob: Job not successful!
Streaming Command Failed!
[hadoop@mgmt-florida-poly ~]$

I've tried solution from other questions and it doesn't seem to work.

Yeah, just completely stuck here.


问:
Retrieve value TR in javascript
Goal:

Retrieve the value "2TR" from "MARSSTANDGATA132TR" in javascript.

Need to retrieve the index number of number 2.

Problem:

Just don't know what is the right syntax to do it?

Info:

*The value "TR" is always in the end of the word.

*The number "2" of "TR" is always changing. it is only a single number, no two or 3 numbers.

*The address and address number is always changing.

*When you execute the regex code and it cannot find the TR in the end of the word, then you cannot retrieve the requested result.

function myFunction() {
    var str = "MARSSTANDGATA132TR";
    var n = str.search("TR");
    document.getElementById("demo").innerHTML = n;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="myFunction()">Test</button>

<p id="demo"></p></code>```

Thank you!

答:
Or if you want to use the index instead to find correct tr and num idx:

```<code>let str = "MARSSTANDGATA132TR";
let tr = str.search("TR"), numIdx;

if (tr !== -1) {
  numIdx = str[tr -1];
  tr = str.substr(tr, tr + 1);
} else {
  alert('no TR');
}
console.log(tr);
console.log(numIdx)
</code>```

or in case that the string contains multiple TRs, then you want to make sure that its really the correct one.

```<code>let str = "MARSS**TR**ANDGATA132**TR**";
let trIdx = 0, tr, numIdx;

let findTrIdx = (str) => {
  let tmpIdx = str.search('TR');
  if (!parseInt(str[tmpIdx - 1])) {
    let newStr = str.substr(tmpIdx + 2, str.length -1);
    tmpIdx = tmpIdx + 2;
    findTrIdx(newStr);
  }
  trIdx += tmpIdx;
  return trIdx;
}

trIdx = findTrIdx(str);

if (trIdx !== -1) {
    numIdx = str[trIdx -1];
  tr = str.substr(trIdx, trIdx + 1);
} else {
    alert('no TR');
}
console.log(tr);
console.log(numIdx)
</code>```

Title: Retrieve value TR in javascript

Body:
Goal:

Retrieve the value "2TR" from "MARSSTANDGATA132TR" in javascript.

Need to retrieve the index number of number 2.

Problem:

Just don't know what is the right syntax to do it?

Info:

*The value "TR" is always in the end of the word.

*The number "2" of "TR" is always changing. it is only a single number, no two or 3 numbers.

*The address and address number is always changing.

*When you execute the regex code and it cannot find the TR in the end of the word, then you cannot retrieve the requested result.

function myFunction() {
    var str = "MARSSTANDGATA132TR";
    var n = str.search("TR");
    document.getElementById("demo").innerHTML = n;
}

<button onclick="myFunction()">Test</button>

Thank you!

Body:
Or if you want to use the index instead to find correct tr and num idx:

let str = "MARSSTANDGATA132TR";
let tr = str.search("TR"), numIdx;

if (tr !== -1) {
  numIdx = str[tr -1];
  tr = str.substr(tr, tr + 1);
} else {
  alert('no TR');
}
console.log(tr);
console.log(numIdx)

or in case that the string contains multiple TRs, then you want to make sure that its really the correct one.

let str = "MARSS**TR**ANDGATA132**TR**";
let trIdx = 0, tr, numIdx;

let findTrIdx = (str) => {
  let tmpIdx = str.search('TR');
  if (!parseInt(str[tmpIdx - 1])) {
    let newStr = str.substr(tmpIdx + 2, str.length -1);
    tmpIdx = tmpIdx + 2;
    findTrIdx(newStr);
  }
  trIdx += tmpIdx;
  return trIdx;
}

trIdx = findTrIdx(str);

if (trIdx !== -1) {
    numIdx = str[trIdx -1];
  tr = str.substr(trIdx, trIdx + 1);
} else {
    alert('no TR');
}
console.log(tr);
console.log(numIdx)


问:
Joi validation set default as empty object
I'm running into an issue (or what I believe to be one) with Joi validation.  I'm trying to assign a value to a non-existent key if it's been passed as part of the request body.

So for example:

```<code>parameters: Joi.object().keys({
  keyA: Joi.string().allow('').allow(null).default(null),
  keyB: Joi.object().keys({
    b1: Joi.string(),
    b2: Joi.string(),
    b3: Joi.object().keys({
      b3_1: Joi.string(),
      b3_2: Joi.string(),
      b3_3: Joi.string()
    })
  }).default({}),
  keyC: Joi.object().keys({
    c1: Joi.number(),
    c2: Joi.number(),
    c3: Joi.boolean(),
    c4: Joi.boolean()
  }).default({}),
  keyD: Joi.object().keys({
    d1: Joi.number(),
    d2: Joi.number()
  }).default({}),
  keyE: Joi.object().keys({
    e1: Joi.number()
  }).default({})
}).allow(null)
</code>```

So to be specific if I were to pass in:

```<code>{
  keyA: "foo",
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}
</code>```

I would get this in return

```<code>{
  keyA: "foo",
  keyB: {},
  keyC: {},
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}
</code>```

With :eyes: on the empty objects.  What am I missing with the Joi.default() method?  Am I overextending what Joi is meant for?

答:
I'll start by pointing out that the schema in your question isn't valid JavaScript, you've closed a few too many brackets before declaring the rule for keyC. I'll assume this is simply a formatting error with the question and your actual schema is currently valid.

Secondly, there's nothing wrong with how you've declared your defaults.. it works just fine. I'll assume it's the way you're validating the schema which is the problem.

Try running this. I've mimicked the validation method in the docs for default().

```<code>const schema = Joi.object().keys({
    keyA: Joi.string().allow('').allow(null).default(null),
    keyB: Joi.object().keys({
        b1: Joi.string(),
        b2: Joi.string(),
        b3: Joi.object().keys({
            b3_1: Joi.string(),
            b3_2: Joi.string(),
            b3_3: Joi.string()
        })
    }).default({}),
    keyC: Joi.object().keys({
        c1: Joi.number(),
        c2: Joi.number(),
        c3: Joi.boolean(),
        c4: Joi.boolean()
    }).default({}),
    keyD: Joi.object().keys({
        d1: Joi.number(),
        d2: Joi.number()
    }).default({}),
    keyE: Joi.object().keys({
        e1: Joi.number()
    }).default({})
}).allow(null);

Joi.validate({
    keyA: "foo",
    keyD: {
        d1: 21.9,
        d2: 21.1
    },
    keyE: {
        e1: 42
    }
}, schema, (err, value) =>
{
    if (err)
        throw err;

    console.log(value);
});
</code>```

I get this in the console:

```<code>{
    keyA :'foo',
    keyD: {
        d1: 21.9,
        d2: 21.1
    },
    keyE: {
        e1: 42
    },
    keyB: {},
    keyC: {}
}
</code>```

The keys are unlikely to look ordered like your expected output, but that shouldn't matter as object keys are not ordered anyway.

Body:
I'm running into an issue (or what I believe to be one) with Joi validation.  I'm trying to assign a value to a non-existent key if it's been passed as part of the request body.

So for example:

parameters: Joi.object().keys({
  keyA: Joi.string().allow('').allow(null).default(null),
  keyB: Joi.object().keys({
    b1: Joi.string(),
    b2: Joi.string(),
    b3: Joi.object().keys({
      b3_1: Joi.string(),
      b3_2: Joi.string(),
      b3_3: Joi.string()
    })
  }).default({}),
  keyC: Joi.object().keys({
    c1: Joi.number(),
    c2: Joi.number(),
    c3: Joi.boolean(),
    c4: Joi.boolean()
  }).default({}),
  keyD: Joi.object().keys({
    d1: Joi.number(),
    d2: Joi.number()
  }).default({}),
  keyE: Joi.object().keys({
    e1: Joi.number()
  }).default({})
}).allow(null)

So to be specific if I were to pass in:

{
  keyA: "foo",
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}

I would get this in return

{
  keyA: "foo",
  keyB: {},
  keyC: {},
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}

With :eyes: on the empty objects.  What am I missing with the Joi.default() method?  Am I overextending what Joi is meant for?

Body:
I'll start by pointing out that the schema in your question isn't valid JavaScript, you've closed a few too many brackets before declaring the rule for keyC. I'll assume this is simply a formatting error with the question and your actual schema is currently valid.

Secondly, there's nothing wrong with how you've declared your defaults.. it works just fine. I'll assume it's the way you're validating the schema which is the problem.

Try running this. I've mimicked the validation method in the docs for default().

const schema = Joi.object().keys({
    keyA: Joi.string().allow('').allow(null).default(null),
    keyB: Joi.object().keys({
        b1: Joi.string(),
        b2: Joi.string(),
        b3: Joi.object().keys({
            b3_1: Joi.string(),
            b3_2: Joi.string(),
            b3_3: Joi.string()
        })
    }).default({}),
    keyC: Joi.object().keys({
        c1: Joi.number(),
        c2: Joi.number(),
        c3: Joi.boolean(),
        c4: Joi.boolean()
    }).default({}),
    keyD: Joi.object().keys({
        d1: Joi.number(),
        d2: Joi.number()
    }).default({}),
    keyE: Joi.object().keys({
        e1: Joi.number()
    }).default({})
}).allow(null);

Joi.validate({
    keyA: "foo",
    keyD: {
        d1: 21.9,
        d2: 21.1
    },
    keyE: {
        e1: 42
    }
}, schema, (err, value) =>
{
    if (err)
        throw err;

    console.log(value);
});

I get this in the console:

{
    keyA :'foo',
    keyD: {
        d1: 21.9,
        d2: 21.1
    },
    keyE: {
        e1: 42
    },
    keyB: {},
    keyC: {}
}

The keys are unlikely to look ordered like your expected output, but that shouldn't matter as object keys are not ordered anyway.


问:
Bootstrap responsive layout in mobile convert to tabs
So as the title suggests, I am currently using Bootstrap.  I am working on a responsive layout that in desktop size, is just a normal columned floated layout.  Then in mobile device or tablet size, it adds bootstrap tabs.  I am not sure quite how to solve this as the bootstrap 3 col-xs floats don't seem to be playing nice with the tabs plugin.  I have made a diagram to help explain.

Fiddle I've been working with jsfiddle

```<code><div class="container">
<div class="content">
    <ul class="nav nav-tabs visible-phone">
        <li class="active"><a href="#t1" data-toggle="tab">T1</a></li>
        <li><a href="#t2" data-toggle="tab">T2</a></li>
        <li><a href="#t3" data-toggle="tab">T3</a></li>
    </ul>

    <div class="row tab-content">
        <div class="col-sm-4 tab-pane active" id="enter">
            <div class="inner-right-border">
                <h2>T1 CONTENT</h2>
                <hr />
            </div>
        </div>
        <div class="col-sm-8">
            <div class="tab-pane" id="t2">
                <h2>T2 CONTENT</h2><hr />
            </div>
            <div class="tab-pane" id="t3">
                <h2>T3 CONTENT</h2><hr />
            </div>
        </div>
    </div>
</div>
</code>```

Thanks in advance for any help!

答:
The CSS code above works, but has an issue with nested tabs. e.g from the initial - future tab one then contains 2 tabs.

I wanted to post this as a comment to the Atul's response, but don't have enough "reputation" points.

This is a slight tweak to allow nested tabs.

@media (max-width: 767px) {
  .device-big {
    display: none;
  }
  .device-small {
    display: block;
  }
}
/* big device */
@media only screen and (min-width : 768px) {
  .tab-content > .tab-pane.device-big {
    display: block;
  }
  .device-small {
    display: none;
  }
}```

Body:
So as the title suggests, I am currently using Bootstrap.  I am working on a responsive layout that in desktop size, is just a normal columned floated layout.  Then in mobile device or tablet size, it adds bootstrap tabs.  I am not sure quite how to solve this as the bootstrap 3 col-xs floats don't seem to be playing nice with the tabs plugin.  I have made a diagram to help explain.

Fiddle I've been working with jsfiddle

T1

T2

T3

T1 CONTENT

T2 CONTENT

T3 CONTENT

Thanks in advance for any help!


问:
Client Side Alerts not working
```
I am using MeteorJS technology and trying alerts on success or failure
of meteor call. And alerts not working, unable to recognize the
problem. And this is a client-side code.

             Template.socialIntFBGoogle.events({
                 'click .socialFb': function(event) {
                     Meteor.loginWithFacebook({}, function(err){
                         if (err) {
                          throw new Meteor.Error("Facebook login failed");
                          }else{
                          alert("Google login");
                          Meteor.call('transfer',function(error, result){
                          if(error){alert(error);}
                          else{alert("Successful");}
                          });

                     FlowRouter.go('/');
                   }
                });
              },
           });

Thanks in Advance!
```

答:
For logging purposes you should not using alert instead replace your alert calls with:

```<code>console.log("your message");
</code>```

After that you can review, the output in your Web browser Dev tools.

Title: Client Side Alerts not working

Body:
For logging purposes you should not using alert instead replace your alert calls with:

console.log("your message");

After that you can review, the output in your Web browser Dev tools.


问:
How to bind values using ng-model
I am working on an app where I am facing this similar issue. I am dynamically creating select boxes based on API response. I dont understand how to bind these values in controller. Code for reference is

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   // how to get values of input boxes here
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model= "What_Should_Go_Here" ng-repeat="x in [10,11,22,33]">
<option>aaa</option>
<option>bbb</option>
<option>ccc</option>
</select>
{{What_Should_Go_Here}}
</div></code>```

答:
use a select box with ng-change method and pass the model value to that change function like below.....so that you can access the selected item in js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.array=[10,11,22,33];//assuem it as your db result
  $scope.fix=function(val){
    console.log(val);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
  <select ng-model= "x" ng-options="x as x for x in array" ng-change="fix(x)"</select>
  {{x}}
  </body>

</html></code>```

Title: How to bind values using ng-model

Body:
I am working on an app where I am facing this similar issue. I am dynamically creating select boxes based on API response. I dont understand how to bind these values in controller. Code for reference is

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   // how to get values of input boxes here
});

<select ng-model= "What_Should_Go_Here" ng-repeat="x in [10,11,22,33]">
<option>aaa</option>
<option>bbb</option>
<option>ccc</option>
</select>
{{What_Should_Go_Here}}

Body:
use a select box with ng-change method and pass the model value to that change function like below.....so that you can access the selected item in js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.array=[10,11,22,33];//assuem it as your db result
  $scope.fix=function(val){
    console.log(val);
  }
});

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
  <select ng-model= "x" ng-options="x as x for x in array" ng-change="fix(x)"</select>
  {{x}}
  </body>

</html>


问:
reference & pointers confusing parts(declarations and their types)
I'm studying pointer and reference parts and having very hard time to study them.
I think I understand now some simple usage of reference and pointers in the function, but there is something I cannot totally understand.

Here are some variable declarations:

```<code>int a = 1;
float b = 2;
int* p = &a;
string s = "Hello";
vector<int*> values = {p};
</code>```

What will be the types of the following expressions?

```<code>&a
&b
p
&p
&s
&(s.at(1))
values.at(0)
&(values.at(0))
&values
</code>```

I have no idea what their types exactly are, but I tried it myself.

```<code>&a : pointer to int
&b : pointer float
 p : pointer to int
&p : pointer to pointer to int
&s : pointer to string
&(s.at(1)) : pointer to string
values.at(0) : pointer to int
&(values.at(0)) : pointer to pointer to int
&values : pointer to pointer to int
</code>```

and one more problem >
write the following variable declarations:
a) A pointer to a string
b) A reference to a float
c) An array of pointers-to-ints.
d) A pointer to a pointer to bool
e) A reference to a pointer to an int

and my answers are:

```<code>a: string* s = "Hello"

b: float& f = g;

c: int n =1;
   int*x =&n;
   int arr[] = {*x};

d: bool y = true;
   bool* x = &y;
   bool** qq = &x;

e: int a = 1;
   int* x = &a;
   int& z = *x;
</code>```

I'm not sure about my answers. Please help these confusing parts.

答:
Part 1:

If the expression e has type T, the type of &e is pointer to T; T*.

Consider the types of the expressions s.at(1) and values more carefully.

Part 2:

c: int arr[] is not "array of pointers-to-ints", it's "array of int".

An array of T is T arr[]; an array of int* is int* arr[].

```<code>int n = 1;
int* arr[] = {&n};
</code>```

e: int& z is not "reference to a pointer to an int", it's "reference to int".

A reference to T is T&; a reference to int* is int*&.

```<code>int a = 1;
int* x = &a;
int*& z = x;
</code>```

Body:
I'm studying pointer and reference parts and having very hard time to study them.
I think I understand now some simple usage of reference and pointers in the function, but there is something I cannot totally understand.

Here are some variable declarations:

int a = 1;
float b = 2;
int* p = &a;
string s = "Hello";
vector<int*> values = {p};

What will be the types of the following expressions?

&a
&b
p
&p
&s
&(s.at(1))
values.at(0)
&(values.at(0))
&values

I have no idea what their types exactly are, but I tried it myself.

&a : pointer to int
&b : pointer float
 p : pointer to int
&p : pointer to pointer to int
&s : pointer to string
&(s.at(1)) : pointer to string
values.at(0) : pointer to int
&(values.at(0)) : pointer to pointer to int
&values : pointer to pointer to int

and one more problem >
write the following variable declarations:
a) A pointer to a string
b) A reference to a float
c) An array of pointers-to-ints.
d) A pointer to a pointer to bool
e) A reference to a pointer to an int

and my answers are:

a: string* s = "Hello"

b: float& f = g;

c: int n =1;
   int*x =&n;
   int arr[] = {*x};

d: bool y = true;
   bool* x = &y;
   bool** qq = &x;

e: int a = 1;
   int* x = &a;
   int& z = *x;

I'm not sure about my answers. Please help these confusing parts.

Body:
Part 1:

If the expression e has type T, the type of &e is pointer to T; T*.

Consider the types of the expressions s.at(1) and values more carefully.

Part 2:

c: int arr[] is not "array of pointers-to-ints", it's "array of int".

An array of T is T arr[]; an array of int* is int* arr[].

int n = 1;
int* arr[] = {&n};

e: int& z is not "reference to a pointer to an int", it's "reference to int".

A reference to T is T&; a reference to int* is int*&.

int a = 1;
int* x = &a;
int*& z = x;


问:
StringBuilder - Reset or create a new
I have a condition that a StringBuilder keeps storing lines matching a pattern from a large flat file (100's of MB). However after reaching a condition I write the content of the StringBuilder varialble to a textfile.

Now I wonder if I should use the same variable by resetting the object ->

```<code>stringBuilder.delete(0,stringBuilder.length())
</code>```

OR

```<code>stringBuilder=new StringBuilder();
</code>```

Please suggest which would do you think is better as far as both performance and OOM issues are concerned.

答:
It is cheaper reuse the created object than allocate a new one, always. It also avoids extra work for the Garbage Collector, as you are handling only an object.

The faster way is:

```<code>stringBuilder.setLength(0);
</code>```

Title: StringBuilder - Reset or create a new

Body:
I have a condition that a StringBuilder keeps storing lines matching a pattern from a large flat file (100's of MB). However after reaching a condition I write the content of the StringBuilder varialble to a textfile.

Now I wonder if I should use the same variable by resetting the object ->

stringBuilder.delete(0,stringBuilder.length())

OR

stringBuilder=new StringBuilder();

Please suggest which would do you think is better as far as both performance and OOM issues are concerned.

Body:
It is cheaper reuse the created object than allocate a new one, always. It also avoids extra work for the Garbage Collector, as you are handling only an object.

The faster way is:

stringBuilder.setLength(0);