问:
How can I share OpenSSL sessions between Perl processes?
I'm using Perl to connect to some (very) low-powered hardware devices with TLS. The first handshake can take around 10-15 seconds to complete! Reusing the session (from the same Perl process) is much faster but when the next job comes around to connect to the same device the new process has to establish a new session with the same delay. I'd like to share a session cache between my processes but I'm running into problems (and segfaults!).

I have a test script (connecting to openssl s_server -www) with a IO::Socket::SSL::Session_Cache wrapper that uses Sereal to write the cache object out to disk. Despite finding the existing sessions in the cache, it does not reuse them and sometimes segfaults when trying to add additional entries to the cache.

```<code>use 5.20.1; use warnings;

use LWP::UserAgent;
use IO::Socket::SSL;
# $IO::Socket::SSL::DEBUG = 2;

request_with_new_ua();
request_with_new_ua();
request_with_new_ua();

sub request_with_new_ua {
   say "make request";
   my $ua = LWP::UserAgent->new;
   $ua->ssl_opts(
      verify_hostname => 0,
      SSL_session_cache => Inline::SessionStore->new,
   );
   process_response($ua->get('https://localhost:4433'));
}

sub process_response {
   my $res = shift;
   say "> $_" for grep /Session|Master/, split /\n/, $res->as_string;
}

BEGIN {
   package Inline::SessionStore;

   use 5.20.1; use warnings;
   use Moo;
   use experimental qw(signatures);
   use Sereal::Encoder;
   use Sereal::Decoder;
   use Try::Tiny;
   use Path::Tiny;

   has session_cache => ( is => 'rw' );

   my $encoder = Sereal::Encoder->new;
   my $decoder = Sereal::Decoder->new;
   my $file = path('/tmp/ssl-session-cache');

   sub get_session ($self, $key) {
      say "get session $key";
      my $cache;
      try {
         $cache = $decoder->decode($file->slurp_raw);
         say "got cache from file, ".ref $cache;
      } catch {
         say $_ unless /No such file/;
         $cache = IO::Socket::SSL::Session_Cache->new(128);
         say "made new cache";
      };
      $self->session_cache($cache);

      my $ret = $cache->get_session($key);
      say "found session $ret" if $ret;
      return $ret;
   }

   sub add_session {
      my $self = shift;
      say"add session " . join ' - ', @_;
      my $session = $self->session_cache->add_session(@_);

      $file->spew_raw($encoder->encode($self->session_cache));
      return $session;
   }

   sub del_session {
      my $self = shift;
      say "del session " . join ' - ', @_;
      $self->session_cache->del_session(@_);

      $file->spew_raw($encoder->encode($self->session_cache));
   }

   1;
}
</code>```

And output:

```
 rm -f /tmp/ssl-session-cache && perl wes.swp/workbench.pl
make request
get session localhost:4433
made new cache
add session localhost:4433 - 23864624
> SSL-Session:
>     Session-ID:
>     Session-ID-ctx: 01000000
>     Master-Key: DDF335492BFE2A7BA7674A656E72005865859D89249D597302F338D01C5776E2C94B61E6BCBED6114DFDA5AAEECD22EA
make request
get session localhost:4433
got cache from file, IO::Socket::SSL::Session_Cache
found session 23864624
add session localhost:4433 - 23864624  # trying to re-add the session??
> SSL-Session:
>     Session-ID:
>     Session-ID-ctx: 01000000
>     Master-Key: 4FE17B7FE9B4DE0A711C659FC333F686AD41840740B9D10E67A972D5A27D1720F0470329DA63DE65C1B023A1E2F0CC89
make request
get session localhost:4433
got cache from file, IO::Socket::SSL::Session_Cache
found session 23864624
add session localhost:4433 - 23864624
> SSL-Session:
>     Session-ID:
>     Session-ID-ctx: 01000000
>     Master-Key: C76C52E5ECC13B0BB4FA887B381779B6F686A73DDFBEA06B33336537EC6AE39290370C07505BCD8B552CA874CD6E4089
```

I feel like I'm close to getting this to work but I'm missing something.

答:
I don't think there is a way to use IO::Socket::SSL/Net::SSLeay or Crypt::SSLeay (which are the newer and older SSL backend for LWP) between processes.

The session cache you are trying to use in your code references SESSION objects which are internal to the OpenSSL library. Serializing the cache at the Perl level will not serialize the parts from inside the OpenSSL library but will just include the pointers to the internal structures. Since these pointers are only valid for the current state of the process, deserializing this again inside a different process or process state will thus result in dangling pointers pointing into nowhere in the best case or to some other data in the worst case and will thus result in segmentation faults or corruption of internal data.

In Net::SSLeay there are i2d_SSL_SESSION and d2i_SSL_SESSION functions which could in theory be used to properly serialize a SESSION object. But I doubt that there are usable in the current implementation.

Body:
I'm using Perl to connect to some (very) low-powered hardware devices with TLS. The first handshake can take around 10-15 seconds to complete! Reusing the session (from the same Perl process) is much faster but when the next job comes around to connect to the same device the new process has to establish a new session with the same delay. I'd like to share a session cache between my processes but I'm running into problems (and segfaults!).

I have a test script (connecting to openssl s_server -www) with a IO::Socket::SSL::Session_Cache wrapper that uses Sereal to write the cache object out to disk. Despite finding the existing sessions in the cache, it does not reuse them and sometimes segfaults when trying to add additional entries to the cache.

use 5.20.1; use warnings;

use LWP::UserAgent;
use IO::Socket::SSL;
# $IO::Socket::SSL::DEBUG = 2;

request_with_new_ua();
request_with_new_ua();
request_with_new_ua();

sub request_with_new_ua {
   say "make request";
   my $ua = LWP::UserAgent->new;
   $ua->ssl_opts(
      verify_hostname => 0,
      SSL_session_cache => Inline::SessionStore->new,
   );
   process_response($ua->get('https://localhost:4433'));
}

sub process_response {
   my $res = shift;
   say "> $_" for grep /Session|Master/, split /\n/, $res->as_string;
}

BEGIN {
   package Inline::SessionStore;

   use 5.20.1; use warnings;
   use Moo;
   use experimental qw(signatures);
   use Sereal::Encoder;
   use Sereal::Decoder;
   use Try::Tiny;
   use Path::Tiny;

   has session_cache => ( is => 'rw' );

   my $encoder = Sereal::Encoder->new;
   my $decoder = Sereal::Decoder->new;
   my $file = path('/tmp/ssl-session-cache');

   sub get_session ($self, $key) {
      say "get session $key";
      my $cache;
      try {
         $cache = $decoder->decode($file->slurp_raw);
         say "got cache from file, ".ref $cache;
      } catch {
         say $_ unless /No such file/;
         $cache = IO::Socket::SSL::Session_Cache->new(128);
         say "made new cache";
      };
      $self->session_cache($cache);

      my $ret = $cache->get_session($key);
      say "found session $ret" if $ret;
      return $ret;
   }

   sub add_session {
      my $self = shift;
      say"add session " . join ' - ', @_;
      my $session = $self->session_cache->add_session(@_);

      $file->spew_raw($encoder->encode($self->session_cache));
      return $session;
   }

   sub del_session {
      my $self = shift;
      say "del session " . join ' - ', @_;
      $self->session_cache->del_session(@_);

      $file->spew_raw($encoder->encode($self->session_cache));
   }

   1;
}

And output:

 rm -f /tmp/ssl-session-cache && perl wes.swp/workbench.pl
make request
get session localhost:4433
made new cache
add session localhost:4433 - 23864624
> SSL-Session:
>     Session-ID:
>     Session-ID-ctx: 01000000
>     Master-Key: DDF335492BFE2A7BA7674A656E72005865859D89249D597302F338D01C5776E2C94B61E6BCBED6114DFDA5AAEECD22EA
make request
get session localhost:4433
got cache from file, IO::Socket::SSL::Session_Cache
found session 23864624
add session localhost:4433 - 23864624  # trying to re-add the session??
> SSL-Session:
>     Session-ID:
>     Session-ID-ctx: 01000000
>     Master-Key: 4FE17B7FE9B4DE0A711C659FC333F686AD41840740B9D10E67A972D5A27D1720F0470329DA63DE65C1B023A1E2F0CC89
make request
get session localhost:4433
got cache from file, IO::Socket::SSL::Session_Cache
found session 23864624
add session localhost:4433 - 23864624
> SSL-Session:
>     Session-ID:
>     Session-ID-ctx: 01000000
>     Master-Key: C76C52E5ECC13B0BB4FA887B381779B6F686A73DDFBEA06B33336537EC6AE39290370C07505BCD8B552CA874CD6E4089

I feel like I'm close to getting this to work but I'm missing something.


来源: stackexchange

问:
hide home indicator for iPhone X
i have an iOS app with video player, when the video is playing (landscape, full screen) i would like to hide the home indicator on iPhone X. I have try with

```<code>if (@available(iOS 11.0, *)) {
     [self setNeedsUpdateOfHomeIndicatorAutoHidden];
}
</code>```

and also

```<code>-(BOOL)prefersHomeIndicatorAutoHidden{
   return YES;
}
</code>```

but no luck. Does anyone have any idea?

答:
When implementing a container view controller, override
  childViewControllerForHomeIndicatorAutoHidden() method if you want
  one your child view controllers to determine whether to display the
  visual indicator. If you do, the system calls the
  prefersHomeIndicatorAutoHidden() method of the returned view
  controller. If the method returns nil, the system calls the
  prefersHomeIndicatorAutoHidden() method of the current view controller

So if you are using childViewController then need to implement childViewControllerForHomeIndicatorAutoHidden
as -

Swift

```<code>extension UINavigationController {
    open override func childViewControllerForHomeIndicatorAutoHidden() -> UIViewController? {
        return DemoViewController.loadFromNib()
    }
}

//DemoViewController is childViewController
class DemoViewController: UIViewController {
    static func loadFromNib() -> DemoViewController{
        let storyBoardInst = UIStoryboard(name: "Main", bundle: nil)
        return storyBoardInst.instantiateViewController(withIdentifier: "DemoViewController") as! DemoViewController
    }

    override func prefersHomeIndicatorAutoHidden() -> Bool {
        return true
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        view.backgroundColor = .red
        if #available(iOS 11.0, *) {
            //Notifies UIKit that your view controller updated its preference regarding the visual indicator
            setNeedsUpdateOfHomeIndicatorAutoHidden()
        }
    }
}
</code>```

Objective C-

