问:
Pausing and resuming an observable stream, please suggest better options
I have a requirement to listen to a stream of items from an observable. When certain conditions arise an asynchronous task will be performed on the item and the component will be 'busy' until this completes. I would like to pause handling items in the subscription until this task has completed (as the processing of the following items is dependent on the result) and then resume from the next item in the sequence without any loss.

the next part is probably best read whilst looking at the Plunk here

To achieve this I have used a buffer with a swtichMap. I thought these would do the job on their own but switchMap destroys and recreates the subscription the sequence gets reset every time.

export class AppComponent implements OnInit {
    source$: Observable<any>;
    clearBuffer$ = new Subject();
    busy$ = new Subject();

    private itemSubscription: Subscription;
    private stayAliveSubscription: Subscription;

    items: any[] = [];

    constructor() { }

    ngOnInit() {
      this.source$ = Observable.range(1, 500).zip(
        Observable.interval(500),
        function (x, y) { return x; }
      ).share();

      this.busy$
        .subscribe(result => {
          if (!result) {
            this.clearBuffer$.next();
          }
        }, error => {
          console.log(error);
        });
    }

    start() {
      if (!this.itemSubscription) {
        this.itemSubscription =
          this.busy$.switchMap(busy => {
            if (busy) {
              return this.source$.buffer(this.clearBuffer$);
            } else {
              return this.source$;
            }
          })
            .subscribe(items => {
              if (Array.isArray(items)) {
                this.items.push('buffered: ' + items.join());
              } else {
                this.items.push('live feed: ' + items);
              }
            }, error => {
              this.items.push(error);
            });

        this.stayAliveSubscription = this.source$
          .subscribe(result => {
            console.log(result);
          }, error => {
            console.log(error);
          });

        this.busy$.next(false);
      }
   }
...
}
```

<p>To fix this the <strong>source$</strong> observable is now shared and a separate subscription is started (<strong>stayAliveSubscription</strong>) so a single subscription is used throughout. This seems messy to me and I wanted to ask if anyone can show me better/alternative approaches to the problem.</p>

<p>I put the working sample in a Plunk here click start to start the subscription and then set/unset the busy toggle to buffer and continue.</p>

<p><strong>edit: working code with concatMap</strong></p>

<p>I changed the Plunk to use concatMap. I've pasted the code below as well. The key is that the busy observable returned in concatMap must complete you can't just return the busy$ observable multiple times and call next on it when the busy status changes.</p>

<pre class="lang-js prettyprint-override"><code>    source$: Observable<any>;
    busy$ = new Subject();
    busy: boolean;

    private itemSubscription: Subscription;
    private stayAliveSubscription: Subscription;

    items: any[] = [];

    constructor() { }

    ngOnInit() {
      this.source$ = Observable.range(1, 500).zip(
        Observable.interval(500),
        function (x, y) { return x; }
      );

      this.busy$
        .subscribe(busy => {
          this.busy = <any>busy;
        });
    }

    start() {
      if (!this.itemSubscription) {
        this.itemSubscription = this.source$.concatMap(item => {
          const busySubject = new Subject();
          this.busy$
            .subscribe(result => {
              busySubject.next(item);
              busySubject.complete();
            });

          if (this.busy) {
            return busySubject;
          } else {
            return Observable.of(item);
          }

        })
          .subscribe(item => {
            this.items.push(item);
          }, error => {
            this.items.push(error);
          });
      }

      this.setBusy(false);
    }
</code>```

答:
I don't fully understand what you are trying to do, but if it is just a matter of preserving the order of the emitted values while the "async task" can take a long (random) time, I guess you could use the concatMap operator.

Theory

concatMap

Projects each source value to an Observable which is merged in the output Observable, in a serialized fashion waiting for each one to complete before merging the next.

Practice

In this example, the srcObservable emits a value every 100ms and each value is mapped to a new observable that emits a value between 0 and 2000ms (the async task). You can see the order is safe.

let src = Rx.Observable.timer(0,100);
src.concatMap(i=>{
  return Rx.Observable.timer(Math.random()*2000).mapTo(i); // this is the async task
}).subscribe(data=>console.log(data));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/rxjs@5.4.0/bundles/Rx.min.js"></script></code>```

Making a hot Observable

You should also not use these subscriptions to make your observable emit data. Actually you should transform your cold observable to a hot one using .publish()  and .connect() instead of share()and subscribe() :

```<code>this.source$ = Observable.range(1, 500).zip(
        Observable.interval(500),
        function (x, y) { return x; }
      ).publish();
// blah blah blah some code
this.source$.connect();
</code>```

Body:
I have a requirement to listen to a stream of items from an observable. When certain conditions arise an asynchronous task will be performed on the item and the component will be 'busy' until this completes. I would like to pause handling items in the subscription until this task has completed (as the processing of the following items is dependent on the result) and then resume from the next item in the sequence without any loss.

the next part is probably best read whilst looking at the Plunk here

To achieve this I have used a buffer with a swtichMap. I thought these would do the job on their own but switchMap destroys and recreates the subscription the sequence gets reset every time.

export class AppComponent implements OnInit {
    source$: Observable<any>;
    clearBuffer$ = new Subject();
    busy$ = new Subject();

    private itemSubscription: Subscription;
    private stayAliveSubscription: Subscription;

    items: any[] = [];

    constructor() { }

    ngOnInit() {
      this.source$ = Observable.range(1, 500).zip(
        Observable.interval(500),
        function (x, y) { return x; }
      ).share();

      this.busy$
        .subscribe(result => {
          if (!result) {
            this.clearBuffer$.next();
          }
        }, error => {
          console.log(error);
        });
    }

    start() {
      if (!this.itemSubscription) {
        this.itemSubscription =
          this.busy$.switchMap(busy => {
            if (busy) {
              return this.source$.buffer(this.clearBuffer$);
            } else {
              return this.source$;
            }
          })
            .subscribe(items => {
              if (Array.isArray(items)) {
                this.items.push('buffered: ' + items.join());
              } else {
                this.items.push('live feed: ' + items);
              }
            }, error => {
              this.items.push(error);
            });

        this.stayAliveSubscription = this.source$
          .subscribe(result => {
            console.log(result);
          }, error => {
            console.log(error);
          });

        this.busy$.next(false);
      }
   }
...
}

To fix this the source$ observable is now shared and a separate subscription is started (stayAliveSubscription) so a single subscription is used throughout. This seems messy to me and I wanted to ask if anyone can show me better/alternative approaches to the problem.

I put the working sample in a Plunk here click start to start the subscription and then set/unset the busy toggle to buffer and continue.

edit: working code with concatMap

I changed the Plunk to use concatMap. I've pasted the code below as well. The key is that the busy observable returned in concatMap must complete you can't just return the busy$ observable multiple times and call next on it when the busy status changes.

    source$: Observable<any>;
    busy$ = new Subject();
    busy: boolean;

    private itemSubscription: Subscription;
    private stayAliveSubscription: Subscription;

    items: any[] = [];

    constructor() { }

    ngOnInit() {
      this.source$ = Observable.range(1, 500).zip(
        Observable.interval(500),
        function (x, y) { return x; }
      );

      this.busy$
        .subscribe(busy => {
          this.busy = <any>busy;
        });
    }

    start() {
      if (!this.itemSubscription) {
        this.itemSubscription = this.source$.concatMap(item => {
          const busySubject = new Subject();
          this.busy$
            .subscribe(result => {
              busySubject.next(item);
              busySubject.complete();
            });

          if (this.busy) {
            return busySubject;
          } else {
            return Observable.of(item);
          }

        })
          .subscribe(item => {
            this.items.push(item);
          }, error => {
            this.items.push(error);
          });
      }

      this.setBusy(false);
    }

Body:
I don't fully understand what you are trying to do, but if it is just a matter of preserving the order of the emitted values while the "async task" can take a long (random) time, I guess you could use the concatMap operator.

Theory

concatMap

Projects each source value to an Observable which is merged in the output Observable, in a serialized fashion waiting for each one to complete before merging the next.

Practice

In this example, the srcObservable emits a value every 100ms and each value is mapped to a new observable that emits a value between 0 and 2000ms (the async task). You can see the order is safe.

let src = Rx.Observable.timer(0,100);
src.concatMap(i=>{
  return Rx.Observable.timer(Math.random()*2000).mapTo(i); // this is the async task
}).subscribe(data=>console.log(data));

<script src="https://unpkg.com/rxjs@5.4.0/bundles/Rx.min.js"></script>

Making a hot Observable

You should also not use these subscriptions to make your observable emit data. Actually you should transform your cold observable to a hot one using .publish()  and .connect() instead of share()and subscribe() :

this.source$ = Observable.range(1, 500).zip(
        Observable.interval(500),
        function (x, y) { return x; }
      ).publish();
// blah blah blah some code
this.source$.connect();


来源: stackexchange

问:
PHP save to file script giving errors after upgrade to PHP 7.0
I have rather simple script that is supposed to add new line of string to a file.

```<code>if (isset($_POST["score"]))
{
$myFile = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);

$File = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$Handle = fopen($File, 'w');
$Data = $_POST["score"]."\n".$theData;
fwrite($Handle, $Data);
fclose($Handle);
}
</code>```

After upgrading to PHP 7.0 I get errors:

```<code>fread() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 7
fclose() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 8
</code>```

Could anyone explain why this error shows up and how it can be fixed? What is it with PHP 7.0 that caused it suddenly to stop working?

答:
When fopen() fails it returns false. false is not a resource, thus the warning.

You'd better test $fh before injecting it as a resource-like argument:

```<code>if($fh = fopen($myFile, 'r')) {

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have rather simple script that is supposed to add new line of string to a file.

if (isset($_POST["score"]))
{
$myFile = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);

$File = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$Handle = fopen($File, 'w');
$Data = $_POST["score"]."\n".$theData;
fwrite($Handle, $Data);
fclose($Handle);
}

After upgrading to PHP 7.0 I get errors:

fread() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 7
fclose() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 8

Could anyone explain why this error shows up and how it can be fixed? What is it with PHP 7.0 that caused it suddenly to stop working?

Body:
When fopen() fails it returns false. false is not a resource, thus the warning.

You'd better test $fh before injecting it as a resource-like argument:

if($fh = fopen($myFile, 'r')) {

}


问:
Files being uploaded get the first letter cut off
I'm migrating a website from a server with WS2003, IIS6, PHP 5.2 over to a server with WS2008, IIS7 and PHP 5.3

I have a html form that uploads files to the site.

```<code><?php
if(isset($_POST["Upload"])){
    echo "```";
    print_r($_POST);
    print_r($_FILES);
    echo "```";
}
?>

<form action="tester.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="Upload" value="1" />
    <input type="hidden" name="MAX_FILE_SIZE" value="4500000" />
    <input type="file" name="artImage" id="artImage" />
    <input type="submit" />
</form>
</code>```

Works great on the old server, but on the new server, it chops off the first letter for no reason I can see. I don't know if it's an IIS setting, or a PHP setting.

Output:

```<code>Array
(
    [Upload] => 1
    [MAX_FILE_SIZE] => 4500000
)
Array
(
    [artImage] => Array
        (
            [name] => easons_Change_(HD_Ready).jpg
            [type] => image/pjpeg
            [tmp_name] => C:\Windows\Temp\php99.tmp
            [error] => 0
            [size] => 498879
        )

)
</code>```

Output from the old server, same code, same file:

```<code>Array
(
    [Upload] => 1
    [MAX_FILE_SIZE] => 4500000
)
Array
(
    [artImage] => Array
        (
            [name] => Seasons_Change_(HD_Ready).jpg
            [type] => image/pjpeg
            [tmp_name] => C:\WINDOWS\Temp\php6835.tmp
            [error] => 0
            [size] => 498879
        )

)
</code>```

答:
I had same issue and search a lot but it's a bug and I don't know why! But I have solution and it works as well.
Just prefix a name before file name. Example :</p>

```<code>'fileNamePrefix_' . $_FILES['file_name_attribute']['name']
</code>```

Body:
I'm migrating a website from a server with WS2003, IIS6, PHP 5.2 over to a server with WS2008, IIS7 and PHP 5.3

I have a html form that uploads files to the site.

<?php
if(isset($_POST["Upload"])){
    echo "
";
    print_r($_POST);
    print_r($_FILES);
    echo "
";
}
?>

<form action="tester.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="Upload" value="1" />
    <input type="hidden" name="MAX_FILE_SIZE" value="4500000" />
    <input type="file" name="artImage" id="artImage" />
    <input type="submit" />
</form>

Works great on the old server, but on the new server, it chops off the first letter for no reason I can see. I don't know if it's an IIS setting, or a PHP setting.

Output:

Array
(
    [Upload] => 1
    [MAX_FILE_SIZE] => 4500000
)
Array
(
    [artImage] => Array
        (
            [name] => easons_Change_(HD_Ready).jpg
            [type] => image/pjpeg
            [tmp_name] => C:\Windows\Temp\php99.tmp
            [error] => 0
            [size] => 498879
        )

)

Output from the old server, same code, same file:

Array
(
    [Upload] => 1
    [MAX_FILE_SIZE] => 4500000
)
Array
(
    [artImage] => Array
        (
            [name] => Seasons_Change_(HD_Ready).jpg
            [type] => image/pjpeg
            [tmp_name] => C:\WINDOWS\Temp\php6835.tmp
            [error] => 0
            [size] => 498879
        )

)

Body:
I had same issue and search a lot but it's a bug and I don't know why! But I have solution and it works as well.
Just prefix a name before file name. Example :

'fileNamePrefix_' . $_FILES['file_name_attribute']['name']


问:
adhoc virtual fields fat-free-framework
Hi i'm using fat free framework  ,how can i get the value of the virtual filds below '#adhoc' :

"subset" =>
 array:2 [

```<code>0 => Mapper {#36 ▶}
1 => Mapper {#39 ▼
  #db: SQL {#8 ▶}
  #engine: "mysql"
  #source: "groupe_client"
  #table: "`groupe_client`"
  #_id: null
  #fields: array:10 [▼
    "id_groupe_client" => array:9 [▶]
    "nom" => array:8 [▶]
    "reference" => array:8 [▶]
    "nbr_occupant" => array:8 [▶]
    "date_debut" => array:8 [▶]
    "date_fin" => array:8 [▶]
    "id_administrateur" => array:8 [▶]
    "date_heure_last_update" => array:8 [▶]
    "etat" => array:8 [▶]
    "remarque" => array:8 [▶]
  ]
  #adhoc: array:2 [▼
    "administrateur" => array:2 [▶]
    "client" => array:2 [▶]
  ]
</code>```

EDIT  sorry , but i need to access to the fileds in my View ?

答:
Are you sure you are using virtual fields?

virtual fields are setted like:

$model->virtualfields = "select name from category";

$model->load();

With this way you can use the field in the Views and Controller in the same way

Title: adhoc virtual fields fat-free-framework

Body:
Hi i'm using fat free framework  ,how can i get the value of the virtual filds below '#adhoc' :

"subset" =>
 array:2 [

0 => Mapper {#36 ▶}
1 => Mapper {#39 ▼
  #db: SQL {#8 ▶}
  #engine: "mysql"
  #source: "groupe_client"
  #table: "`groupe_client`"
  #_id: null
  #fields: array:10 [▼
    "id_groupe_client" => array:9 [▶]
    "nom" => array:8 [▶]
    "reference" => array:8 [▶]
    "nbr_occupant" => array:8 [▶]
    "date_debut" => array:8 [▶]
    "date_fin" => array:8 [▶]
    "id_administrateur" => array:8 [▶]
    "date_heure_last_update" => array:8 [▶]
    "etat" => array:8 [▶]
    "remarque" => array:8 [▶]
  ]
  #adhoc: array:2 [▼
    "administrateur" => array:2 [▶]
    "client" => array:2 [▶]
  ]

EDIT  sorry , but i need to access to the fileds in my View ?


问:
Reduced VS 2017 IDE interactivity in MVC 5 Razor views in 2015 project
I just installed VS 2017 and am opening an MVC 5 project created in VS 2015.  The application runs fine, but I am experiencing reduced interactivity between my MVC Razor view code and the 2017 IDE.

Here's is the context menu when I right-click on an HTML helper method in VS 2015:

However, I only see this in 2017:

Also notice the lack of syntax color-coding in the 2017 verison.  It's like it's not recognizing Razor syntax at all.

I did not do any special solution/project upgrades.  I just opened the solution in 2017 and expected it to prompt me to upgrade any files that needed upgrading.

答:
So it turns out that the component installation for VS 2017 is modular in that you have to install exactly what you need.  This is different from 2015 (at least as far as I recall) where all components are included with the installation.

I have a tendency not to read entire pages and just focus on what seems like the "most comprehensive" option.  In my case, I selected only Universal Windows Platform development (doesn't that just sound like everything you'd need?).  If I bothered to look at all the components, I would have seen ASP.NET and web development.

So, after modifying my installation, I am now seeing all the Razor syntax in my views.


问:
Python regex capture issue
I have a regex expression that captures the text from a text file. The regex can ve viewed at the following URL:
https://regex101.com/r/wwEjTF/1

In my python code I would like extract the text that is matched by the regex only from all the other text in the text file.
I have following python code for matching th regex and storing it in a variable.

```<code>match = re.findall(r'test\s.+\n\sdescription\s\"(.+)\"', text, re.S)
</code>```

I am expecting all the matches to be in the match variable and returned a list.
But when I do print (match) I get empty list. I do not understand why it is coming up an empty list. How do i capture the matched part of the regex into the variable.
Thanks for your help.
Just in case if there is an issue with the above url, is the regex and the sample text string:

```<code>test\s.+\n\sdescription\s\"(.+)\"
</code>```

```<code>some random text
test 111.333.555.666
  description "text10"
some random text
some random text
test 22.44.55.66
  description "text12"
some random text
some random text
test 77.77.88.99
  description "text13"
some random text
some random text
test 14.22.55.99
  description "text16"
some random text
some random text
test 13.33.55.66
  description "text17"
some random text`
</code>```

答:
Example in the regex101 uses tab as separator for description, so single \s works for it. Replace it with repetition:

```<code>match = re.findall(r'test\s.+\n\s+description\s\"(.+)\"', text, re.S)
</code>```

Title: Python regex capture issue

Body:
I have a regex expression that captures the text from a text file. The regex can ve viewed at the following URL:
https://regex101.com/r/wwEjTF/1

In my python code I would like extract the text that is matched by the regex only from all the other text in the text file.
I have following python code for matching th regex and storing it in a variable.

match = re.findall(r'test\s.+\n\sdescription\s\"(.+)\"', text, re.S)

I am expecting all the matches to be in the match variable and returned a list.
But when I do print (match) I get empty list. I do not understand why it is coming up an empty list. How do i capture the matched part of the regex into the variable.
Thanks for your help.
Just in case if there is an issue with the above url, is the regex and the sample text string:

test\s.+\n\sdescription\s\"(.+)\"

some random text
test 111.333.555.666
  description "text10"
some random text
some random text
test 22.44.55.66
  description "text12"
some random text
some random text
test 77.77.88.99
  description "text13"
some random text
some random text
test 14.22.55.99
  description "text16"
some random text
some random text
test 13.33.55.66
  description "text17"
some random text`

Body:
Example in the regex101 uses tab as separator for description, so single \s works for it. Replace it with repetition:

match = re.findall(r'test\s.+\n\s+description\s\"(.+)\"', text, re.S)


问:
Android Enable Zoom and Pinch Controls in Webview
I'm trying to get zoom controls to display along with pinch to zoom to work in an android webview. Largely referencing this SO.

Right now I have these being set in the onCreate method:

```<code>this._webView.getSettings().setBuiltInZoomControls(true);
this._webView.getSettings().setDisplayZoomControls(true);
this._webView.getSettings().setSupportZoom(true);
</code>```

But nothing appears and the Zoom controls don't appear. I've also tried without setSupportZoom but that didn't seem to help.

As far as I can tell my webview is not wrapped in a scroll view but it is a subclass of Webview:

```<code>class MyWebView extends WebView {
        public MyWebView(Context context) {
            super(context);
        }

        @Override
        public void goBack() {

            super.goBack();
        }

    }