```<code>@interface UINavigationController(custom)
@end
@implementation UINavigationController(custom)
-(UIViewController *)childViewControllerForHomeIndicatorAutoHidden{
    return [self.storyboard  instantiateViewControllerWithIdentifier:@"DemoViewController"];
}
@end
    //DemoViewController is childViewController
@interface DemoViewController ()
@end
@implementation DemoViewController
-(BOOL)prefersHomeIndicatorAutoHidden{
    return YES;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    self.view.backgroundColor = [UIColor redColor];
    //Notifies UIKit that your view controller updated its preference
    // regarding the visual indicator
    if (@available(iOS 11.0, *)) {
        [self setNeedsUpdateOfHomeIndicatorAutoHidden];
    }
}
</code>```

Output -

ContentLicense: CC BY-SA 3.0

Title: hide home indicator for iPhone X

Body:
i have an iOS app with video player, when the video is playing (landscape, full screen) i would like to hide the home indicator on iPhone X. I have try with

if (@available(iOS 11.0, *)) {
     [self setNeedsUpdateOfHomeIndicatorAutoHidden];
}

and also

-(BOOL)prefersHomeIndicatorAutoHidden{
   return YES;
}

but no luck. Does anyone have any idea?

Body:
When implementing a container view controller, override
  childViewControllerForHomeIndicatorAutoHidden() method if you want
  one your child view controllers to determine whether to display the
  visual indicator. If you do, the system calls the
  prefersHomeIndicatorAutoHidden() method of the returned view
  controller. If the method returns nil, the system calls the
  prefersHomeIndicatorAutoHidden() method of the current view controller

So if you are using childViewController then need to implement childViewControllerForHomeIndicatorAutoHidden
as -

Swift

extension UINavigationController {
    open override func childViewControllerForHomeIndicatorAutoHidden() -> UIViewController? {
        return DemoViewController.loadFromNib()
    }
}

//DemoViewController is childViewController
class DemoViewController: UIViewController {
    static func loadFromNib() -> DemoViewController{
        let storyBoardInst = UIStoryboard(name: "Main", bundle: nil)
        return storyBoardInst.instantiateViewController(withIdentifier: "DemoViewController") as! DemoViewController
    }

    override func prefersHomeIndicatorAutoHidden() -> Bool {
        return true
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        view.backgroundColor = .red
        if #available(iOS 11.0, *) {
            //Notifies UIKit that your view controller updated its preference regarding the visual indicator
            setNeedsUpdateOfHomeIndicatorAutoHidden()
        }
    }
}

Objective C-

@interface UINavigationController(custom)
@end
@implementation UINavigationController(custom)
-(UIViewController *)childViewControllerForHomeIndicatorAutoHidden{
    return [self.storyboard  instantiateViewControllerWithIdentifier:@"DemoViewController"];
}
@end
    //DemoViewController is childViewController
@interface DemoViewController ()
@end
@implementation DemoViewController
-(BOOL)prefersHomeIndicatorAutoHidden{
    return YES;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    self.view.backgroundColor = [UIColor redColor];
    //Notifies UIKit that your view controller updated its preference
    // regarding the visual indicator
    if (@available(iOS 11.0, *)) {
        [self setNeedsUpdateOfHomeIndicatorAutoHidden];
    }
}

Output -

ContentLicense: CC BY-SA 4.0


问:
Arrange data in the table
I've been working to this kind of data in array

```<code>data:[
    0:{
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"16:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"16:00:00"}
     ]
    }
    1:{
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"17:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"17:00:00"}
     ]
    }
]
</code>```

I want the data to be display like this:

But it always turn out like this:

I use this code below in distributing data in the table

```<code><table>
      <thead>
            <tr class="text-center location text-white">
                <th>Employee</th>
                <th>Date</th>
                <th>Time In / Time Out</th>
            </tr>
      </thead>
      <tbody>
            <ng-container *ngFor= "let da of data; ">
            <tr *ngFor= "let s of da.details">
                  <td>
                     <strong>{{da.name}}</strong>
                  </td>
                  <td>
                     {{s.date}}
                  </td>
                  <td>
                    <input type="time [value]="s.start_time">
                    <strong>/</strong>
                    <input type="time [value]="s.end_time">
                  </td>
            </tr>
            </ng-container>
      </tbody>
</table>
</code>```

can you help on how I should display my data in the table properly.
I'm using angular 2

答:
Try like this :

here demo link : demo

```<code><table>
    <thead>
        <tr class="text-center location text-white">
            <th>Employee</th>
            <th>Date</th>
            <th>Time In / Time Out</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let d of data">
            <td>{{d.name}}</td>
            <td>
                <table>
                    <tr *ngFor="let c of d.details">
                        <td>
                            {{c.date}}
                        </td>
                    </tr>
                </table>
            </td>
            <td>
                <table>
                    <tr *ngFor="let s of d.details">
                        <td>
                            <input type="time" [value]="s.start_time">
                            <input type="time" [value]="s.end_time">
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </tbody>
</table>
</code>```

Title: Arrange data in the table

Body:
I've been working to this kind of data in array

data:[
    0:{
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"16:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"16:00:00"}
     ]
    }
    1:{
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"17:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"17:00:00"}
     ]
    }
]

I want the data to be display like this:

But it always turn out like this:

I use this code below in distributing data in the table

                Employee
                Date
                Time In / Time Out

            <ng-container *ngFor= "let da of data; ">

                     {{da.name}}

                     {{s.date}}

                    <input type="time [value]="s.start_time">
                    /
                    <input type="time [value]="s.end_time">

            </ng-container>

can you help on how I should display my data in the table properly.
I'm using angular 2

Body:
Try like this :

here demo link : demo

<table>
    <thead>
        <tr class="text-center location text-white">
            <th>Employee</th>
            <th>Date</th>
            <th>Time In / Time Out</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let d of data">
            <td>{{d.name}}</td>
            <td>
                <table>
                    <tr *ngFor="let c of d.details">
                        <td>
                            {{c.date}}
                        </td>
                    </tr>
                </table>
            </td>
            <td>
                <table>
                    <tr *ngFor="let s of d.details">
                        <td>
                            <input type="time" [value]="s.start_time">
                            <input type="time" [value]="s.end_time">
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </tbody>
</table>


问:
how to input the parent id into database in different table
I have table -> subkategori

and I can't insert the id_kategori attribute to table portfolio

i have a code for the model :

```<code>function get_subcategories($id_kategori){

$query = $this->db->query("SELECT id_kategori from subkategori WHERE id_subkategori=".$this->input->post('a'));
return $query->result();
}
</code>```

and the controller here :

```<code>if ($this->input->post('a')!=''){
    $this->load->model('Model_app');
    $this->model_app->get_subcatoegories('$id_kategori');
}else{
    $id_kategori = '';
}
$data = array(
            'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
            'id_kategori'=>$id_kategori
        );
</code>```

答:
$this->input->post('a') as you mentioned here I assume that you have input in the form and its name is a.

In Controller

```<code>if (!empty($this->input->post('a')))
{
    $this->load->model('Model_app');
    $id = $this->model_app->get_subcatoegories($this->input->post('a'));

    if (empty($id)) {
        $id_kategori = '';
    } else {
        $id_kategori = $id[0]['id_kategori'];
    }

}else{
    $id_kategori = '';
}

$data = array(
    'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
    'id_kategori'=>$id_kategori
);
</code>```

In Model

```<code>function get_subcategories($id_kategori)
{
    $query = $this->db->query("SELECT id_kategori FROM subkategori WHERE id_subkategori = $id_kategori");
    return $query->result_array();
}
</code>```

You can get last insterted if with $this->db->insert_id();

Body:
I have table -> subkategori

and I can't insert the id_kategori attribute to table portfolio

i have a code for the model :

function get_subcategories($id_kategori){

$query = $this->db->query("SELECT id_kategori from subkategori WHERE id_subkategori=".$this->input->post('a'));
return $query->result();
}

and the controller here :

if ($this->input->post('a')!=''){
    $this->load->model('Model_app');
    $this->model_app->get_subcatoegories('$id_kategori');
}else{
    $id_kategori = '';
}
$data = array(
            'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
            'id_kategori'=>$id_kategori
        );

Body:
$this->input->post('a') as you mentioned here I assume that you have input in the form and its name is a.

In Controller

if (!empty($this->input->post('a')))
{
    $this->load->model('Model_app');
    $id = $this->model_app->get_subcatoegories($this->input->post('a'));

    if (empty($id)) {
        $id_kategori = '';
    } else {
        $id_kategori = $id[0]['id_kategori'];
    }

}else{
    $id_kategori = '';
}

$data = array(
    'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
    'id_kategori'=>$id_kategori
);

In Model

function get_subcategories($id_kategori)
{
    $query = $this->db->query("SELECT id_kategori FROM subkategori WHERE id_subkategori = $id_kategori");
    return $query->result_array();
}

You can get last insterted if with $this->db->insert_id();


问:
Android keyboard loses focus on touch in Page Renderer
I have an app with a custom keyboard. To do this, I use a page renderer so I can use an Android layout which makes the keyboard logic a lot easier to handle.

When I do a longish press (.5s) on the keyboard, everything works great. When I do a quick tap on a key (what most people do), the EditText targeted by the keyboard loses focus, causing the keyboard to hide and the cursor to be removed from the EditText. I set up a FocusChanged handler to hide the keyboard when the user clicks elsewhere on the screen. With this error, when I do FindFocus after a keyboard tap, the focus returns as null. I showed layout bounds in case of some ghost view receiving the click, but there's nothing there. I don't know what the lifecycle is on a keyboard event, but whatever is causing this issue is called after mKeyboardView.Key.

Any ideas? Thanks.

```<code>class KeyboardPageRenderer : PageRenderer
{

    public CustomKeyboardView mKeyboardView;
    public EditText mTargetView;
    public Android.InputMethodServices.Keyboard mKeyboard;
    Activity activity;
    global::Android.Views.View view;

    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null || Element == null)
        {
            return;
        }

        try
        {
            SetupUserInterface();
            SetupEventHandlers();
            this.AddView(view);
        }
        catch (System.Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"           ERROR: ", ex.Message);
        }
    }

    void SetupUserInterface()
    {
        activity = this.Context as Activity;
        view = activity.LayoutInflater.Inflate(Resource.Layout.Main, this, false);

        mKeyboard = new Android.InputMethodServices.Keyboard(Context, Resource.Xml.keyboard);
        mTargetView = view.FindViewById<EditText>(Resource.Id.target);

        mKeyboardView = view.FindViewById<CustomKeyboardView>(Resource.Id.keyboard_view);
        mKeyboardView.Keyboard = mKeyboard;
    }

    void SetupEventHandlers()
    {
        mTargetView.Touch += (sender, e) =>
        {
            ShowKeyboardWithAnimation();
            e.Handled = false;
            mTargetView.ShowSoftInputOnFocus = false;
        };

        mTargetView.FocusChange += (sender, e) =>
        {
            var idk = FindFocus();
            if (!mTargetView.IsFocused)
            {
                mKeyboardView.Visibility = ViewStates.Gone;
            }

        };

        mKeyboardView.Key += (sender, e) =>
        {
            long eventTime = JavaSystem.CurrentTimeMillis();
            KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

            DispatchKeyEvent(ev);
        };
    }

    public void ShowKeyboardWithAnimation()
    {
        if (mKeyboardView.Visibility == ViewStates.Gone)
        {
            mKeyboardView.Visibility = ViewStates.Visible;
            Android.Views.Animations.Animation animation = AnimationUtils.LoadAnimation(
                Context,
                Resource.Animation.slide_up_bottom
            );
            mKeyboardView.ShowWithAnimation(animation);
        }
    }

    protected override void OnLayout (bool changed, int l, int t, int r, int b)
    {
        base.OnLayout (changed, l, t, r, b);

        var msw = MeasureSpec.MakeMeasureSpec (r - l, MeasureSpecMode.Exactly);
        var msh = MeasureSpec.MakeMeasureSpec (b - t, MeasureSpecMode.Exactly);

        view.Measure (msw, msh);
        view.Layout (0, 0, r - l, b - t);
    }
}
</code>```

EDIT:

Whole project can be found here. iOS project is working pretty well if anyone is looking to implement that as well.

答:
Delete the EditText.FocusChange method and modify your  CustomKeyboardView.Key method like this :

```<code>mKeyboardView.Key += (sender, e) =>
{
    long eventTime = JavaSystem.CurrentTimeMillis();
    KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

    //Make your editText get Focus
    mTargetView.RequestFocus();

    DispatchKeyEvent(ev);
};
</code>```

Effect.

Update :

Here is my workaround :

```<code>mKeyboardView.Key += async (sender, e) =>
{
    long eventTime = JavaSystem.CurrentTimeMillis();
    KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

    DispatchKeyEvent(ev);
    await Task.Delay(1);

    //mTargetView.RequestFocus();
 };
</code>```

Then, the cursor will always be visible.

Effect like this.

Body:
I have an app with a custom keyboard. To do this, I use a page renderer so I can use an Android layout which makes the keyboard logic a lot easier to handle.

When I do a longish press (.5s) on the keyboard, everything works great. When I do a quick tap on a key (what most people do), the EditText targeted by the keyboard loses focus, causing the keyboard to hide and the cursor to be removed from the EditText. I set up a FocusChanged handler to hide the keyboard when the user clicks elsewhere on the screen. With this error, when I do FindFocus after a keyboard tap, the focus returns as null. I showed layout bounds in case of some ghost view receiving the click, but there's nothing there. I don't know what the lifecycle is on a keyboard event, but whatever is causing this issue is called after mKeyboardView.Key.

Any ideas? Thanks.

class KeyboardPageRenderer : PageRenderer
{

    public CustomKeyboardView mKeyboardView;
    public EditText mTargetView;
    public Android.InputMethodServices.Keyboard mKeyboard;
    Activity activity;
    global::Android.Views.View view;

    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null || Element == null)
        {
            return;
        }

        try
        {
            SetupUserInterface();
            SetupEventHandlers();
            this.AddView(view);
        }
        catch (System.Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"           ERROR: ", ex.Message);
        }
    }

    void SetupUserInterface()
    {
        activity = this.Context as Activity;
        view = activity.LayoutInflater.Inflate(Resource.Layout.Main, this, false);

        mKeyboard = new Android.InputMethodServices.Keyboard(Context, Resource.Xml.keyboard);
        mTargetView = view.FindViewById<EditText>(Resource.Id.target);

        mKeyboardView = view.FindViewById<CustomKeyboardView>(Resource.Id.keyboard_view);
        mKeyboardView.Keyboard = mKeyboard;
    }

    void SetupEventHandlers()
    {
        mTargetView.Touch += (sender, e) =>
        {
            ShowKeyboardWithAnimation();
            e.Handled = false;
            mTargetView.ShowSoftInputOnFocus = false;
        };

        mTargetView.FocusChange += (sender, e) =>
        {
            var idk = FindFocus();
            if (!mTargetView.IsFocused)
            {
                mKeyboardView.Visibility = ViewStates.Gone;
            }

        };

        mKeyboardView.Key += (sender, e) =>
        {
            long eventTime = JavaSystem.CurrentTimeMillis();
            KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

            DispatchKeyEvent(ev);
        };
    }

    public void ShowKeyboardWithAnimation()
    {
        if (mKeyboardView.Visibility == ViewStates.Gone)
        {
            mKeyboardView.Visibility = ViewStates.Visible;
            Android.Views.Animations.Animation animation = AnimationUtils.LoadAnimation(
                Context,
                Resource.Animation.slide_up_bottom
            );
            mKeyboardView.ShowWithAnimation(animation);
        }
    }

    protected override void OnLayout (bool changed, int l, int t, int r, int b)
    {
        base.OnLayout (changed, l, t, r, b);

        var msw = MeasureSpec.MakeMeasureSpec (r - l, MeasureSpecMode.Exactly);
        var msh = MeasureSpec.MakeMeasureSpec (b - t, MeasureSpecMode.Exactly);

        view.Measure (msw, msh);
        view.Layout (0, 0, r - l, b - t);
    }
}

EDIT:

Whole project can be found here. iOS project is working pretty well if anyone is looking to implement that as well.

Body:
Delete the EditText.FocusChange method and modify your  CustomKeyboardView.Key method like this :

mKeyboardView.Key += (sender, e) =>
{
    long eventTime = JavaSystem.CurrentTimeMillis();
    KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

    //Make your editText get Focus
    mTargetView.RequestFocus();

    DispatchKeyEvent(ev);
};

Effect.

Update :

Here is my workaround :

mKeyboardView.Key += async (sender, e) =>
{
    long eventTime = JavaSystem.CurrentTimeMillis();
    KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

    DispatchKeyEvent(ev);
    await Task.Delay(1);

    //mTargetView.RequestFocus();
 };

Then, the cursor will always be visible.

Effect like this.


问:
What is the equivalent of the following code in tensorflow?
I have the following function:

```<code>import random

lst = []
for i in range(100):
    lst.append(random.randint(1, 10))

print(lst)

buffer = []

# This is the peace of code which I am interested to convert into tensorflow.
for a in lst:
    buffer.append(a)

    if len(buffer) > 5:
        buffer.pop(0)

    if len(buffer) == 5:
        print(buffer)
</code>```

So, from the code, I need to create a buffer (that could be a variable in tensorflow). This buffer should hold the extracted features from the last conv layer. The variable will be an input to an RNN in my case.

The advantage of this approach is that when we have large images, and when we need to feed a RNN with a (batch of images) * (sequence length) * (size of 1 image), that will require a very big batch of images to be loaded into the main memory. On the other hand, according to the code above, we will be feeding 1 image at a time using the Datasets from tensorflow, or an input queue or any other alternative. As a result, we will be storing in memory the feature of size: batch_size * sequence_length * feature space .In addition, we can say:

```<code>if len(buffer) == n:
    # empty out the buffer after using its elements
    buffer = [] # Or any other alternative way
</code>```

I am aware that I can feed my network batches of images, but I  need to accomplish the mentioned code based on some literature.

Any help is much appreciated!!