</code>```

So I end up creating it like this:

```<code>if (this._webView == null) {
            this._webView = new MyWebView(this);
            this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            this._webView.getSettings().setJavaScriptEnabled(true);
            this._webView.setWebChromeClient(new WebChromeClient());
            this._webView.setWebViewClient(new WebViewClient());
            this._webView.getSettings().setBuiltInZoomControls(true);
            this._webView.getSettings().setDisplayZoomControls(true);
            this._webView.getSettings().setSupportZoom(true);
            this._webView.loadUrl(this._baseUrl);
        }
</code>```

Any ideas where I'm going wrong?

Thanks!

EDIT:

In onCreate I do this:

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(1);
    getWindow().setFlags(1024, 1024);

    RelativeLayout my_layout = generateLayout();

    initUI();

    setContentView(my_layout);
}
</code>```

In generateLayout we create the initial layout and create the holder for the webView:

```<code>private RelativeLayout generateLayout() {
    RelativeLayout my_layout = new RelativeLayout(this);
    my_layout.setId(this.generateViewId());
    my_layout.setLayoutParams(new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT));

    ... more layout stuff

    FrameLayout webViewPlaceholder = new FrameLayout(this);
    this._webViewPlaceholder = webViewPlaceholder;
    webViewPlaceholder.setId(this.generateViewId());
    webViewPlaceholder.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    RelativeLayout.LayoutParams webViewPlaceholderLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    webViewPlaceholderLayoutParams.addRule(RelativeLayout.BELOW, rlHeader.getId());
    webViewPlaceholder.setLayoutParams(webViewPlaceholderLayoutParams);

    my_layout.addView(webViewPlaceholder);
 }
</code>```

Then in initUI we create the webView itself:

```<code>@SuppressLint({"SetJavaScriptEnabled"})
protected void initUI() {
    if (this._webView == null) {
        this._webView = new MyWebView(this);
        this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this._webView.getSettings().setJavaScriptEnabled(true);
        this._webView.setWebChromeClient(new WebChromeClient());
        this._webView.setWebViewClient(new WebViewClient());

        this._webView.getSettings().setSupportZoom(true);
        this._webView.getSettings().setBuiltInZoomControls(true);
        this._webView.getSettings().setDisplayZoomControls(true);

        this._webView.loadUrl(this._baseUrl);

    } else {
        if (this._webView.getProgress() >= 100) {
            this._progressIndicatorView.setVisibility(View.INVISIBLE);
        }
        setNavigationButtonsState();
    }
    this._webViewPlaceholder.addView(this._webView);
}
</code>```

答: call your initUI after set content view. You need to get a reference to your layout before you can do anything with it. you are creating your layout in generateLayout(), you need to set it before you work on your web view settings.</p>

Body:
I'm trying to get zoom controls to display along with pinch to zoom to work in an android webview. Largely referencing this SO.

Right now I have these being set in the onCreate method:

this._webView.getSettings().setBuiltInZoomControls(true);
this._webView.getSettings().setDisplayZoomControls(true);
this._webView.getSettings().setSupportZoom(true);

But nothing appears and the Zoom controls don't appear. I've also tried without setSupportZoom but that didn't seem to help.

As far as I can tell my webview is not wrapped in a scroll view but it is a subclass of Webview:

class MyWebView extends WebView {
        public MyWebView(Context context) {
            super(context);
        }

        @Override
        public void goBack() {

            super.goBack();
        }

    }

So I end up creating it like this:

if (this._webView == null) {
            this._webView = new MyWebView(this);
            this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            this._webView.getSettings().setJavaScriptEnabled(true);
            this._webView.setWebChromeClient(new WebChromeClient());
            this._webView.setWebViewClient(new WebViewClient());
            this._webView.getSettings().setBuiltInZoomControls(true);
            this._webView.getSettings().setDisplayZoomControls(true);
            this._webView.getSettings().setSupportZoom(true);
            this._webView.loadUrl(this._baseUrl);
        }

Any ideas where I'm going wrong?

Thanks!

EDIT:

In onCreate I do this:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(1);
    getWindow().setFlags(1024, 1024);

    RelativeLayout my_layout = generateLayout();

    initUI();

    setContentView(my_layout);
}

In generateLayout we create the initial layout and create the holder for the webView:

private RelativeLayout generateLayout() {
    RelativeLayout my_layout = new RelativeLayout(this);
    my_layout.setId(this.generateViewId());
    my_layout.setLayoutParams(new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT));

    ... more layout stuff

    FrameLayout webViewPlaceholder = new FrameLayout(this);
    this._webViewPlaceholder = webViewPlaceholder;
    webViewPlaceholder.setId(this.generateViewId());
    webViewPlaceholder.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    RelativeLayout.LayoutParams webViewPlaceholderLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    webViewPlaceholderLayoutParams.addRule(RelativeLayout.BELOW, rlHeader.getId());
    webViewPlaceholder.setLayoutParams(webViewPlaceholderLayoutParams);

    my_layout.addView(webViewPlaceholder);
 }

Then in initUI we create the webView itself:

@SuppressLint({"SetJavaScriptEnabled"})
protected void initUI() {
    if (this._webView == null) {
        this._webView = new MyWebView(this);
        this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this._webView.getSettings().setJavaScriptEnabled(true);
        this._webView.setWebChromeClient(new WebChromeClient());
        this._webView.setWebViewClient(new WebViewClient());

        this._webView.getSettings().setSupportZoom(true);
        this._webView.getSettings().setBuiltInZoomControls(true);
        this._webView.getSettings().setDisplayZoomControls(true);

        this._webView.loadUrl(this._baseUrl);

    } else {
        if (this._webView.getProgress() >= 100) {
            this._progressIndicatorView.setVisibility(View.INVISIBLE);
        }
        setNavigationButtonsState();
    }
    this._webViewPlaceholder.addView(this._webView);
}


问:
Input data on Table OnCreate
Please what the best way to solve this problem
I have a form to insert data on model_request.
(I have other model: model_approver with Type Of Expense, Approver)

I need that when onCreate event from model_request one other field  receive information from model_approver.

Example:
An user will be create a request and choose a type of expense (Field from model_approver) via dropdown after this when submit , the field ResponsabileApprover [from model_request]   receive Approver [from model_approver].

Dropdowns was working fine
Thanks for clarifications