答:
I try to regenerate your output using tf.FIFOQueue (https://www.tensorflow.org/api_docs/python/tf/FIFOQueue). I have given my code below with the comments where necessary.

```<code>BATCH_SIZE = 20

lst = []
for i in range(BATCH_SIZE):
    lst.append(random.randint(1, 10))
print(lst)

curr_data = np.reshape(lst, (BATCH_SIZE, 1)) # reshape the tensor so that [BATCH_SIZE 1]

# queue starts here
queue_input_data = tf.placeholder(tf.int32, shape=[1]) # Placeholder for feed the data

queue = tf.FIFOQueue(capacity=50, dtypes=[tf.int32], shapes=[1]) # Queue define here

enqueue_op = queue.enqueue([queue_input_data])  # enqueue operation
len_op = queue.size()  # chek the queue size

#check the length of the queue and dequeue one if greater than 5
dequeue_one = tf.cond(tf.greater(len_op, 5), lambda: queue.dequeue(), lambda: 0)
#check the length of the queue and dequeue five elemts if equals to 5
dequeue_many = tf.cond(tf.equal(len_op, 5), lambda:queue.dequeue_many(5), lambda: 0)

with tf.Session() as session:
    for i in range(BATCH_SIZE):
        _ = session.run(enqueue_op, feed_dict={queue_input_data: curr_data[i]}) # enqueue one element each ietaration
        len = session.run(len_op)  # check the legth of the queue
        print(len)

        element = session.run(dequeue_one)  # dequeue the first element
        print(element)
</code>```

However, following two problems are associated with the above code,

Only the dequeue one and dequeue many operations are available and you cannot see the elements inside the queue (I don't think you will need this since you are looking something like a pipeline).

I think that tf.cond is the only way to implement a conditional operation (I couldn't find any other suitable function similar to that). However, since its similar to the if-then-else statement, its mandatory to define an operation when the statement is false also (not just having only if statement without the else). Since Tensorflow is all about building a graph I think its necessary to include the two branches (when the condition is true and false).

Moreover, a good explanation for Tensorflow input pipelines can be found here (http://ischlag.github.io/2016/11/07/tensorflow-input-pipeline-for-large-datasets/).

Hope this helps.

Body:
I have the following function:

import random

lst = []
for i in range(100):
    lst.append(random.randint(1, 10))

print(lst)

buffer = []

# This is the peace of code which I am interested to convert into tensorflow.
for a in lst:
    buffer.append(a)

    if len(buffer) > 5:
        buffer.pop(0)

    if len(buffer) == 5:
        print(buffer)

So, from the code, I need to create a buffer (that could be a variable in tensorflow). This buffer should hold the extracted features from the last conv layer. The variable will be an input to an RNN in my case.

The advantage of this approach is that when we have large images, and when we need to feed a RNN with a (batch of images) * (sequence length) * (size of 1 image), that will require a very big batch of images to be loaded into the main memory. On the other hand, according to the code above, we will be feeding 1 image at a time using the Datasets from tensorflow, or an input queue or any other alternative. As a result, we will be storing in memory the feature of size: batch_size * sequence_length * feature space .In addition, we can say:

if len(buffer) == n:
    # empty out the buffer after using its elements
    buffer = [] # Or any other alternative way

I am aware that I can feed my network batches of images, but I  need to accomplish the mentioned code based on some literature.

Any help is much appreciated!!

Body:
I try to regenerate your output using tf.FIFOQueue (https://www.tensorflow.org/api_docs/python/tf/FIFOQueue). I have given my code below with the comments where necessary.

BATCH_SIZE = 20

lst = []
for i in range(BATCH_SIZE):
    lst.append(random.randint(1, 10))
print(lst)

curr_data = np.reshape(lst, (BATCH_SIZE, 1)) # reshape the tensor so that [BATCH_SIZE 1]

# queue starts here
queue_input_data = tf.placeholder(tf.int32, shape=[1]) # Placeholder for feed the data

queue = tf.FIFOQueue(capacity=50, dtypes=[tf.int32], shapes=[1]) # Queue define here

enqueue_op = queue.enqueue([queue_input_data])  # enqueue operation
len_op = queue.size()  # chek the queue size

#check the length of the queue and dequeue one if greater than 5
dequeue_one = tf.cond(tf.greater(len_op, 5), lambda: queue.dequeue(), lambda: 0)
#check the length of the queue and dequeue five elemts if equals to 5
dequeue_many = tf.cond(tf.equal(len_op, 5), lambda:queue.dequeue_many(5), lambda: 0)

with tf.Session() as session:
    for i in range(BATCH_SIZE):
        _ = session.run(enqueue_op, feed_dict={queue_input_data: curr_data[i]}) # enqueue one element each ietaration
        len = session.run(len_op)  # check the legth of the queue
        print(len)

        element = session.run(dequeue_one)  # dequeue the first element
        print(element)

However, following two problems are associated with the above code,

Only the dequeue one and dequeue many operations are available and you cannot see the elements inside the queue (I don't think you will need this since you are looking something like a pipeline).

I think that tf.cond is the only way to implement a conditional operation (I couldn't find any other suitable function similar to that). However, since its similar to the if-then-else statement, its mandatory to define an operation when the statement is false also (not just having only if statement without the else). Since Tensorflow is all about building a graph I think its necessary to include the two branches (when the condition is true and false).

Moreover, a good explanation for Tensorflow input pipelines can be found here (http://ischlag.github.io/2016/11/07/tensorflow-input-pipeline-for-large-datasets/).

Hope this helps.


问:
Do not reset value in select drop down on event of reset button click
I navigate to a page after successful completion of a webservice call and will populate values retrieved from webservice in to input fields of a page and will disable those fields after population.

Now, On click of reset, these values should not be cleared. I am successful in implementing this functionality for input fields by using defaultValue concept.

for e.g. During population of values in to form, I use
    inputField.defaultValue = inputField.value

and On click of reset button

```<code>inputField.value = inputField.defaultValue;
</code>```

to keep the values from clearing..

However, I am not able to achieve the same with select drop down. Its value is getting cleared upon reset button. How to achieve this in Javascript?

答:
Changing the value of the selection box work different than text boxes. You need to grab the selected values index and then need to use the following code to reset it.

```<code>document.getElementById("select").selectedIndex = saved_index
</code>```

Hope this will work for you.

Body:
I navigate to a page after successful completion of a webservice call and will populate values retrieved from webservice in to input fields of a page and will disable those fields after population.

Now, On click of reset, these values should not be cleared. I am successful in implementing this functionality for input fields by using defaultValue concept.

for e.g. During population of values in to form, I use
    inputField.defaultValue = inputField.value

and On click of reset button

inputField.value = inputField.defaultValue;

to keep the values from clearing..

However, I am not able to achieve the same with select drop down. Its value is getting cleared upon reset button. How to achieve this in Javascript?

Body:
Changing the value of the selection box work different than text boxes. You need to grab the selected values index and then need to use the following code to reset it.

document.getElementById("select").selectedIndex = saved_index

Hope this will work for you.


问:
Zip and Unzip File in Powershell 4
I am using Windows Server 2012 R2 (64 bit). I have powershell version 4 available in it. I am trying to zip and unzip files. When I try Write-Zip command, it throws me following error:

Write-Zip : The term 'Write-Zip' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

What should I do to fix it? Do I need to install zip/winrar in the server? Or is there any other command do zip/unzip files?

答:
You can use custom powershell object New-Object -ComObject Shell.Application and copy the file with flags to unzip.

```<code>$filePath = "foo.zip"
$shell = New-Object -ComObject Shell.Application
$zipFile = $shell.NameSpace($filePath)
$destinationFolder = $shell.NameSpace("C:\Program Files\WindowsPowerShell\Modules")

$copyFlags = 0x00
$copyFlags += 0x04 # Hide progress dialogs
$copyFlags += 0x10 # Overwrite existing files

$destinationFolder.CopyHere($zipFile.Items(), $copyFlags)
</code>```

Credit source https://github.com/hashicorp/best-practices/blob/master/packer/scripts/windows/install_windows_updates.ps1#L12-L22

This does not work with windows 'core' edition. If possible, upgrade to powershell 5 and use Expand Archive since it is much simpler.

Title: Zip and Unzip File in Powershell 4

Body:
You can use custom powershell object New-Object -ComObject Shell.Application and copy the file with flags to unzip.

$filePath = "foo.zip"
$shell = New-Object -ComObject Shell.Application
$zipFile = $shell.NameSpace($filePath)
$destinationFolder = $shell.NameSpace("C:\Program Files\WindowsPowerShell\Modules")

$copyFlags = 0x00
$copyFlags += 0x04 # Hide progress dialogs
$copyFlags += 0x10 # Overwrite existing files

$destinationFolder.CopyHere($zipFile.Items(), $copyFlags)

Credit source https://github.com/hashicorp/best-practices/blob/master/packer/scripts/windows/install_windows_updates.ps1#L12-L22

This does not work with windows 'core' edition. If possible, upgrade to powershell 5 and use Expand Archive since it is much simpler.


问:
Recursion function in python- check if element in a list is already present and generate a new one
I am trying to write a recursion function with python which checks for names in a list and gives out a new name. The name of csv to be checked can be formed using parameters comm and index passed to the function.
I wrote  the below function and expecting the output to be printed as string

```<code>csv_full_list=["mycsv_0","mycsv_1"]

def create_csv_name(comm,index):
    if comm+"_"+str(index) in csv_full_list:
        create_csv_name(comm,index+1)
    else:
        return comm+"_"+str(index)
print create_csv_name("mycsv",0)
</code>```

can anyone tel me why this function returning
  none type

instead

of string.

答:
You have to increment the index to avoid endless recursion.</p>

```<code>csv_full_list = ['mycsv_0', 'mycsv_1']

def create_csv_name(comm, index):
    global csv_full_list
    if comm + '_' + str(index) in csv_full_list:
        index += 1 # increment index by 1
        create_csv_name(comm, index=index)
    else:
        return '%s_%i' % (comm, index)

print(create_csv_name('mycsv', 0))
</code>```

Body:
I am trying to write a recursion function with python which checks for names in a list and gives out a new name. The name of csv to be checked can be formed using parameters comm and index passed to the function.
I wrote  the below function and expecting the output to be printed as string

csv_full_list=["mycsv_0","mycsv_1"]

def create_csv_name(comm,index):
    if comm+"_"+str(index) in csv_full_list:
        create_csv_name(comm,index+1)
    else:
        return comm+"_"+str(index)
print create_csv_name("mycsv",0)

can anyone tel me why this function returning
  none type

instead

of string.

Body:
You have to increment the index to avoid endless recursion.

csv_full_list = ['mycsv_0', 'mycsv_1']

def create_csv_name(comm, index):
    global csv_full_list
    if comm + '_' + str(index) in csv_full_list:
        index += 1 # increment index by 1
        create_csv_name(comm, index=index)
    else:
        return '%s_%i' % (comm, index)

print(create_csv_name('mycsv', 0))


问:
asp.net core data protection : An exception was thrown while deserializing the token
Im running asp.net core on a webfarm using redis as dataprotection storage.

my app is under heavy load so i get following error constantly from redis :

Timeout performing EVAL, inst: 9, queue: 1448, qu: 0, qs: 1448, qc: 0,
  wr: 0, wq: 0, in: 65536, ar: 0, clientName: xxxx

The way redis was initialized at startup.cs using microsoft recommendation was

```<code>var redis = ConnectionMultiplexer.Connect("<URI>");
services.AddDataProtection()
    .PersistKeysToRedis(redis, "DataProtection-Keys");
</code>```

so aftre reading some articles regarding not redis being thread safe i change redis initialization to be thread safe as suggested at azure and here

```<code>private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => {
    return ConnectionMultiplexer.Connect("mycache.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
});

public static ConnectionMultiplexer Connection {
    get {
        return lazyConnection.Value;
    }
}
</code>```

but now the problem is that every second or so i get the following errors:

The antiforgery token could not be decrypted. --->
  System.Security.Cryptography.CryptographicException: The key {xxxxxxx}
  was not found in the key ring.

or

An exception was thrown while deserializing the token.

or

Error unprotecting the session cookie.

or

System.Security.Cryptography.CryptographicException: The key {xxxxx}
  was not found in the key ring.

what's the problem and what should i do?

should i change initialization again? but then app will halt under heavy load.

Updated

More Info:

i have accidentally used a wrong connection string for redis and again change it to correct one.

Of course there could be other bugs that cause this error.

How can i handle and mitigate this error now?

The error is clear and may be it is not possible to reproduce it on another dev env.

But there should be a way to handle this kind of error.

答: To avoid the data protection error, you can run a PowerShell script. https://raw.githubusercontent.com/aspnet/DataProtection/dev/Provision-AutoGenKeys.ps1. you just need to run the script as Administrator and provide the app pool name</p>

Body:
Im running asp.net core on a webfarm using redis as dataprotection storage.

my app is under heavy load so i get following error constantly from redis :

Timeout performing EVAL, inst: 9, queue: 1448, qu: 0, qs: 1448, qc: 0,
  wr: 0, wq: 0, in: 65536, ar: 0, clientName: xxxx

The way redis was initialized at startup.cs using microsoft recommendation was

var redis = ConnectionMultiplexer.Connect("<URI>");
services.AddDataProtection()
    .PersistKeysToRedis(redis, "DataProtection-Keys");

so aftre reading some articles regarding not redis being thread safe i change redis initialization to be thread safe as suggested at azure and here

private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => {
    return ConnectionMultiplexer.Connect("mycache.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
});

public static ConnectionMultiplexer Connection {
    get {
        return lazyConnection.Value;
    }
}

but now the problem is that every second or so i get the following errors:

The antiforgery token could not be decrypted. --->
  System.Security.Cryptography.CryptographicException: The key {xxxxxxx}
  was not found in the key ring.

or

An exception was thrown while deserializing the token.

or

Error unprotecting the session cookie.

or

System.Security.Cryptography.CryptographicException: The key {xxxxx}
  was not found in the key ring.

what's the problem and what should i do?

should i change initialization again? but then app will halt under heavy load.

Updated

More Info:

i have accidentally used a wrong connection string for redis and again change it to correct one.

Of course there could be other bugs that cause this error.

How can i handle and mitigate this error now?

The error is clear and may be it is not possible to reproduce it on another dev env.

But there should be a way to handle this kind of error.


问:
Database execution results and mybatis execution results are inconsistent
use:

```<code>1.mysql 5.6.36
2.mybatis 3.4.5
</code>```

in the database,i exceute the four sql,here the logs:

```<code>SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@54b0f2cd] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://xxxx/xxxx, UserName=xxxx@xxxx, MySQL-AB JDBC Driver] will not be managed by Spring
==>  Preparing: select IFNULL(count(*),0) from goods_info
==> Parameters:
<==    Columns: IFNULL(count(*),0)
<==        Row: 149
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@54b0f2cd]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@25b99cbf] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://xxxx/xxxx, UserName=xxxx@xxxx, MySQL-AB JDBC Driver] will not be managed by Spring
==>  Preparing: select sum(browsed_times) from goods_info
==> Parameters:
<==    Columns: sum(browsed_times)
<==        Row: 10128
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@25b99cbf]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5d271b1a] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://xxxx/xxxx, UserName=xxxx@xxxx, MySQL-AB JDBC Driver] will not be managed by Spring
==>  Preparing: select IFNULL(count(*),0) from user
==> Parameters:
<==    Columns: IFNULL(count(*),0)
<==        Row: 694
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5d271b1a]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@20bbe729] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://xxxx/xxxxx, UserName=xxxx@xxxx, MySQL-AB JDBC Driver] will not be managed by Spring
==>  Preparing: select IFNULL(sum(total_price),0) from order_build where order_status = '已支付'
==> Parameters:
<==    Columns: IFNULL(sum(total_price),0)
<==        Row: 0.00
<==      Total: 1
</code>```

and now i find the first three are consistent with database,but the last one is error.when i excute it in the database ,i can get the correct result.

here is my mapper.xml:

```<code><select id="getTotalMoney" resultType="String">
    select IFNULL(sum(total_price),0)
    from order_build
    where order_status =
    '已支付'
</select>
</code>```

in database ,i get this result:

i am upset.i don`t know why.

答:
Reslove.
i specify the Encoding with utf8.</p>

Body:
use:

1.mysql 5.6.36
2.mybatis 3.4.5

in the database,i exceute the four sql,here the logs:

SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@54b0f2cd] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://xxxx/xxxx, UserName=xxxx@xxxx, MySQL-AB JDBC Driver] will not be managed by Spring
==>  Preparing: select IFNULL(count(*),0) from goods_info
==> Parameters:
<==    Columns: IFNULL(count(*),0)
<==        Row: 149
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@54b0f2cd]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@25b99cbf] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://xxxx/xxxx, UserName=xxxx@xxxx, MySQL-AB JDBC Driver] will not be managed by Spring
==>  Preparing: select sum(browsed_times) from goods_info
==> Parameters:
<==    Columns: sum(browsed_times)
<==        Row: 10128
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@25b99cbf]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5d271b1a] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://xxxx/xxxx, UserName=xxxx@xxxx, MySQL-AB JDBC Driver] will not be managed by Spring
==>  Preparing: select IFNULL(count(*),0) from user
==> Parameters:
<==    Columns: IFNULL(count(*),0)
<==        Row: 694
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5d271b1a]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@20bbe729] was not registered for synchronization because synchronization is not active
JDBC Connection [jdbc:mysql://xxxx/xxxxx, UserName=xxxx@xxxx, MySQL-AB JDBC Driver] will not be managed by Spring
==>  Preparing: select IFNULL(sum(total_price),0) from order_build where order_status = '已支付'
==> Parameters:
<==    Columns: IFNULL(sum(total_price),0)
<==        Row: 0.00
<==      Total: 1

and now i find the first three are consistent with database,but the last one is error.when i excute it in the database ,i can get the correct result.

here is my mapper.xml:

<select id="getTotalMoney" resultType="String">
    select IFNULL(sum(total_price),0)
    from order_build
    where order_status =
    '已支付'
</select>

in database ,i get this result:

i am upset.i don`t know why.


答:
In your, if statement you didn't assign the database value to the $id_kategori variable. Hence while inserting the empty value into the table it inserts as 0(int field).

And also when you pass a variable to a function it should not be single quoted. You have to pass the post variable but you are passing a variable which is undefined.

```<code>if ($this->input->post('a')!=''){
    $this->load->model('Model_app');
    $category = $this->model_app->get_subcatoegories($this->input->post('a'));
    $id_kategori = $category['id_kategori];
}else{
    $id_kategori = '';
}
$data = array(
            'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
            'id_kategori'=>$id_kategori
        );
</code>```

Title: how to input the parent id into database in different table

Body:
In your, if statement you didn't assign the database value to the $id_kategori variable. Hence while inserting the empty value into the table it inserts as 0(int field).

And also when you pass a variable to a function it should not be single quoted. You have to pass the post variable but you are passing a variable which is undefined.

if ($this->input->post('a')!=''){
    $this->load->model('Model_app');
    $category = $this->model_app->get_subcatoegories($this->input->post('a'));
    $id_kategori = $category['id_kategori];
}else{
    $id_kategori = '';
}
$data = array(
            'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
            'id_kategori'=>$id_kategori
        );


问:
Redirect Standard Output/error to log file
Looking for a way to redirect std error and std output to a log file in Tcsh shell.

Tried ./ShellFile.sh 2>&1 | pathToLogFile.log
and got the error "Ambiguous output redirect"

Would appreciate any inputs.

答:
On a side note, tee(1) may be of use if you want to see output both on the terminal and in a file.

```<code>  ./script 2>&1 | tee logfile.txt
</code>```

Body:
On a side note, tee(1) may be of use if you want to see output both on the terminal and in a file.

  ./script 2>&1 | tee logfile.txt

ContentLicense: CC BY-SA 2.5


问:
Pyinstaller and Cython PermissionError: [Error 13] Permission denied
I am trying to integrate Cython + Pyinstaller.  I am wanting to lastly compile the files with Cython but it keeps giving me: [Error 13] Permission denied

I have tried other folders, given myself full administration access.

My original file:

```<code>from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as expected
from selenium.webdriver.support.wait import WebDriverWait

if name == "main":
options = Options()
options.add_argument('-headless')
driver = Firefox(executable_path='geckodriver', firefox_options=options)
wait = WebDriverWait(driver, timeout=10)
driver.get('http://www.google.com')
wait.until(expected.visibility_of_element_located((By.NAME, 'q'))).send_keys('headless firefox' + Keys.ENTER)
wait.until(expected.visibility_of_element_located((By.CSS_SELECTOR, '#ires a'))).click()
print(driver.page_source)
driver.quit()
</code>```

1 Convert py to pyx (renaming in Pycharm)

```<code>h1test.py -> h1test.pyx (Pyx file)
</code>```

2 Creating a pyd and C file.
cython -a h1test.pyx which creates cython -a yourmod.pyx the C, pyd file.

3 Create setup.py file

Creating Cython setup...

```<code>setup(
name="test",
scripts=glob("*"),
ext_modules=cythonize("h1test.pyx")
)
</code>```

Output:

```<code>usage: Setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: Setup.py --help [cmd1 cmd2 ...]
or: Setup.py --help-commands
or: Setup.py cmd --help

error: no commands supplied

Process finished with exit code 1
</code>```

Run:

```<code>python setup.py develop
</code>```

Which creates test.egg-info folder

Lastly the thing which is causing me grief.

I copy everything into C:\Users\Stan\test.egg-info

I then run:

```<code>pyinstaller -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -F C:\Users\Stan\test.egg-info
</code>```

Error message:

```<code>C:\Users\Stan\test.egg-info
PermissionError: [Errno 13] Permission denied: 'C:\Users\Stan'

C:\WINDOWS\system32>pyinstaller -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -F C:\Users\Stan\test.egg-info
357 INFO: PyInstaller: 3.3
358 INFO: Python: 3.6.3
360 INFO: Platform: Windows-10-10.0.16299-SP0
362 INFO: wrote C:\WINDOWS\system32\test.spec
364 INFO: UPX is not available.
365 INFO: Extending PYTHONPATH with paths
['C:\Users\Stan', 'C:\WINDOWS\system32']
366 INFO: checking Analysis
366 INFO: Building Analysis because out00-Analysis.toc is non existent
366 INFO: Initializing module dependency graph...
374 INFO: Initializing module graph hooks...
375 INFO: Analyzing base_library.zip ...
3521 INFO: running Analysis out00-Analysis.toc
3523 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
required by c:\users\Stan\anaconda3\python.exe
4066 INFO: Caching module hooks...
4070 INFO: Analyzing C:\Users\Stan\test.egg-info
Traceback (most recent call last):
File "c:\users\Stan\anaconda3\lib\runpy.py", line 193, in run_module_as_main
"main", mod_spec)
File "c:\users\Stan\anaconda3\lib\runpy.py", line 85, in run_code
exec(code, run_globals)
File "C:\Users\Stan\Anaconda3\Scripts\pyinstaller.exe_main.py", line 9, in
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller_main.py", line 92, in run
run_build(pyi_config, spec_file, **vars(args))
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller_main_.py", line 46, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 791, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 737, in build
exec(text, spec_namespace)
File "", line 16, in
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 213, in init
self.postinit()
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\datastruct.py", line 161, in postinit
self.assemble()
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 415, in assemble
priority_scripts.append(self.graph.run_script(script))
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\depend\analysis.py", line 201, in run_script
self._top_script_node = super(PyiModuleGraph, self).run_script(pathname)
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\lib\modulegraph\modulegraph.py", line 1326, in run_script
</code>```

答: You may have to run the command line window as administrator</p>

Body:
I am trying to integrate Cython + Pyinstaller.  I am wanting to lastly compile the files with Cython but it keeps giving me: [Error 13] Permission denied

I have tried other folders, given myself full administration access.

My original file:

from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as expected
from selenium.webdriver.support.wait import WebDriverWait

if name == "main":
options = Options()
options.add_argument('-headless')
driver = Firefox(executable_path='geckodriver', firefox_options=options)
wait = WebDriverWait(driver, timeout=10)
driver.get('http://www.google.com')
wait.until(expected.visibility_of_element_located((By.NAME, 'q'))).send_keys('headless firefox' + Keys.ENTER)
wait.until(expected.visibility_of_element_located((By.CSS_SELECTOR, '#ires a'))).click()
print(driver.page_source)
driver.quit()

1 Convert py to pyx (renaming in Pycharm)

h1test.py -> h1test.pyx (Pyx file)

2 Creating a pyd and C file.
cython -a h1test.pyx which creates cython -a yourmod.pyx the C, pyd file.

3 Create setup.py file

Creating Cython setup...

setup(
name="test",
scripts=glob("*"),
ext_modules=cythonize("h1test.pyx")
)

Output:

usage: Setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: Setup.py --help [cmd1 cmd2 ...]
or: Setup.py --help-commands
or: Setup.py cmd --help

error: no commands supplied

Process finished with exit code 1

Run:

python setup.py develop

Which creates test.egg-info folder

Lastly the thing which is causing me grief.

I copy everything into C:\Users\Stan\test.egg-info

I then run:

pyinstaller -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -F C:\Users\Stan\test.egg-info

Error message:

C:\Users\Stan\test.egg-info
PermissionError: [Errno 13] Permission denied: 'C:\Users\Stan'

C:\WINDOWS\system32>pyinstaller -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -r h1test.cp36-win_amd64.pyd,dll,h1test.cp36-win_amd64.pyd -F C:\Users\Stan\test.egg-info
357 INFO: PyInstaller: 3.3
358 INFO: Python: 3.6.3
360 INFO: Platform: Windows-10-10.0.16299-SP0
362 INFO: wrote C:\WINDOWS\system32\test.spec
364 INFO: UPX is not available.
365 INFO: Extending PYTHONPATH with paths
['C:\Users\Stan', 'C:\WINDOWS\system32']
366 INFO: checking Analysis
366 INFO: Building Analysis because out00-Analysis.toc is non existent
366 INFO: Initializing module dependency graph...
374 INFO: Initializing module graph hooks...
375 INFO: Analyzing base_library.zip ...
3521 INFO: running Analysis out00-Analysis.toc
3523 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
required by c:\users\Stan\anaconda3\python.exe
4066 INFO: Caching module hooks...
4070 INFO: Analyzing C:\Users\Stan\test.egg-info
Traceback (most recent call last):
File "c:\users\Stan\anaconda3\lib\runpy.py", line 193, in run_module_as_main
"main", mod_spec)
File "c:\users\Stan\anaconda3\lib\runpy.py", line 85, in run_code
exec(code, run_globals)
File "C:\Users\Stan\Anaconda3\Scripts\pyinstaller.exe_main.py", line 9, in
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller_main.py", line 92, in run
run_build(pyi_config, spec_file, **vars(args))
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller_main_.py", line 46, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 791, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 737, in build
exec(text, spec_namespace)
File "", line 16, in
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 213, in init
self.postinit()
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\datastruct.py", line 161, in postinit
self.assemble()
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 415, in assemble
priority_scripts.append(self.graph.run_script(script))
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\depend\analysis.py", line 201, in run_script
self._top_script_node = super(PyiModuleGraph, self).run_script(pathname)
File "c:\users\Stan\anaconda3\lib\site-packages\PyInstaller\lib\modulegraph\modulegraph.py", line 1326, in run_script


问:
Send data to JS when PHP is told to do so
Here's an example. One user connects to the website and does some stuff. JS sends changes to PHP and it's processed. Say another user that connected at the same time needs to be notified of this change. So PHP somehow tells the second users browser through JS or something to change some HTML to the second user is aware of said changes. Is there a way I can do this? Or is it a no can do?</p>

答:
you can use this</p>

```<code>$.ajax({
    url: "url",
    type: "POST",
    data: params,
    success: success(){},
    error: error()
});
</code>```

Body:
you can use this

$.ajax({
    url: "url",
    type: "POST",
    data: params,
    success: success(){},
    error: error()
});


问:
Selected Tabbar padding issue
I am creating sample project in swift. I have added tabbar controller in this project. I have set selectionIndicatorImage to highlight selected tab. I'm getting extra padding in selected tab.

Here is code for highlight selected tab :

```<code>let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: (tabBar.frame.width / numberOfItems), height: tabBar.frame.height)
tabBar.selectionIndicatorImage = UIImage.imageWithColor(color: UIColor(red:123.0/255.0, green:31.0/255.0, blue:162.0/255.0, alpha:1.0), size: tabBarItemSize).resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
</code>```

With the use of above code I'm getting output like this,

Any suggestion would be appreciated.

Thanks.

答:
There is some default spacing while you select any UITabBar. To overcome below are the two solutions you can go with it.

Solution 1:

You can change UITabBar x-origin slightly to left:

```<code>self.tabBarController!.tabBar.frame = self.tabBarController!.tabBar.frame.insetBy(dx: -2, dy: 0)
</code>```

Solution 2:

```<code>self.tabBarController!.tabBarItem.imageInsets = UIEdgeInsetsMake(0, -2, 0, 0)
</code>```

Title: Selected Tabbar padding issue

Body:
I am creating sample project in swift. I have added tabbar controller in this project. I have set selectionIndicatorImage to highlight selected tab. I'm getting extra padding in selected tab.

Here is code for highlight selected tab :

let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: (tabBar.frame.width / numberOfItems), height: tabBar.frame.height)
tabBar.selectionIndicatorImage = UIImage.imageWithColor(color: UIColor(red:123.0/255.0, green:31.0/255.0, blue:162.0/255.0, alpha:1.0), size: tabBarItemSize).resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))

With the use of above code I'm getting output like this,

Any suggestion would be appreciated.

Thanks.

Body:
There is some default spacing while you select any UITabBar. To overcome below are the two solutions you can go with it.

Solution 1:

You can change UITabBar x-origin slightly to left:

self.tabBarController!.tabBar.frame = self.tabBarController!.tabBar.frame.insetBy(dx: -2, dy: 0)

Solution 2:

self.tabBarController!.tabBarItem.imageInsets = UIEdgeInsetsMake(0, -2, 0, 0)


问:
where to use this code?
where to use this code :</p>

```<code>EXEC sp_attach_db @dbname = N'myASPNetDB',
   @filename1 = N'c:\mypathdata\myaspnet.mdf',
   @filename2 = N'c:\mypathlogs\myaspnet_log.ldf'
</code>```

答: You would run that within SQL Server Management Studio.</p>

Title: where to use this code?

Body:
where to use this code :

EXEC sp_attach_db @dbname = N'myASPNetDB',
   @filename1 = N'c:\mypathdata\myaspnet.mdf',
   @filename2 = N'c:\mypathlogs\myaspnet_log.ldf'


问:
more elegant xpath solution?
I am scraping a forum and am trying to retrieve stats about the post, specifically the number of views a post gets and the number of replies.

The page source for what I am parsing looks like this:

```<code><ul class="ipsDataItem_stats">
<li>
    <span class="ipsDataItem_stats_number">61</span>
    <span class="ipsDataItem_stats_type"> replies</span>
</li>
<li class="ipsType_light">
    <span class="ipsDataItem_stats_number">6,106</span>
    <span class="ipsDataItem_stats_type"> views</span>
</li>
</code>```

And I've hacked together some code that pulls what I'm looking for, but I'm wonder how you xpath experts would have handled this.

```<code>Stats = node.find_elements_by_xpath('.//ul[@class="ipsDataItem_stats"]')
Replies = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[0].text
Views = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[1].text
</code>```

My solution relies on the stats being in a certain order, and I'm wondering if there's a more accurate way to achieve the same result.

eg psuedo code:

```<code>Replies = node.find_elements_by_xpath({get span text where class = "ipsDataItem_stats" and sibling span class = "ipsDataItem_stats_type" and text = "replies"})
</code>```

答:
You could look at label that describes a stat. The general xpath would look something like this:

```<code>'//ul[@class="ipsDataItem_stats"][<FILL HERE RECORDS POSITION>]//li[contains(., "<FILL HERE RECORDS LABEL>")]/span[@class="ipsDataItem_stats_number"]'
</code>```

For replies and views we get following xpath:

```<code>FirstRecordsRepliesXpath = '//ul[@class="ipsDataItem_stats"][0]//li[contains(., "replies")]/span[@class="ipsDataItem_stats_number"]'
FirstRecordsViewsXpath = '//ul[@class="ipsDataItem_stats"][0]//li[contains(., "views")]/span[@class="ipsDataItem_stats_number"]'
</code>```

This way you don't need to know anything about the order. But you need to know labels, which should be ok.

Title: more elegant xpath solution?

Body:
I am scraping a forum and am trying to retrieve stats about the post, specifically the number of views a post gets and the number of replies.

The page source for what I am parsing looks like this:

    61
     replies

    6,106
     views

And I've hacked together some code that pulls what I'm looking for, but I'm wonder how you xpath experts would have handled this.

Stats = node.find_elements_by_xpath('.//ul[@class="ipsDataItem_stats"]')
Replies = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[0].text
Views = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[1].text

My solution relies on the stats being in a certain order, and I'm wondering if there's a more accurate way to achieve the same result.

eg psuedo code:

Replies = node.find_elements_by_xpath({get span text where class = "ipsDataItem_stats" and sibling span class = "ipsDataItem_stats_type" and text = "replies"})

Body:
You could look at label that describes a stat. The general xpath would look something like this:

'//ul[@class="ipsDataItem_stats"][<FILL HERE RECORDS POSITION>]//li[contains(., "<FILL HERE RECORDS LABEL>")]/span[@class="ipsDataItem_stats_number"]'

For replies and views we get following xpath:

FirstRecordsRepliesXpath = '//ul[@class="ipsDataItem_stats"][0]//li[contains(., "replies")]/span[@class="ipsDataItem_stats_number"]'
FirstRecordsViewsXpath = '//ul[@class="ipsDataItem_stats"][0]//li[contains(., "views")]/span[@class="ipsDataItem_stats_number"]'

This way you don't need to know anything about the order. But you need to know labels, which should be ok.


问:
calculate petrol consumed per second and show on web
I want to calculate the petrol consumed per second and show on the website as a footer.

The calculation will be like, petrol consumption increases by 0.13L per second, so for this, I thought to use setInterval for one second and call a function which will calculate the petrol consumption.

Till now I attempted this:

function random_no() {
  var i;
  i = i + 0.13;

  // jQuery('#random_no_container').html(ran);
}

window.setInterval(function() {
  /// call your function here
  random_no();
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="random_no_container">
  Hello. Here you can see petrol consumption per second
</div></code>```

How can I show the value of I in liters, in the footer?

I am a beginner, please help, thank you.

答:
I hope this willl help you :) </p>

```<code>var i = 10; // Initialize your variable here; I have used 10.
    function random_no() {
      i = i + 0.13;
      document.getElementById("petrol-cons").innerHTML = i; // the span will contain the value of petrol (value of i )
    }

    window.setInterval(function() {
      /// call your function here
      random_no();
    }, 1000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  Hello. Here you can see petrol consumption per second :
  <span id="petrol-cons"></span>

</div>
</code>```

Body:
I want to calculate the petrol consumed per second and show on the website as a footer.

The calculation will be like, petrol consumption increases by 0.13L per second, so for this, I thought to use setInterval for one second and call a function which will calculate the petrol consumption.

Till now I attempted this:

function random_no() {
  var i;
  i = i + 0.13;

  // jQuery('#random_no_container').html(ran);
}

window.setInterval(function() {
  /// call your function here
  random_no();
}, 1000);

  Hello. Here you can see petrol consumption per second

How can I show the value of I in liters, in the footer?

I am a beginner, please help, thank you.

Body:
I hope this willl help you :)

var i = 10; // Initialize your variable here; I have used 10.
    function random_no() {
      i = i + 0.13;
      document.getElementById("petrol-cons").innerHTML = i; // the span will contain the value of petrol (value of i )
    }

    window.setInterval(function() {
      /// call your function here
      random_no();
    }, 1000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  Hello. Here you can see petrol consumption per second :
  <span id="petrol-cons"></span>

</div>


问:
Using "npm run build" fails with "npm ERR! missing script: build"
How can I fix this error, I'm running Windows 10

When i try to npm run build on the cmd i get this error

```<code>C:\Users\anai_> npm run build
npm ERR! missing script: build
</code>```

Here is the log of the run

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'build' ]
2 info using npm@5.5.1
3 info using node@v9.1.0
4 verbose config Skipping project config: C:\Users\anai_/.npmrc. (matches userconfig)
5 verbose stack Error: missing script: build
5 verbose stack     at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:151:19)
5 verbose stack     at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:61:5
5 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:115:5
5 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:402:5
5 verbose stack     at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:357:45)
5 verbose stack     at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:400:3)
5 verbose stack     at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:160:5)
5 verbose stack     at ReadFileContext.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:332:20)
5 verbose stack     at ReadFileContext.callback (C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:78:16)
5 verbose stack     at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:437:13)
6 verbose cwd C:\Users\anai_
7 verbose Windows_NT 10.0.15063
8 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
9 verbose node v9.1.0
10 verbose npm  v5.5.1
11 error missing script: build
12 verbose exit [ 1, true ]
</code>```

Although the error refers to a missing script build, i have placed a 'build' script in my package.json

```<code>{
  "name": "es6",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^3.8.1"
  }

}
</code>```

and this is my webpack.config.js file

```<code>module.exports = {
  entry: ['./app/index.js'],
  output: {
    path: './build',
    filename: 'bundle.js'

  }
}
</code>```

Why is this error happening, and how can the problem be fixed?

答:
You put "npm run build && gh-pages -d build" in your deploy script, but you need to tell npm what to do when npm run build is being run. Configure build to whatever command needs to run to build your project.

Since you are using webpack, I assume it would be webpack --config webpack.conf.js. With gulp, gulp build, with TypeScript tsc -p tsproject.json, and so on. It depends on your project.

you can check out the full writeup here:
https://github.com/npm/npm/wiki/Troubleshooting#a-brief-note-on-the-built-in-windows-configuration

Body:
How can I fix this error, I'm running Windows 10

When i try to npm run build on the cmd i get this error

C:\Users\anai_> npm run build
npm ERR! missing script: build

Here is the log of the run

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'build' ]
2 info using npm@5.5.1
3 info using node@v9.1.0
4 verbose config Skipping project config: C:\Users\anai_/.npmrc. (matches userconfig)
5 verbose stack Error: missing script: build
5 verbose stack     at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:151:19)
5 verbose stack     at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:61:5
5 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:115:5
5 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:402:5
5 verbose stack     at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:357:45)
5 verbose stack     at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:400:3)
5 verbose stack     at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:160:5)
5 verbose stack     at ReadFileContext.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:332:20)
5 verbose stack     at ReadFileContext.callback (C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:78:16)
5 verbose stack     at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:437:13)
6 verbose cwd C:\Users\anai_
7 verbose Windows_NT 10.0.15063
8 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
9 verbose node v9.1.0
10 verbose npm  v5.5.1
11 error missing script: build
12 verbose exit [ 1, true ]

Although the error refers to a missing script build, i have placed a 'build' script in my package.json

{
  "name": "es6",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^3.8.1"
  }

}