答:
Call server script with all necessary date from client (https://developers.google.com/appmaker/scripting/client#call_a_server_script), and create item on the server side,

onCreate event is useful to set some default values (date_created) or validate input data to prohibit creating a new record in a model

Title: Input data on Table OnCreate


问:
how to use proguard in android 2.3
one of the features in android 2.3 is integrated proguard obfuscation when doing release builds. but how do i enable this obfuscation when creating my apk?

thanks!

答: I just used it with maven. If you are using maven as well, I would recommend you reading this blog post.</p>

ContentLicense: CC BY-SA 2.5

Title: how to use proguard in android 2.3


问:
Swift UIView background color opacity
I have a UIView with a UILabel in it. I want the UIView to have white background color, but with an opacity of 50%. The problem whith setting view.alpha = 0.5 is that the label will have an opacity of 50% as well, so I figured out that it maybe would be possible to have a UIView with white background color and opacity (white_view), and then have another UIView with the label (label_view). Then add the "white_view" to "label_view" by doing this: label_view.addSubview(white_view). This apparently doesn't work. I'd like to do like: label_view.backgroundView(white_view) but you can't set a background view on a UIView like you can do in a UICollectionView for instance.

Does anyone have any clue of how to solve this?

EDIT
Because several answers are approx the same I'll type it here.
Now I've tried even these:

```<code>label_view1.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
label_view1.addSubview(firstPlacelbl)
endGameView.addSubview(label_view1)
</code>```

and

```<code>label_view1.backgroundColor = UIColor(white: 1, alpha: 0.5)
label_view1.addSubview(firstPlacelbl)
endGameView.addSubview(label_view1)
</code>```

And still the label is also affected by the alpha, and it gets an opacity of 50%. I don't get it what I do wrong because I only set the colors alpha to 0.5 and not the labels. Any ideas?

答:
For Swift 4.x and above

yourView.backgroundColor = UIColor.black.withAlphaComponent(0.5)

Title: Swift UIView background color opacity

Body:
I have a UIView with a UILabel in it. I want the UIView to have white background color, but with an opacity of 50%. The problem whith setting view.alpha = 0.5 is that the label will have an opacity of 50% as well, so I figured out that it maybe would be possible to have a UIView with white background color and opacity (white_view), and then have another UIView with the label (label_view). Then add the "white_view" to "label_view" by doing this: label_view.addSubview(white_view). This apparently doesn't work. I'd like to do like: label_view.backgroundView(white_view) but you can't set a background view on a UIView like you can do in a UICollectionView for instance.

Does anyone have any clue of how to solve this?

EDIT
Because several answers are approx the same I'll type it here.
Now I've tried even these:

label_view1.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
label_view1.addSubview(firstPlacelbl)
endGameView.addSubview(label_view1)

and

label_view1.backgroundColor = UIColor(white: 1, alpha: 0.5)
label_view1.addSubview(firstPlacelbl)
endGameView.addSubview(label_view1)

And still the label is also affected by the alpha, and it gets an opacity of 50%. I don't get it what I do wrong because I only set the colors alpha to 0.5 and not the labels. Any ideas?

ContentLicense: CC BY-SA 4.0


问:
Swift - Parse - Friend list - Possibility to create groups of friends
Could someone give me a link (github/gitlab) of a swift projet which show the possibility of managing Users on Parse.

For example , I would like for a user (who have 15 friends):

to create a group with 5 friends for example (the user could add a name for this group)

to delete if necessary the group

to send a message(textfield) to a group

to send a message (textfield) to a user

For the UI, I would like if it exists, to manager user like the Springboard (having the picture of user in round), and when you longpress on it, you have a cross to delete /and 'block sign' to block user.
And the user could drag/drop other user on his friend list to create a group (like on the Springboard when you create a group of app)

Thanks for helping me !

Have a nice day!

答:
I've not come across such framework for parse/swift. I think you need to build it yourself.

This might help you in the direction:

Friend/de-friend people: https://stackoverflow.com/a/32557977/3314336 &
Parse Swift: User relations with a "friends request"

Send messages framework: https://github.com/slackhq/SlackTextViewController


问:
`re.search` is not giving entire match (Python)
Below is one line of my file "test.txt":

```<code>"","links":{"self":"https://1.1.1.10/abc/abc_config/v1/domain/1234-e0f2-11e3-8169-dfgd1234/devices/devicerecords/71a54444-442e-11e7-b2e0-ef8622226aec"},"name":"10.105.206.87"},{"id":"118e8d36-49ba-11e7-8c4e-fb1fe31bd90c","type":"
</code>```

I want to fetch ("name":"10.105.206.87"},{"id":"118e8d36-49ba-11e7-8c4e-fb1fe31bd90c","type") portion from the line below is my code-

```<code> f=open("test.txt","r")
 str1=f.read()
 str2=str1.split("Device")
 for string in str2:
    if "name" in string:
       reg='\"name.+,\"typ'
       match=re.search(reg,string)
       print (match)
</code>```

it  matches half of the expected output:

```<code><_sre.SRE_Match object; span=(164, 237), match='"name":"10.105.206.87"},{"id":"118e8d36-49ba-11e7>
</code>```

I want to print entire string:

```<code> "name":"10.105.206.87"},{"id":"118e8d36-49ba-11e7-8c4e-fb1fe31bd90c","type"
</code>```

Let me know, if I am passing the wrong regex.

答:
The pattern is correct. You are trying to print the result of re.search. Try to pull only the matched text like below.

```<code> reg='\"name.+,\"type\"'
 match=re.search(reg,string)
 print (match.group())
</code>```

BTW, I have modified the pattern a little to match till "type"

Body:
Below is one line of my file "test.txt":

"","links":{"self":"https://1.1.1.10/abc/abc_config/v1/domain/1234-e0f2-11e3-8169-dfgd1234/devices/devicerecords/71a54444-442e-11e7-b2e0-ef8622226aec"},"name":"10.105.206.87"},{"id":"118e8d36-49ba-11e7-8c4e-fb1fe31bd90c","type":"

I want to fetch ("name":"10.105.206.87"},{"id":"118e8d36-49ba-11e7-8c4e-fb1fe31bd90c","type") portion from the line below is my code-

 f=open("test.txt","r")
 str1=f.read()
 str2=str1.split("Device")
 for string in str2:
    if "name" in string:
       reg='\"name.+,\"typ'
       match=re.search(reg,string)
       print (match)

it  matches half of the expected output:

<_sre.SRE_Match object; span=(164, 237), match='"name":"10.105.206.87"},{"id":"118e8d36-49ba-11e7>

I want to print entire string:

 "name":"10.105.206.87"},{"id":"118e8d36-49ba-11e7-8c4e-fb1fe31bd90c","type"

Let me know, if I am passing the wrong regex.

Body:
The pattern is correct. You are trying to print the result of re.search. Try to pull only the matched text like below.

 reg='\"name.+,\"type\"'
 match=re.search(reg,string)
 print (match.group())

BTW, I have modified the pattern a little to match till "type"


问:
What can we do about a randomly crashing app without source code?
I am trying to help a client with a problem, but I am running out of ideas. They have a custom, written in house application that runs on a schedule, but it crashes. I don't know how long it has been like this, so I don't think I can trace the crashes back to any particular software updates. The most unfortunate part is there is no longer any source code for the VB6 DLL which contains the meat of the logic.

This VB6 DLL is kicked off by 2-3 function calls from a VB Script. Obviously, I can modify the VB Script to add error logging, but I'm not having much luck getting quality information to pinpoint the source of the crash. I have put logging messages on either side of all of the function calls and determined which of the calls is causing the crash. However, nothing is ever returned in the err object because the call is crashing wscript.exe.

I'm not sure if there is anything else I can do. Any ideas?

Edit: The main reason I care, even though I don't have the source code is that there may be some external factor causing the crash (insufficient credentials, locked file, etc). I have checked the log file that is created in drwtsn32.log as a result of wscript.exe crashing, and the only information I get is an "Access Violation".

I first tend to think this is something to do with security permissions, but couldn't this also be a memory access violation?

答: You may want to try using Resource Hacker you may have luck de-compiling the in house application.  it may not give you the full source code but at least maybe some more info about what the app is doing, which also may help you determine your culrpit.</p>

OwnerDisplayName: Brad Barker

LastEditorDisplayName: Brad Barker

OwnerDisplayName: mrTomahawk


问:
ReSharper will not build multiple projects when debugging
I am using Visual Studio 2015 update 3 and have a solution full of independent API projects. Some time recently, it stopped building all the projects under a multi-project solution when start Debug.

All projects are set to Always Build in the Resharper "Build & Run" settings.

Multiple Startup Projects is selected and the "Build" option is selected on all projects under Configuration manager.

However, only one project will build. That is whatever project is at the top of the Configuration Manager list. I can move a different project to the top of that list to make it the project that builds.

The only way I can get multiple projects to run is to make the top Configuration Manager project depend on them.

I've uninstalled and reinstalled VS and Resharper and reset both to default settings and have had no luck.

Any ideas what the problem might be? I've never had to set all the projects to depend on each other for them to all build before.

Windows 10 Pro FWIW

Updates

Projects and Solutions > Build and Run settings Screenshot

manually executing an MSBUILD command against the SLN file builds all projects without issue.

Still no luck with this but I have, at least, confirmed that it is a ReSharper Build issue. VS Build is building all of the projects as it should. I can, at least, use VS Build until I can figure out what's going on with ReSharper Build.

答: Are you sure you have proper 'Start' Action selected for the projects you want? (The question only says you have Multiple Startup Projects)


问:
C# - Insert XML Element from String template
I have a xml with the given structure:

```<code><ArrayOfElement>
    <Element>
        <ID>1</ID>
        <Value>Value1</Value>
    </Element>
    <Element>
        <ID>2</ID>
        <Value>Value2</Value>
    </Element>
    <Element>
        <ID>3</ID>
        <Value>Value3</Value>
    </Element>
    ...
</ArrayOfElement>
</code>```

And I want to insert another Element with this template (but only if no element with the given ID exists):

```<code><Element>
    <ID>$ID$</ID>
    <Value>$VALUE$</Value>
</Element>
</code>```

So my idea was to load the template as string and replace $ID$ and $VALUE$ by whatever is given. Then I parse this string as a XmlDocumentFragment. And then I need to see if an element with this ID is already present and only if none is there I want to insert the new one.

But I don't know how to find if one exists.

My current approach is:

```<code>// Load the XML with the ArrayOfElement
var allElements = new XmlDocument();
allElements.Load("file.xml");

// Load the template and insert id and value
var xmlTemplate = File.ReadAllText("template.xml");
var fragment = allElements.CreateDocumentFragment();
fragment.InnerXml = xmlTemplate.Replace("$ID$", _id).Replace("$VALUE$", _value);

// This does not work since it will throw an exception if none is found:
if (allElements.SelectNodes("ArrayOfElement/Element/ID/text() = '" + _id + "'").Count == 0)
{
    allElements.appendChild(fragment);
}
</code>```

Also I really want to use a template file because I actually have more complex scenarios where adding these XML-Tags in C# without a template string would be way to much work.

答:
Conditions in XPath must be inside brackets, so rewrite xpath as:</p>

```<code>if (allElements.SelectNodes("ArrayOfElement/Element/ID[text()='" + _id + "']").Count == 0)
</code>```

Body:
I have a xml with the given structure:

<ArrayOfElement>
    <Element>
        <ID>1</ID>
        <Value>Value1</Value>
    </Element>
    <Element>
        <ID>2</ID>
        <Value>Value2</Value>
    </Element>
    <Element>
        <ID>3</ID>
        <Value>Value3</Value>
    </Element>
    ...
</ArrayOfElement>

And I want to insert another Element with this template (but only if no element with the given ID exists):

<Element>
    <ID>$ID$</ID>
    <Value>$VALUE$</Value>
</Element>

So my idea was to load the template as string and replace $ID$ and $VALUE$ by whatever is given. Then I parse this string as a XmlDocumentFragment. And then I need to see if an element with this ID is already present and only if none is there I want to insert the new one.

But I don't know how to find if one exists.

My current approach is:

// Load the XML with the ArrayOfElement
var allElements = new XmlDocument();
allElements.Load("file.xml");

// Load the template and insert id and value
var xmlTemplate = File.ReadAllText("template.xml");
var fragment = allElements.CreateDocumentFragment();
fragment.InnerXml = xmlTemplate.Replace("$ID$", _id).Replace("$VALUE$", _value);

// This does not work since it will throw an exception if none is found:
if (allElements.SelectNodes("ArrayOfElement/Element/ID/text() = '" + _id + "'").Count == 0)
{
    allElements.appendChild(fragment);
}

Also I really want to use a template file because I actually have more complex scenarios where adding these XML-Tags in C# without a template string would be way to much work.

Body:
Conditions in XPath must be inside brackets, so rewrite xpath as:

if (allElements.SelectNodes("ArrayOfElement/Element/ID[text()='" + _id + "']").Count == 0)


问:
How to edit a cell and delete a row by clicking icon in Angular JS 1.3?
Still be a angular learner.

I have my page like

The code is:

```<code>    @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div ng-controller="EmpCtrl">
    <div>
        <h2 align="center">Angular JS Basic Example</h2>
        <h5 align="center">Employee List</h5>
        <table border="1" cellpadding="10" align="center">
            <tr>
                <th>
                    Edit
                </th>
                <th>
                    Employee Id
                </th>
                <th>
                    Employee Name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Email Id
                </th>
                <th>
                    Delete
                </th>
            </tr>
            <tr ng-repeat="emp in employees">
                <td>
                    <a href="#" class="btn btn-default btn-sm">
                        <i class="glyphicon glyphicon-edit"></i>
                    </a>
                </td>
                <td>
                    {{emp.EmployeeId}}
                </td>
                <td>
                    {{emp.EmployeeName}}
                </td>
                <td>
                    {{emp.Address}}
                </td>
                <td>
                    {{emp.EmailId}}
                </td>
                <td>
                    <a href="#"
                       onclick="return confirm('Delete this Employee?');"
                       class="btn btn-default btn-sm">
                        <i class="glyphicon glyphicon-trash"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>
</div>
</code>```

I have the js code for getting all employees. It works well.

```<code>app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
 }
});
</code>```

My asp mvc service code to delete methos is

```<code> [HttpDelete]
    public void DeleteEmployee(int id)
    {
        using (DatabaseContext db = new DatabaseContext())
        {
            var employeeList = db.EmployeeModels.ToList();
            var temp = employeeList.Find(x => x.EmployeeId == id);
            employeeList.Remove(temp);
            db.SaveChanges();
        }
    }
</code>```

I want to click the edit/delete icon to edit or delete, I guess that I have to add other javascript functions to do that.(Maybe ng-clcik??) But I don't know exactly, so how to edit a cell or delete a row?

答:
```<code>//html
<td>
 <a href="#"
    ng-click="delFn(emp.EmployeeId,$index)"
    class="btn btn-default btn-sm">
    <i class="glyphicon glyphicon-trash"></i>
  </a>
</td>

//this way u can achieve it
$scope.delFn = function(id, index){
    var response = confirm('Delete this Employee?');
    if(response) {
       $http.delete('url/' + id).then(function(result) {
          result.data ? $scope.employees.splice(index, 1) : null;
       }
    }
}
</code>```

Body:
Still be a angular learner.

I have my page like

The code is:

    @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Angular JS Basic Example

Employee List

                    Edit

                    Employee Id

                    Employee Name

                    Address

                    Email Id

                    Delete

                    {{emp.EmployeeId}}

                    {{emp.EmployeeName}}

                    {{emp.Address}}

                    {{emp.EmailId}}

I have the js code for getting all employees. It works well.

app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
 }
});