and this is my webpack.config.js file

module.exports = {
  entry: ['./app/index.js'],
  output: {
    path: './build',
    filename: 'bundle.js'

  }
}

Why is this error happening, and how can the problem be fixed?


问:
android Admob and startApp
I have an app on playstore https://play.google.com/store/apps/details?id=com.advocosoftwares.colorbook. I have used startApp in first release version. Now for next version I am trying to add AdMob rewarded video ad in the same app. I am getting the issue while implementing it. I have followed the complete procedure from https://www.youtube.com/watch?v=_frcK8lYnX8 but onRewardedVideoAdFailedToLoad() method is called showing error code 3, I tried with both the sample id as well as created new Id for project but same error code as a result. I did the same procedure in other app where it works fine. Just having the issue in this app. Please help me out. </p>

答:
Error Code 3 means no fills from the mediated ad network.

Try again by enabling only test ads from startApp and see if that works.
You can also use this sample app to test you ad unit id.

Title: android Admob and startApp


问:
How can i parse json file in scala spark 2.0 and can I insert data into hive table?
I want to parse json file in spark 2.0(scala). Next i want to save the data..   in Hive table.
How can i parse json file by using scala?
json file example) metadata.json:

```<code>  {
        "syslog": {
            "month": "Sep",
            "day": "26",
            "time": "23:03:44",
            "host": "cdpcapital.onmicrosoft.com"
        },
        "prefix": {
            "cef_version": "CEF:0",
            "device_vendor": "Microsoft",
            "device_product": "SharePoint Online",
        },
        "extensions": {
            "eventId": "7808891",
            "msg": "ManagedSyncClientAllowed",
            "art": "1506467022378",
            "cat": "SharePoint",
            "act": "ManagedSyncClientAllowed",
            "rt": "1506466717000",
            "requestClientApplication": "Microsoft SkyDriveSync",
            "cs1": "0bdbe027-8f50-4ec3-843f-e27c41a63957",
            "cs1Label": "Organization ID",
            "cs2Label": "Modified Properties",
            "ahost": "cdpdiclog101.cgimss.com",
            "agentZoneURI": "/All Zones",
            "amac": "F0-1F-AF-DA-8F-1B",
            "av": "7.6.0.8009.0",
        }
    },
</code>```

Thanks

答:
You can use something like:

```<code>val jsonDf = sparkSession
      .read
      //.option("wholeFile", true) if its not a Single Line JSON
      .json("resources/json/metadata.json")

    jsonDf.printSchema()

jsonDf.registerTempTable("metadata")
</code>```

More details about this https://spark.apache.org/docs/latest/sql-programming-guide.html#hive-tables

Body:
I want to parse json file in spark 2.0(scala). Next i want to save the data..   in Hive table.
How can i parse json file by using scala?
json file example) metadata.json:

  {
        "syslog": {
            "month": "Sep",
            "day": "26",
            "time": "23:03:44",
            "host": "cdpcapital.onmicrosoft.com"
        },
        "prefix": {
            "cef_version": "CEF:0",
            "device_vendor": "Microsoft",
            "device_product": "SharePoint Online",
        },
        "extensions": {
            "eventId": "7808891",
            "msg": "ManagedSyncClientAllowed",
            "art": "1506467022378",
            "cat": "SharePoint",
            "act": "ManagedSyncClientAllowed",
            "rt": "1506466717000",
            "requestClientApplication": "Microsoft SkyDriveSync",
            "cs1": "0bdbe027-8f50-4ec3-843f-e27c41a63957",
            "cs1Label": "Organization ID",
            "cs2Label": "Modified Properties",
            "ahost": "cdpdiclog101.cgimss.com",
            "agentZoneURI": "/All Zones",
            "amac": "F0-1F-AF-DA-8F-1B",
            "av": "7.6.0.8009.0",
        }
    },