My asp mvc service code to delete methos is

 [HttpDelete]
    public void DeleteEmployee(int id)
    {
        using (DatabaseContext db = new DatabaseContext())
        {
            var employeeList = db.EmployeeModels.ToList();
            var temp = employeeList.Find(x => x.EmployeeId == id);
            employeeList.Remove(temp);
            db.SaveChanges();
        }
    }

I want to click the edit/delete icon to edit or delete, I guess that I have to add other javascript functions to do that.(Maybe ng-clcik??) But I don't know exactly, so how to edit a cell or delete a row?


问:
mysql select on max date per item
I have the following tables:

posts

```<code>| id | message         |
| 1  | a message       |
| 2  | another message |
</code>```

posts_summaries

```<code>| post_id | datetime            | param    | value  |
| 1       | 2016-06-06 09:01:09 | like     | 100    |
| 1       | 2016-06-06 09:01:11 | reach    | 700    |
| 1       | 2016-06-06 09:01:07 | comments | 80     |
| 1       | 2016-06-06 10:01:06 | like     | 180    |
| 1       | 2016-06-06 10:01:12 | reach    | 1200   |
| 1       | 2016-06-06 10:01:09 | comments | 92     |
| 2       | 2016-06-06 09:01:09 | like     | 94     |
| 2       | 2016-06-06 09:01:11 | reach    | 600    |
| 2       | 2016-06-06 09:01:07 | comments | 50     |
| 2       | 2016-06-06 10:01:06 | like     | 133    |
| 2       | 2016-06-06 10:01:12 | reach    | 1100   |
| 2       | 2016-06-06 10:01:09 | comments | 93     |
</code>```

Every hour the current data from every post is stored in the post_summaries table.
Now I want to load only the latest data from a post. So for post 2 that would be

```<code>| 2       | 2016-06-06 10:01:06 | like     | 133    |
| 2       | 2016-06-06 10:01:12 | reach    | 1100   |
| 2       | 2016-06-06 10:01:09 | comments | 93     |
</code>```

I tried to do this by using:

```<code> select param, value, MAX(date) from posts_summaries WHERE post_id = 2 GROUP BY param
</code>```

But this  returns the oldest data with the newest date, so:

```<code>| 2       | 2016-06-06 10:01:06 | like     | 94     |
| 2       | 2016-06-06 10:01:12 | reach    | 600    |
| 2       | 2016-06-06 10:01:09 | comments | 50     |
</code>```

So it gives me the rows from 2016-06-06 09, But with date 2016-06-06 10.

What query can I use to get the latest data per param where post_id = 2

Thanks in advance!

答:
One method is to use a where clause to get the last value for each parameter:

```<code>select ps.*
from post_summaries ps
where ps.post_id = 2 and
      ps.datetime = (select max(ps2.datetime)
                     from post_summaries ps2
                     where ps2.post_id = ps.post_id and ps2.param = ps.param
                    );
</code>```

If you know that there are always three params and they are inserted together, then this is easier:

```<code>select ps.*
from post_summaries ps
where ps.post_id = 2
order by ps.datetime desc
limit 3;
</code>```

Title: mysql select on max date per item

Body:
I have the following tables:

posts

| id | message         |
| 1  | a message       |
| 2  | another message |

posts_summaries

| post_id | datetime            | param    | value  |
| 1       | 2016-06-06 09:01:09 | like     | 100    |
| 1       | 2016-06-06 09:01:11 | reach    | 700    |
| 1       | 2016-06-06 09:01:07 | comments | 80     |
| 1       | 2016-06-06 10:01:06 | like     | 180    |
| 1       | 2016-06-06 10:01:12 | reach    | 1200   |
| 1       | 2016-06-06 10:01:09 | comments | 92     |
| 2       | 2016-06-06 09:01:09 | like     | 94     |
| 2       | 2016-06-06 09:01:11 | reach    | 600    |
| 2       | 2016-06-06 09:01:07 | comments | 50     |
| 2       | 2016-06-06 10:01:06 | like     | 133    |
| 2       | 2016-06-06 10:01:12 | reach    | 1100   |
| 2       | 2016-06-06 10:01:09 | comments | 93     |

Every hour the current data from every post is stored in the post_summaries table.
Now I want to load only the latest data from a post. So for post 2 that would be

| 2       | 2016-06-06 10:01:06 | like     | 133    |
| 2       | 2016-06-06 10:01:12 | reach    | 1100   |
| 2       | 2016-06-06 10:01:09 | comments | 93     |

I tried to do this by using:

 select param, value, MAX(date) from posts_summaries WHERE post_id = 2 GROUP BY param

But this  returns the oldest data with the newest date, so:

| 2       | 2016-06-06 10:01:06 | like     | 94     |
| 2       | 2016-06-06 10:01:12 | reach    | 600    |
| 2       | 2016-06-06 10:01:09 | comments | 50     |

So it gives me the rows from 2016-06-06 09, But with date 2016-06-06 10.

What query can I use to get the latest data per param where post_id = 2

Thanks in advance!

Body:
One method is to use a where clause to get the last value for each parameter:

select ps.*
from post_summaries ps
where ps.post_id = 2 and
      ps.datetime = (select max(ps2.datetime)
                     from post_summaries ps2
                     where ps2.post_id = ps.post_id and ps2.param = ps.param
                    );

If you know that there are always three params and they are inserted together, then this is easier:

select ps.*
from post_summaries ps
where ps.post_id = 2
order by ps.datetime desc
limit 3;


问:
Plesk API - Response error 1019 You specified incorrect username
I  create FTP account  with the Plesk API. Everything works fine until I add the $name variable in  <name>.$name.</name> its showed an error:

Response error 1019 You specified incorrect username.

Can anyone suggest me how to pass variable?

    <?php
require_once('PleskApiClient.php');
 $host = "74.208.10.205";//getenv('REMOTE_HOST');
 $login = getenv('REMOTE_LOGIN') ?: 'root';
 $password = "********";// getenv('REMOTE_PASSWORD');
$client = new PleskApiClient($host);
 $client->setCredentials($login, $password);
$name="finalftp3";
$request = <<<EOF
<packet version="1.6.7.0">
  <ftp-user>
<add>
<name>.$name.</name>
<password>dkfje44Fwe345n</password>
<home>/httpdocs/eie4retailers.com/</home>
<create-non-existent>true</create-non-existent>
<quota>10</quota>
<permissions>
<read>true</read>
<write>true</write>
</permissions>
<webspace-id>1</webspace-id>
</add>
</ftp-user>
</packet>
EOF;
$response = $client->request($request);
echo "Response".$response;`echo "Response".$response;
```

答: I guess <name>.$name.</name> should be <name>$name</name>. You don't need to concat the variable within a heredoc string.


问:
how to play video in same page(media player)
hi i have create one simple media player.... now its working fine. i retrieve video thumbnails in gallery. when i click the thumbnails video will play in other page... if i click thumbnails video play same page...see my screen shot....my video play in that red box...this type of frame how to create.....

this is my screen shot:

if i click thumbnails the video will play another page:
that screen shot:

this is for my coding:

```<code>public class videothumb extends Activity
{
private final static Uri MEDIA_EXTERNAL_CONTENT_URI =
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private Gallery _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
private int video_column_index;

protected Context _context;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    _context = getApplicationContext();

    setContentView(R.layout.main);

    //set GridView for gallery
    _gallery = (Gallery) findViewById(R.id.videoGrdVw);
    //set default as external/sdcard uri
    _contentUri = MEDIA_EXTERNAL_CONTENT_URI;
    //initialize the videos uri
    //showToast(_contentUri.getPath());
    initVideosId();
    //set gallery adapter
    setGalleryAdapter();
}
private void setGalleryAdapter() {
    _gallery.setAdapter(new VideoGalleryAdapter(_context));
    _gallery.setOnItemClickListener(videogridlistener);
    }
private void initVideosId() {
    try
    {
        //Here we set up a string array of the thumbnail ID column we want to get back
        String [] proj={_ID};
        // Now we create the cursor pointing to the external thumbnail store
        _cursor = managedQuery(_contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int count= _cursor.getCount();
        System.out.println("total"+_cursor.getCount());
        // We now get the column index of the thumbnail id
        _columnIndex = _cursor.getColumnIndex(_ID);
        //initialize
        _videosId = new int[count];
        //move position to first element
        _cursor.moveToFirst();
        for(int i=0;i<count;i++)
        {
            int id = _cursor.getInt(_columnIndex);
            //

            _videosId[i]= id;
            //
            _cursor.moveToNext();
            //
        }
    }catch(Exception ex)
    {
        showToast(ex.getMessage().toString());
    }

}
protected void showToast(String msg)
{
    Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
private AdapterView.OnItemClickListener videogridlistener = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position,
long id) {
        // Now we want to actually get the data location of the file
        String [] proj={MEDIA_DATA};
        // We request our cursor again
        _cursor = managedQuery(_contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);
          //System.gc();
         // video_column_index =
           _cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
          _columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
            // Lets move to the selected item in the cursor
            _cursor.moveToPosition(position);

          String filename = _cursor.getString(_columnIndex);
          Intent intent = new Intent(videothumb.this, ViewVideo.class);
          intent.putExtra("videofilename", filename);
          startActivity(intent);
          showToast(filename);
         // Toast.makeText(videothumb.this, "" + position, Toast.LENGTH_SHORT).show();

        }
       };
    private class VideoGalleryAdapter extends BaseAdapter
    {
    public VideoGalleryAdapter(Context c)
    {
        _context = c;

    }
    public int getCount()
    {
        return _videosId.length;
    }
    public Object getItem(int position)
    {
        return position;
    }
    public long getItemId(int position)
    {
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ImageView imgVw= new ImageView(_context);
        try
        {
            if(convertView!=null)
            {
                imgVw= (ImageView) convertView;
            }
            imgVw.setImageBitmap(getImage(_videosId[position]));
            imgVw.setAdjustViewBounds(true);
            imgVw.setBackgroundColor(Color.WHITE);
            imgVw.setLayoutParams(new Gallery.LayoutParams(150, 100));
            imgVw.setPadding(5,5,5,5);
            imgVw.setScaleType(ImageView.ScaleType.FIT_XY);
    }
        catch(Exception ex)
        {
            System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +",
     "+ ex.getMessage());
        }
        return imgVw;
    }

    // Create the thumbnail on the fly
    private Bitmap getImage(int id) {
    Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id,
    MediaStore.Video.Thumbnails.MICRO_KIND, null);
    System.out.println("ff"+MediaStore.Video.Thumbnails.
  getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null));
        return thumb;
       }
      }
     }
</code>```

coding 2:`

```<code>public class ViewVideo extends Activity {
private String filename;
private VideoView Video;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

      setContentView(R.layout.main1);
    //setContentView(new Zoom(this));
    Video=(VideoView)findViewById(R.id.VideoView01);
    System.gc();
    Intent i = getIntent();
    Bundle extras = i.getExtras();
    filename = extras.getString("videofilename");
    Video.setVideoPath(filename);

    Video.setMediaController(new MediaController(this));
    Video.requestFocus();
    Video.start();
   }

   }
</code>```

anyone help me...

答:
```
private VideoView mVView;

mVView= (VideoView) findViewById(R.id.Videoview1);

mVView.setVideoPath("sdcard/filename.mp4");
mVView.start();

```

Body:
hi i have create one simple media player.... now its working fine. i retrieve video thumbnails in gallery. when i click the thumbnails video will play in other page... if i click thumbnails video play same page...see my screen shot....my video play in that red box...this type of frame how to create.....

this is my screen shot:

if i click thumbnails the video will play another page:
that screen shot:

this is for my coding:

public class videothumb extends Activity
{
private final static Uri MEDIA_EXTERNAL_CONTENT_URI =
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private Gallery _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
private int video_column_index;

protected Context _context;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    _context = getApplicationContext();

    setContentView(R.layout.main);

    //set GridView for gallery
    _gallery = (Gallery) findViewById(R.id.videoGrdVw);
    //set default as external/sdcard uri
    _contentUri = MEDIA_EXTERNAL_CONTENT_URI;
    //initialize the videos uri
    //showToast(_contentUri.getPath());
    initVideosId();
    //set gallery adapter
    setGalleryAdapter();
}
private void setGalleryAdapter() {
    _gallery.setAdapter(new VideoGalleryAdapter(_context));
    _gallery.setOnItemClickListener(videogridlistener);
    }
private void initVideosId() {
    try
    {
        //Here we set up a string array of the thumbnail ID column we want to get back
        String [] proj={_ID};
        // Now we create the cursor pointing to the external thumbnail store
        _cursor = managedQuery(_contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int count= _cursor.getCount();
        System.out.println("total"+_cursor.getCount());
        // We now get the column index of the thumbnail id
        _columnIndex = _cursor.getColumnIndex(_ID);
        //initialize
        _videosId = new int[count];
        //move position to first element
        _cursor.moveToFirst();
        for(int i=0;i<count;i++)
        {
            int id = _cursor.getInt(_columnIndex);
            //

            _videosId[i]= id;
            //
            _cursor.moveToNext();
            //
        }
    }catch(Exception ex)
    {
        showToast(ex.getMessage().toString());
    }

}
protected void showToast(String msg)
{
    Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
private AdapterView.OnItemClickListener videogridlistener = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position,
long id) {
        // Now we want to actually get the data location of the file
        String [] proj={MEDIA_DATA};
        // We request our cursor again
        _cursor = managedQuery(_contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);
          //System.gc();
         // video_column_index =
           _cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
          _columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
            // Lets move to the selected item in the cursor
            _cursor.moveToPosition(position);

          String filename = _cursor.getString(_columnIndex);
          Intent intent = new Intent(videothumb.this, ViewVideo.class);
          intent.putExtra("videofilename", filename);
          startActivity(intent);
          showToast(filename);
         // Toast.makeText(videothumb.this, "" + position, Toast.LENGTH_SHORT).show();

        }
       };
    private class VideoGalleryAdapter extends BaseAdapter
    {
    public VideoGalleryAdapter(Context c)
    {
        _context = c;

    }
    public int getCount()
    {
        return _videosId.length;
    }
    public Object getItem(int position)
    {
        return position;
    }
    public long getItemId(int position)
    {
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ImageView imgVw= new ImageView(_context);
        try
        {
            if(convertView!=null)
            {
                imgVw= (ImageView) convertView;
            }
            imgVw.setImageBitmap(getImage(_videosId[position]));
            imgVw.setAdjustViewBounds(true);
            imgVw.setBackgroundColor(Color.WHITE);
            imgVw.setLayoutParams(new Gallery.LayoutParams(150, 100));
            imgVw.setPadding(5,5,5,5);
            imgVw.setScaleType(ImageView.ScaleType.FIT_XY);
    }
        catch(Exception ex)
        {
            System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +",
     "+ ex.getMessage());
        }
        return imgVw;
    }

    // Create the thumbnail on the fly
    private Bitmap getImage(int id) {
    Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id,
    MediaStore.Video.Thumbnails.MICRO_KIND, null);
    System.out.println("ff"+MediaStore.Video.Thumbnails.
  getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null));
        return thumb;
       }
      }
     }

coding 2:`

public class ViewVideo extends Activity {
private String filename;
private VideoView Video;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

      setContentView(R.layout.main1);
    //setContentView(new Zoom(this));
    Video=(VideoView)findViewById(R.id.VideoView01);
    System.gc();
    Intent i = getIntent();
    Bundle extras = i.getExtras();
    filename = extras.getString("videofilename");
    Video.setVideoPath(filename);

    Video.setMediaController(new MediaController(this));
    Video.requestFocus();
    Video.start();
   }

   }

anyone help me...


问:
Vue JS custom component v-model
Hello everyone i have a bit of a problem trying to get v-model to work on a custom component i've created. The problem is that this component consists of two inputs, and each time these are changed i emit the "input" event and bind it to an array i have on the parent.

```<code><key-value-input v-for="n in inputs" v-model="provider.params"></key-value-input>
</code>```

Then in the Component itself...

```<code>        updateData() {
            this.$emit('input', {
                key: this.inputData.key,
                value: this.inputData.value
            })
        }
</code>```

This kinda works the problem is that it replaces provider.params from the original empty array into an object containing only one of the several key-value combinations i might have since this component can be duplicated at runtime...

So the question is, how do i make it so that v-model can fetch the data from each sub-component and simply set it as objects in an array on the parent?

答:
If I understand you correctly, you can simply use v-model on the array element itself:

```<code><key-value-input v-for="n in inputs" v-model="provider.params[n-1]"></key-value-input>
</code>```

Here's the JSFiddle: https://jsfiddle.net/2be4maxm/

Title: Vue JS custom component v-model

Body:
Hello everyone i have a bit of a problem trying to get v-model to work on a custom component i've created. The problem is that this component consists of two inputs, and each time these are changed i emit the "input" event and bind it to an array i have on the parent.

<key-value-input v-for="n in inputs" v-model="provider.params"></key-value-input>

Then in the Component itself...

        updateData() {
            this.$emit('input', {
                key: this.inputData.key,
                value: this.inputData.value
            })
        }

This kinda works the problem is that it replaces provider.params from the original empty array into an object containing only one of the several key-value combinations i might have since this component can be duplicated at runtime...

So the question is, how do i make it so that v-model can fetch the data from each sub-component and simply set it as objects in an array on the parent?

Body:
If I understand you correctly, you can simply use v-model on the array element itself:

<key-value-input v-for="n in inputs" v-model="provider.params[n-1]"></key-value-input>

Here's the JSFiddle: https://jsfiddle.net/2be4maxm/