Thanks

Body:
You can use something like:

val jsonDf = sparkSession
      .read
      //.option("wholeFile", true) if its not a Single Line JSON
      .json("resources/json/metadata.json")

    jsonDf.printSchema()

jsonDf.registerTempTable("metadata")

More details about this https://spark.apache.org/docs/latest/sql-programming-guide.html#hive-tables


问:
Laravel 5 - Binding model from query string
I have the following URL:

/search?customer=my-customer-slug&q=foo

I wonder if there is a way to bind a Customer model into $request->customer, by searching from the Customer's slug.

Doing that when the URL is /search/{customer-slug} is very easy, but I don't know if I can do that with query strings.

答:
Yes you can do it with query strings with the below way:

```<code>if ($request->has('customer')) {
    $user->customer = $request->input('customer');
}
</code>```

Body:
Yes you can do it with query strings with the below way:

if ($request->has('customer')) {
    $user->customer = $request->input('customer');
}


问:
How use redux state with routes react-router?
I created my routes

```<code><Provider store={store}>
    <Router history={browserHistory}>
        <Route path="/" component={App}>
        <Route path="/redux" component={redux} />
    </Router>
</Provider>
</code>```

My problem is when I dispatch an action from redux component , the props changed in the /redux route but in the / always the initial state. Please who can help me ?