问:
Parsing XML file in Xamarin Android
I am fairly new to developing for android using Xamarin.

I am making an application that translates dietary requirements into other languages and I am trying to load the options that one can input when making a translation.

To do this the text is put into a list after I have read the XML file:

```<code>            XmlDocument LifeStyles = new XmlDocument();
            LifeStyles.Load("engLifestyles.xml");
</code>```

and the xml is located here:
File Location In Project

However i keep getting this error where the file is named when i run the app:

Unhandled Exception:

System.IO.FileNotFoundException: Could not find file "/engLifestyles.xml". occurred.

Any help will be much appreciated. Thank you in advanced.

答:
In Xamarin.Android project you have to save your file in Assets folder, then you can load it. Assets folder in Xamarin is way to include arbitary files like text, xml, music etc.

Asstes folder files are readonly so if you try to write to your xml file you will get System.UnauthorizedAccessException

So your code should look like this:

```<code>XmlDocument LifeStyles = XmlDocument.Load(Assets.Open("engLifestyles.xml"));
</code>```

or you can use AssetsManager too:

```<code> AssetManager assets = this.Assets;
 XmlDocument LifeStyles = XmlDocument.Load(assets .Open("engLifestyles.xml"));
</code>```

Title: Parsing XML file in Xamarin Android

Body:
I am fairly new to developing for android using Xamarin.

I am making an application that translates dietary requirements into other languages and I am trying to load the options that one can input when making a translation.

To do this the text is put into a list after I have read the XML file:

            XmlDocument LifeStyles = new XmlDocument();
            LifeStyles.Load("engLifestyles.xml");

and the xml is located here:
File Location In Project

However i keep getting this error where the file is named when i run the app:

Unhandled Exception:

System.IO.FileNotFoundException: Could not find file "/engLifestyles.xml". occurred.

Any help will be much appreciated. Thank you in advanced.

Body:
In Xamarin.Android project you have to save your file in Assets folder, then you can load it. Assets folder in Xamarin is way to include arbitary files like text, xml, music etc.

Asstes folder files are readonly so if you try to write to your xml file you will get System.UnauthorizedAccessException

So your code should look like this:

XmlDocument LifeStyles = XmlDocument.Load(Assets.Open("engLifestyles.xml"));

or you can use AssetsManager too:

 AssetManager assets = this.Assets;
 XmlDocument LifeStyles = XmlDocument.Load(assets .Open("engLifestyles.xml"));


问:
Neo4j Family Tree Relationship Design
I am designing an extended family tree using Neo4j.
During the design of the relationships I came up with two approaches:

CREATE (p:Person)-[:PARENT_OF]->(s:Person)
 CREATE (p:Person)-[:STEPPARENT_OF]->(s:Person)
 CREATE (p:Person)-[:MARRIED_TO]->(s:Person)

With this approach I am creating different relationships for every case (keep in mind that there will be a lot of cases = a lot of relationships)

CREATE (p:Person)-[r:PARENT_OF {type:'natural'}]->(s:Person)
 CREATE (p:Person)-[r:PARENT_OF {type:'step'}]->(s:Person)
 CREATE (p:Person)-[r:SPOUSE_OF {type:'marriage'}]->(s:Person)

With this approach there will be less relationships but the design is a little bit messy.

I would like to know which approach will be better and why?

答:
You are choosing beetwen fine-grained (:PARENT_OF, :STEPPARENT_OF, :MARRIED_TO) or generic relationships (:PARENT_OF {type:'natural'}, :PARENT_OF {type:'step'}, :SPOUSE_OF {type:'marriage'}).

The book Graph Databases (available for download in the Neo4j site) by By Ian Robinson, Jim Webber, and Emil Eifrém says:

Differentiating by relationship name is the best way of eliminating
  large swathes of the graph from a traversal. Using one or more
  property values to decide whether or not to follow a relationship
  incurs extra I/O the first time those properties are accessed because
  the properties reside in a separate store file from the
  relationships (after that, however, they’re cached).

Remember that a graph database model should be built focused on the application needs. That is: it depends basically on what type of queries are you asking to your database.

If you need to evaluate the type of the relationship in your graph transversal queries, probably is a good idea split it into separated relationship types.

Otherwise, keep it as a property of a generic relationship type.

Title: Neo4j Family Tree Relationship Design


问:
Bootstrap dropdown doesn't work in Codeigniter
I just learn Codeigniter, previously I try these code with only bootstrap it's working well but when try to use bootstrap with Codeigniter dropdown menu it doesn't work. Nothing to show when i click at my dropdown menu.

Here is code in head section:

```<code><html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="../../favicon.ico">

        <title>Jumbotron Template for Bootstrap</title>

        <link href = "<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet" type="text/css" />

        <link href = "<?php echo base_url(); ?>css/jumbotron.css" rel="stylesheet" type="text/css" />

      </head>
      <body>
        <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Landing Page System</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav">
                <li><a href="#">Link</a></li>
                <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu" role="menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li class="divider"></li>
                <li><a href="#">Separated link</a></li>
                <li class="divider"></li>
                <li><a href="#">One more separated link</a></li>
              </ul>
            </li>
           </ul>
            </div>
          </div>
        </nav>
</code>```

For footer code:

```<code><footer>
        <p>© Company 2014</p>
      </footer>
    </div> <!-- /container -->

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script type="text/javascript" src="<?= base_url(); ?>js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script type="text/javascript" src="<?= base_url(); ?>js/ie10-viewport-bug-workaround.js"></script>
  </body>
</html>
</code>```

答: Always add jquery.min.js at the top of all js</p>

Body:
I just learn Codeigniter, previously I try these code with only bootstrap it's working well but when try to use bootstrap with Codeigniter dropdown menu it doesn't work. Nothing to show when i click at my dropdown menu.

Here is code in head section:

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="../../favicon.ico">

        <title>Jumbotron Template for Bootstrap</title>

        <link href = "<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet" type="text/css" />

        <link href = "<?php echo base_url(); ?>css/jumbotron.css" rel="stylesheet" type="text/css" />

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

              </button>
              Landing Page System

Link

              Dropdown

Action

Another action

Something else here

Separated link

One more separated link

For footer code:

© Company 2014


问:
colorWithAlphaComponent example in Swift
What is the correct syntax for this function in Swift?

The following works fine, and colors the background purple:

```<code> self.view.backgroundColor = UIColor.purpleColor()
</code>```

When I chain the colorWithAlphaComponent function, the view shows the correct alpha for a moment, and then changes to an opaque purple that is relatively dark:

```<code> self.view.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.5)
</code>```

Is this the recommended function for adding an alpha value to a UIColor?

Furthermore, why does the intellisense popup say that this function expects a UIColor as a parameter? E.g.,

```<code>   self.view.backgroundColor = UIColor.colorWithAlphaComponent(<#UIColor#>)
</code>```

EDIT: The behavior is strange. I am setting the background color on a view controller that is being loaded in a modal. As the modal slides up from the bottom, the alpha is correct. When the modal finishes loading, the background color changes to opaque?!

EDIT 2: The problem was not with the code--both the code above and the suggestion below were properly applying the alpha. The issue is the way that modals are being presented--the underlying view is being removed. See:

Transparent Modal View on Navigation Controller

答:
in Swift 3.0

This works for me in xcode 8.2.

yourView.backgroundColor = UIColor.black.withAlphaComponent(0.5)

It may helps you.

Body:
What is the correct syntax for this function in Swift?

The following works fine, and colors the background purple:

 self.view.backgroundColor = UIColor.purpleColor()

When I chain the colorWithAlphaComponent function, the view shows the correct alpha for a moment, and then changes to an opaque purple that is relatively dark:

 self.view.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.5)

Is this the recommended function for adding an alpha value to a UIColor?

Furthermore, why does the intellisense popup say that this function expects a UIColor as a parameter? E.g.,

   self.view.backgroundColor = UIColor.colorWithAlphaComponent(<#UIColor#>)

EDIT: The behavior is strange. I am setting the background color on a view controller that is being loaded in a modal. As the modal slides up from the bottom, the alpha is correct. When the modal finishes loading, the background color changes to opaque?!

EDIT 2: The problem was not with the code--both the code above and the suggestion below were properly applying the alpha. The issue is the way that modals are being presented--the underlying view is being removed. See:

Transparent Modal View on Navigation Controller


问:
Why Angular Material is responive and AngualJS Material isn't?
I'm trying to choose a framework for an application of mine and I stumbled across
Angular Material and AngularJS Material I understand that both are from Google (correct me if I'm wrong) but basically are both doing more or less the same, rendering components in a HTML page, what I don't get (and google around is not very efficent due to confusion on similar name) why Angular material is not responsive and AngularJS Material is? Wich one I should choose in order to make my app responsive? Or..how would I get an Angular Material app respnsive?</p>

答:
Remember, AngularJS Material is still work in progress. (A lot of features are still being added). A good reason to use it (just mentioning as eg.) Angular-data-table is no longer supported in 1.x and development is stopped on it, but more work is being put into md-data-table which is the material design version of the same and offers a heck lot of features. </p>

<p>https://www.npmjs.com/package/md-data-table </p>

Body:
Remember, AngularJS Material is still work in progress. (A lot of features are still being added). A good reason to use it (just mentioning as eg.) Angular-data-table is no longer supported in 1.x and development is stopped on it, but more work is being put into md-data-table which is the material design version of the same and offers a heck lot of features.

https://www.npmjs.com/package/md-data-table


问:
ajax & load are not working togeher
I want to check each time user access when page loading, sessions.php is working and return true or false but load is not working with ajax...

```<code>var section = $("#header a");
section.on('click', function() {
    $.ajax({
        type: "POST",
        url: "/particley/global/post/sessions.php",

        success: function(html) {
            if (html == 'true') {

                $('#load').load(section.id + ' #load');
                window.history.pushState(this.id, this.id, this.id);

                if (this.id == '/p/sign-out') {
                    window.location.assign("/p");
                }

            } else {
                window.location.assign("/p/sign-out");
            }
        }
    });
});
</code>```

答:
```<code>var section = $("#header a");
section.click(function(){
    $('#load').load(this.id + ' #load', function() {
        $.ajax({
            type: "POST",
            url: "/particley/global/post/sessions.php",
            success: function(html)
            {

                if (html != 'true') {
                    window.location.assign("/p/sign-out");
                }
            }

        });
    });
    window.history.pushState(this.id, this.id, this.id);
    if (this.id == '/p/sign-out') {
        window.location.assign("/p/sign-out");
    }
});
</code>```

Title: ajax & load are not working togeher

Body:
I want to check each time user access when page loading, sessions.php is working and return true or false but load is not working with ajax...

var section = $("#header a");
section.on('click', function() {
    $.ajax({
        type: "POST",
        url: "/particley/global/post/sessions.php",

        success: function(html) {
            if (html == 'true') {

                $('#load').load(section.id + ' #load');
                window.history.pushState(this.id, this.id, this.id);

                if (this.id == '/p/sign-out') {
                    window.location.assign("/p");
                }

            } else {
                window.location.assign("/p/sign-out");
            }
        }
    });
});


问:
null is not an object
i am trying to get stored value from the AsyncStorage. but it gives null is not an object error.
here is my code.

```<code>import React, { Component } from 'react';
import { AsyncStorage, Image, View, StatusBar } from 'react-native';
import { connect } from 'react-redux';
import { Container, Button, H3, Text, Header, Title, Content, Icon, Footer, FooterTab, Left, Right, Body } from 'native-base';

import { openDrawer } from '../../actions/drawer';
import styles from './styles';
import Anatomy from '../anatomy/index.js';

const launchscreenBg = require('../../../img/abc.png');
const launchscreenLogo = require('../../../img/mob_app_bg.png');

var STORAGE_KEY_USER = '@ExpLocal:user';

class Home extends Component { // eslint-disable-line

  componentDidMount() {
    this._loadInitialState().done();
  }

  async _loadInitialState() {
    try {
      var user = await AsyncStorage.getItem(STORAGE_KEY_USER);
      if (user !== null){
        this.setState({selectedUser: user});
        this._appendMessage('Logged In User: ' + user);
      } else {
        this._appendMessage('Empty');
      }
    } catch (error) {
      this._appendMessage('AsyncStorage error: ' + error.message);
    }
  }

  getInitialState() {
    return {
      selectedUser: null,
      messages: [],
    };
  }

  static propTypes = {
    openDrawer: React.PropTypes.func,
  }

  render() {
    this._loadInitialState().done();
    // var loggedUser = this.state.selectedUser;
    if(this.state.selectedUser !== null){
      return (
        <Container style={styles.container}>
        <Header>
        <Left>
        <Button transparent onPress={this.props.openDrawer}>
        <Icon name="ios-menu" />
        </Button>
        </Left>
        <Body>
        <Title>Home</Title>
        </Body>
        <Right />
        </Header>
        </Container>
        );
    }else{
      return (
        <Anatomy />
        );
    }

  }
}

function bindActions(dispatch) {
  return {
    openDrawer: () => dispatch(openDrawer()),
  };
}

const mapStateToProps = state => ({
  navigation: state.cardNavigation,
  themeState: state.drawer.themeState,
  routes: state.drawer.routes,
});

export default connect(mapStateToProps, bindActions)(Home);
</code>```

gives following error
null is not an object (evaluating 'this.state.selectedUser')
 E:\REACT_NATIVE_PROJECTS\NativeBase-KitchenSink-master\js\components\home\index.js:49:18
What do i do wrong?

答:
You can use like this :

```<code>AsyncStorage.getItem("STORAGE_KEY_USER").then((value) => {
   var user = value;
  //Your functionalities
}).catch((error) => {
  //Catch Block
});
</code>```

Title: null is not an object

Body:
i am trying to get stored value from the AsyncStorage. but it gives null is not an object error.
here is my code.

import React, { Component } from 'react';
import { AsyncStorage, Image, View, StatusBar } from 'react-native';
import { connect } from 'react-redux';
import { Container, Button, H3, Text, Header, Title, Content, Icon, Footer, FooterTab, Left, Right, Body } from 'native-base';

import { openDrawer } from '../../actions/drawer';
import styles from './styles';
import Anatomy from '../anatomy/index.js';

const launchscreenBg = require('../../../img/abc.png');
const launchscreenLogo = require('../../../img/mob_app_bg.png');

var STORAGE_KEY_USER = '@ExpLocal:user';

class Home extends Component { // eslint-disable-line

  componentDidMount() {
    this._loadInitialState().done();
  }

  async _loadInitialState() {
    try {
      var user = await AsyncStorage.getItem(STORAGE_KEY_USER);
      if (user !== null){
        this.setState({selectedUser: user});
        this._appendMessage('Logged In User: ' + user);
      } else {
        this._appendMessage('Empty');
      }
    } catch (error) {
      this._appendMessage('AsyncStorage error: ' + error.message);
    }
  }

  getInitialState() {
    return {
      selectedUser: null,
      messages: [],
    };
  }

  static propTypes = {
    openDrawer: React.PropTypes.func,
  }

  render() {
    this._loadInitialState().done();
    // var loggedUser = this.state.selectedUser;
    if(this.state.selectedUser !== null){
      return (
        <Container style={styles.container}>

        <Left>
        <Button transparent onPress={this.props.openDrawer}>
        <Icon name="ios-menu" />
        </Button>
        </Left>

        <Title>Home</Title>

        <Right />

        </Container>
        );
    }else{
      return (
        <Anatomy />
        );
    }

  }
}

function bindActions(dispatch) {
  return {
    openDrawer: () => dispatch(openDrawer()),
  };
}

const mapStateToProps = state => ({
  navigation: state.cardNavigation,
  themeState: state.drawer.themeState,
  routes: state.drawer.routes,
});

export default connect(mapStateToProps, bindActions)(Home);

gives following error
null is not an object (evaluating 'this.state.selectedUser')
 E:\REACT_NATIVE_PROJECTS\NativeBase-KitchenSink-master\js\components\home\index.js:49:18
What do i do wrong?

Body:
You can use like this :

AsyncStorage.getItem("STORAGE_KEY_USER").then((value) => {
   var user = value;
  //Your functionalities
}).catch((error) => {
  //Catch Block
});


问:
Jquery .val() work to set value for textbox but .attr() does not

//does not work
$("#TextBoxID1").attr("value","HI Value Change")
//work fine
$("#TextBoxID2").val("HI Value Change")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" id="TextBoxID1"/>
<input type="text" id="TextBoxID2"/></code>```

I want to set value for textbox but jquery .attr() does not work while if I try .val() it works fine.

I am using angular-autocomplete and in its input control I want to set the value using jquery it works but I just want to know why .attr() does not work.

答:
It's maybe just a problem with your internet browser.

The .attr() method works well for your example:-

https://jsfiddle.net/376a1hjj/

Try to run your code with another browser like chrome or firefox if it isn't the case or update your current browser.

Body:
//does not work
$("#TextBoxID1").attr("value","HI Value Change")
//work fine
$("#TextBoxID2").val("HI Value Change")

<input type="text" id="TextBoxID1"/>
<input type="text" id="TextBoxID2"/>

I want to set value for textbox but jquery .attr() does not work while if I try .val() it works fine.

I am using angular-autocomplete and in its input control I want to set the value using jquery it works but I just want to know why .attr() does not work.


问:
time consuming PHP script and the ways to solve the issue?
I have a PHP registration form that is very time consuming  from when the user clicks on the submit button to the point that it will force the server to throw out the following error:

```<code>Request Timeout
This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'.
</code>```

I have been searching on google for ways to solve this issue and there seems to be a few ways of resolving this. however, I would like to know what is the best way of doing this.

I will explain the steps in the registration form from the when the user clicks the submit button:

```<code>step 1- it will checks the mysql database for duplicated data.
step 2- it will create 2 mysql tables with their columns
step 3- it will enter the data passed on by the user into the mysql table.
step 4- it will create a subdomain on my server.
step 5- it will move some files from one folder on my server into the newly created subdomain. there are alot of files but i don't think this should take that long? I need some advise on this please and what is the best way of doing this?
step 6- it will send a confirmation email to the user.
</code>```

I can post my code but it is very big so I thought it might bore anyone's reading this question.

at the top of my PHP registration page, I have this line of code but this has no affect:

```<code>set_time_limit(0);
</code>```

do you think it is best to use the following code instead?

```<code>ini_set('max_execution_time', 300);
</code>```

any advise to solve this issue would be appreciated.

Thanks

答:
This particular error message is generated by the LiteSpeed web server (a faster replacement for Apache).  It has a special feature whereby it cancels long-running scripts. To disable this, you need to put the following in your .htaccess file in the root of your site.

```<code>RewriteEngine On
RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]
</code>```

Body:
I have a PHP registration form that is very time consuming  from when the user clicks on the submit button to the point that it will force the server to throw out the following error:

Request Timeout
This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'.

I have been searching on google for ways to solve this issue and there seems to be a few ways of resolving this. however, I would like to know what is the best way of doing this.

I will explain the steps in the registration form from the when the user clicks the submit button:

step 1- it will checks the mysql database for duplicated data.
step 2- it will create 2 mysql tables with their columns
step 3- it will enter the data passed on by the user into the mysql table.
step 4- it will create a subdomain on my server.
step 5- it will move some files from one folder on my server into the newly created subdomain. there are alot of files but i don't think this should take that long? I need some advise on this please and what is the best way of doing this?
step 6- it will send a confirmation email to the user.

I can post my code but it is very big so I thought it might bore anyone's reading this question.

at the top of my PHP registration page, I have this line of code but this has no affect:

set_time_limit(0);

do you think it is best to use the following code instead?

ini_set('max_execution_time', 300);

any advise to solve this issue would be appreciated.

Thanks

Body:
This particular error message is generated by the LiteSpeed web server (a faster replacement for Apache).  It has a special feature whereby it cancels long-running scripts. To disable this, you need to put the following in your .htaccess file in the root of your site.

RewriteEngine On
RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]