答:
Try to use react-router-redux (https://github.com/reactjs/react-router-redux) to synchronise redux store with react-router.

```<code>import { browserHistory } from 'react-router';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import { createStore, combineReducers } from 'redux';

// Add router reducer to your store on the `routing` key
const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)
// Create enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);

...

<Provider store={store}>
    <Router history={history}>
        <Route path="/" component={App}>
        <Route path="/redux" component={redux} />
    </Router>
</Provider>
</code>```

Body:
I created my routes

<Provider store={store}>
    <Router history={browserHistory}>
        <Route path="/" component={App}>
        <Route path="/redux" component={redux} />
    </Router>
</Provider>

My problem is when I dispatch an action from redux component , the props changed in the /redux route but in the / always the initial state. Please who can help me ?

Body:
Try to use react-router-redux (https://github.com/reactjs/react-router-redux) to synchronise redux store with react-router.

import { browserHistory } from 'react-router';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import { createStore, combineReducers } from 'redux';

// Add router reducer to your store on the `routing` key
const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)
// Create enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);

...

<Provider store={store}>
    <Router history={history}>
        <Route path="/" component={App}>
        <Route path="/redux" component={redux} />
    </Router>
</Provider>


问:
Angular 2 + Google Maps Places Autocomplete, append after Input [Dom manupulation]
I have used "Angular 2 + Google Maps Places Autocomplete" search.
It is basically an input type text like that:

```<code><input placeholder="search your location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #searching="">
</code>```

I want to know about the list, which appears after typing some text. I want to create such list for my customized input field.
If I create the input field in a different child component then I will not be able to apply direct ngModel features of form and validations on it.
So I want to append some HTML after input to show the list to select values like Google Autocomplete.
I have done this before with jQuery by appending a list after input. Please suggest me......

答:
If you want to insert new component or template after HTML component, you need to use the ViewContainerRef service.

Get ViewContainerRef with dependency injection:

```<code>import { Component,ViewContainerRef,ViewChild } from '@angular/core';
@Component({
    selector: 'vcr',
    template: `
    <ng-template #tpl>
    <h1>ViewContainerRef</h1>
    </ng-template>
    `,
})
export class VcrComponent {
    @ViewChild('tpl') tpl;
    constructor(private _vcr: ViewContainerRef) {
    }
    ngAfterViewInit() {
        this._vcr.createEmbeddedView(this.tpl);
    }
}
@Component({
    selector: 'my-app',
    template: `<vcr></vcr>`,
})
export class App {
}
</code>```

We are injecting the service in the component. In this case, the container will refer to your host element ( the vcr element ) and the template will be inserted as a sibling of the vcr element.

Body:
I have used "Angular 2 + Google Maps Places Autocomplete" search.
It is basically an input type text like that:

<input placeholder="search your location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #searching="">

I want to know about the list, which appears after typing some text. I want to create such list for my customized input field.
If I create the input field in a different child component then I will not be able to apply direct ngModel features of form and validations on it.
So I want to append some HTML after input to show the list to select values like Google Autocomplete.
I have done this before with jQuery by appending a list after input. Please suggest me......

Body:
If you want to insert new component or template after HTML component, you need to use the ViewContainerRef service.

Get ViewContainerRef with dependency injection:

import { Component,ViewContainerRef,ViewChild } from '@angular/core';
@Component({
    selector: 'vcr',
    template: `
    <ng-template #tpl>
    <h1>ViewContainerRef</h1>
    </ng-template>
    `,
})
export class VcrComponent {
    @ViewChild('tpl') tpl;
    constructor(private _vcr: ViewContainerRef) {
    }
    ngAfterViewInit() {
        this._vcr.createEmbeddedView(this.tpl);
    }
}
@Component({
    selector: 'my-app',
    template: `<vcr></vcr>`,
})
export class App {
}

We are injecting the service in the component. In this case, the container will refer to your host element ( the vcr element ) and the template will be inserted as a sibling of the vcr element.


问:
How to make Wordpress categories as subdomains without using a plugin?
I was using a plugin called wordpress subdomains 0.6.9 but it has lots of bugs and creating subdomains with this version is risky, I mean later there will be lots of broken links, so is there any way to do this manually, by editing the php code or database values ?
or anything else that will make this work ?
and thank you :D</p>

答: Just an idea: create a wildcard subdomain within your apache config (assuming you´re using apache webserver) and let it point to a php script which redirects acording to the given subdomain. </p>


问:
CASE STATEMENT INSIDE SELECT WITH CONDITION ORACLE
I need to select some records from a table according to my conditions. simply i need to do like this.

```<code>SELECT g.intds_intratechange
case when g.intds_intratechange='0.5% Up to 1%'
then g.intds_intratechange='ddd'
end
FROM glinfo.ref_tblintratefordesignation g
WHERE g.intds_designation =(select s.STR_OFF_TYPE from dpg.inf_responsible_maildetails s where s.STR_USER_CODE='10020336')
</code>```

in above table, there are 3 values. "0 t0 0.5" , "0.5 to 1" and "more than 1".
I need to filter records from my select accoring to above values. like if value is "0 to 0.5" then select first 10 records.
need a way to solve this. this code says "cannot founf from keyword where it expected"

答:
You can use BETWEEN to check those conditions.I am assuming your g.intds_intratechange column has a '%' at the end. If Not  TRIM(g.intds_intratechange,'%')  or TO_NUMBER might not be required.

```<code>SELECT
        g.intds_intratechange,
        case    when TO_NUMBER(TRIM(g.intds_intratechange,'%'))  BETWEEN 0 AND 0.5 THEN 'ddd'
                when TO_NUMBER(TRIM(g.intds_intratechange,'%'))  BETWEEN 0.5 AND 1 THEN 'whatever_u_need'
                when TO_NUMBER(TRIM(g.intds_intratechange,'%'))  > 1  THEN 'whatever_u_need'
        end name_of_new_col
FROM
        glinfo.ref_tblintratefordesignation g
WHERE   g.intds_designation IN
        (select
                s.STR_OFF_TYPE
        from
                dpg.inf_responsible_maildetails s
        where   s.STR_USER_CODE='10020336'
        );
</code>```

like if value is "0 to 0.5" then select first 10 records. need a way
  to solve this.

Not completely clear what you meant by this. Please add more details in the question.

Body:
I need to select some records from a table according to my conditions. simply i need to do like this.

SELECT g.intds_intratechange
case when g.intds_intratechange='0.5% Up to 1%'
then g.intds_intratechange='ddd'
end
FROM glinfo.ref_tblintratefordesignation g
WHERE g.intds_designation =(select s.STR_OFF_TYPE from dpg.inf_responsible_maildetails s where s.STR_USER_CODE='10020336')

in above table, there are 3 values. "0 t0 0.5" , "0.5 to 1" and "more than 1".
I need to filter records from my select accoring to above values. like if value is "0 to 0.5" then select first 10 records.
need a way to solve this. this code says "cannot founf from keyword where it expected"

Body:
You can use BETWEEN to check those conditions.I am assuming your g.intds_intratechange column has a '%' at the end. If Not  TRIM(g.intds_intratechange,'%')  or TO_NUMBER might not be required.

SELECT
        g.intds_intratechange,
        case    when TO_NUMBER(TRIM(g.intds_intratechange,'%'))  BETWEEN 0 AND 0.5 THEN 'ddd'
                when TO_NUMBER(TRIM(g.intds_intratechange,'%'))  BETWEEN 0.5 AND 1 THEN 'whatever_u_need'
                when TO_NUMBER(TRIM(g.intds_intratechange,'%'))  > 1  THEN 'whatever_u_need'
        end name_of_new_col
FROM
        glinfo.ref_tblintratefordesignation g
WHERE   g.intds_designation IN
        (select
                s.STR_OFF_TYPE
        from
                dpg.inf_responsible_maildetails s
        where   s.STR_USER_CODE='10020336'
        );

like if value is "0 to 0.5" then select first 10 records. need a way
  to solve this.

Not completely clear what you meant by this. Please add more details in the question.


问:
Python Flood Fill - How to optimize
```<code>def getRegionSize(cell, world):
    region = []
    frontier = [cell]
    val = world[cell[0]][cell[1]]
    while(len(frontier) > 0):
        item = frontier.pop()
        region.append(item)
        x = item[0]
        y = item[1]
        for i in [-1,1]:
            for j in [-1,1]:
                if (x+i,y+j) not in frontier and (x+i,y+j) not in region:
                    if not (x + i > width - 1 or x + i < 0 or y + j > height - 1 or y + i < 0) and world[x+i][y+j] == val:
                        frontier.append((x+i,y+j))
    return len(region)
</code>```

I want my function to determine the size of an area connected to a given cell. The function takes world (2D binary matrix) and cell ((x,y) coordinates in the world) as arguments, and returns the size of the area connected to cell.

This function works like flood fill, but instead of recoloring an area, I am only interested in the size of the area being recolored. The function works fine, but it is slow. It takes a few seconds to return for areas of size greater than ~4000. Is there something I'm doing terribly wrong, or is it supposed to be slow for large areas?

EDIT: Edited for clarity.

答:
In: if (x+i,y+j) not in frontier and (x+i,y+j) not in region:, you're testing if cell is in frontier or region, both of which are lists, so searching them takes O(n).

1) You don't need to check if cell is in frontier. As long as you ignore cells already in region, you can add a cell to the frontier as many times as you want.

2) Use a more efficient data structure for region, i.e. a set.

Title: Python Flood Fill - How to optimize

Body:
def getRegionSize(cell, world):
    region = []
    frontier = [cell]
    val = world[cell[0]][cell[1]]
    while(len(frontier) > 0):
        item = frontier.pop()
        region.append(item)
        x = item[0]
        y = item[1]
        for i in [-1,1]:
            for j in [-1,1]:
                if (x+i,y+j) not in frontier and (x+i,y+j) not in region:
                    if not (x + i > width - 1 or x + i < 0 or y + j > height - 1 or y + i < 0) and world[x+i][y+j] == val:
                        frontier.append((x+i,y+j))
    return len(region)

I want my function to determine the size of an area connected to a given cell. The function takes world (2D binary matrix) and cell ((x,y) coordinates in the world) as arguments, and returns the size of the area connected to cell.

This function works like flood fill, but instead of recoloring an area, I am only interested in the size of the area being recolored. The function works fine, but it is slow. It takes a few seconds to return for areas of size greater than ~4000. Is there something I'm doing terribly wrong, or is it supposed to be slow for large areas?

EDIT: Edited for clarity.