问:
Combining an Image with Text inside a Button
Hi guys im new to coding and currently learning xml and java for android.
Im trying to make a Button which says GOAL but instead of the "O" it will have an image of a ball,i tried just making an image in a designer program thats says goal with the icon of the ball inside it and than use it as an image background for the button but it than misses the gray (which im planning to change to green) background and its not really what im going for.
Is there a way to just add an image inside a button that has text?
Or should i just design the button in a different software and than add it as a background for the button?

like "Te~ImageHere~xt"

答:
You can use ImageSpan to add a drawable in between text. Below is an example .

```<code>  TextView textView=(TextView)findViewById(R.id.b1);
    Spannable span = new SpannableString("G OL");
    Drawable android = getResources().getDrawable(R.mipmap.ic_launcher);
    android.setBounds(0, 0, 50,50);
    ImageSpan image = new ImageSpan(android, ImageSpan.ALIGN_BASELINE);
    span.setSpan(image, 1, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textView.setText(span);
</code>```

Below is the output . You can modify the bounds.

Body:
You can use ImageSpan to add a drawable in between text. Below is an example .

  TextView textView=(TextView)findViewById(R.id.b1);
    Spannable span = new SpannableString("G OL");
    Drawable android = getResources().getDrawable(R.mipmap.ic_launcher);
    android.setBounds(0, 0, 50,50);
    ImageSpan image = new ImageSpan(android, ImageSpan.ALIGN_BASELINE);
    span.setSpan(image, 1, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textView.setText(span);

Below is the output . You can modify the bounds.


来源: stackexchange

问:
Javascript - A function that accepts parameter and return a string which contains "x"
```<code>function change(o)
{
  var str = "";
  for (var p = 0; p<=o ;p++)
  {
    temp = p;
    str = str + temp;
    if (p == o){
    }
    else{
      str = str + ",";
    }
  }
console.log(str);
}
change(5);
</code>```

(consolelog will be changed into return, it's just to view the output)

Basically, I am a beginner who recently started and I wanted to make a simple function that returns a value of the function. For example; if change(5) was inputted, it would return a string value of 5 x's, so xxxxx. If it was change(7), it would return me xxxxxxx, so any idea how to do this? Because my code only gives value from 0 to my inputted value.

答:
I suppose you want this:

```<code>function change(o)
{
  var str = "";
  for (var p = 0; p<o ;p++)
  {
    str += 'x';
  }
  console.log(str);
}

change(5);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
function change(o)
{
  var str = "";
  for (var p = 0; p<=o ;p++)
  {
    temp = p;
    str = str + temp;
    if (p == o){
    }
    else{
      str = str + ",";
    }
  }
console.log(str);
}
change(5);

(consolelog will be changed into return, it's just to view the output)

Basically, I am a beginner who recently started and I wanted to make a simple function that returns a value of the function. For example; if change(5) was inputted, it would return a string value of 5 x's, so xxxxx. If it was change(7), it would return me xxxxxxx, so any idea how to do this? Because my code only gives value from 0 to my inputted value.

Body:
I suppose you want this:

function change(o)
{
  var str = "";
  for (var p = 0; p<o ;p++)
  {
    str += 'x';
  }
  console.log(str);
}

change(5);


问:
Use of google map library on manifest file
Why do we use the below code on our android manifest file.Can anyone please explain?</p>

```<code>        <uses-library
        android:name="com.google.android.maps"
        android:required="true" />
</code>```

答:
uses-library tells the android system that the app requires com.google.android.maps package to be installed in device ie Google maps app

if you put required attribute true, android:required="true" , then the app will be installed only if device has google maps installed in it.

Body:
Why do we use the below code on our android manifest file.Can anyone please explain?

        <uses-library
        android:name="com.google.android.maps"
        android:required="true" />


问:
React BrowserRouter mashing two pages together
Following a tutorial and trying to build on it; I wanted to add a new page to the app. What happens is that when I navigate from "MovieList" to "MovieDetail.js" and then to "About", I have all of header from App.js, the MovieDetail info from that view, and the info on the About page.

I should not be mixing up the About page with anything but the header. What terrible routing monster have I created here?

https://github.com/ctp-placebo/ghibli

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import styled from 'styled-components';
import logo from './static/sootball.png';
import './css/App.css';

import MoviesList from './views/MoviesList';
import MovieDetail from './views/MovieDetail';
import About from './views/About';

const App = () => (
  <Router>

                <Link className="LinkSiteName" to="/">

                </Link>

                <Link className="LinkSiteName" to="/">
                  <SiteName>Studio Ghibli Filmography</SiteName>
                </Link>

                <SiteDesc>
         something
                </SiteDesc>
                <SiteDesc>
         more info
                </SiteDesc>

          <Link className="navbar-item" to="/">
      Home
          </Link>
          <Link className="navbar-item" to="/About/">
      About
          </Link>

      <Switch>
        <Route exact path="/" component={MoviesList} />
        <Route path="/:id" component={MovieDetail} />
      </Switch>

      <Route exact path="/About" component={About} />

  </Router>
);

export default App;

// var navColor = {
//   color: '#aed6f1',
// };

const SiteName = styled.h1`
 margin: 2rem 0 0 1.5rem;
 font-size: xx-large;
 display: inline-block;
`;
const SiteDesc = styled.p`
 margin: 1.5rem 1.5rem 1.5rem 0;
 text-align: justify;
 > a:link {
  text-decoration: underline;
  font-weight: bold;
 }
 > a:visited {
  color: #8000ff;
 }
`;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

```<code>    import React, { Component } from 'react';
import styled from 'styled-components';

const About = function AboutPage() {
  return (
    <div>
      <section className="content" key={0}>
        <p>somthing or other complementary and links</p>
      </section>
    </div>
  );
};

export default About;
</code>```

答:
The problem with your Route config is because not, all your Routes are inside the Switch

```<code>  <Switch>
    <Route exact path="/" component={MoviesList} />
    <Route path="/:id" component={MovieDetail} />
  </Switch>

  <Route exact path="/About" component={About} />
</code>```

So what happens here is that when you go to /About, the route /:id matches and switch goes not further, but since the /about is outside of the switch, it is also matched and hence rendered. You would rather structure your Route like

```<code> <Switch>
    <Route exact path="/" component={MoviesList} />
    <Route exact path="/About" component={About} />
    <Route path="/:id" component={MovieDetail} />
  </Switch>
</code>```

Body:
Following a tutorial and trying to build on it; I wanted to add a new page to the app. What happens is that when I navigate from "MovieList" to "MovieDetail.js" and then to "About", I have all of header from App.js, the MovieDetail info from that view, and the info on the About page.

I should not be mixing up the About page with anything but the header. What terrible routing monster have I created here?

https://github.com/ctp-placebo/ghibli

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import styled from 'styled-components';
import logo from './static/sootball.png';
import './css/App.css';

import MoviesList from './views/MoviesList';
import MovieDetail from './views/MovieDetail';
import About from './views/About';

const App = () => (
  <Router>

                <Link className="LinkSiteName" to="/">

                </Link>

                <Link className="LinkSiteName" to="/">
                  <SiteName>Studio Ghibli Filmography</SiteName>
                </Link>

                <SiteDesc>
         something
                </SiteDesc>
                <SiteDesc>
         more info
                </SiteDesc>

          <Link className="navbar-item" to="/">
      Home
          </Link>
          <Link className="navbar-item" to="/About/">
      About
          </Link>

      <Switch>
        <Route exact path="/" component={MoviesList} />
        <Route path="/:id" component={MovieDetail} />
      </Switch>

      <Route exact path="/About" component={About} />

  </Router>
);

export default App;

// var navColor = {
//   color: '#aed6f1',
// };

const SiteName = styled.h1`
 margin: 2rem 0 0 1.5rem;
 font-size: xx-large;
 display: inline-block;
`;
const SiteDesc = styled.p`
 margin: 1.5rem 1.5rem 1.5rem 0;
 text-align: justify;
 > a:link {
  text-decoration: underline;
  font-weight: bold;
 }
 > a:visited {
  color: #8000ff;
 }
`;

    import React, { Component } from 'react';
import styled from 'styled-components';

const About = function AboutPage() {
  return (

somthing or other complementary and links

  );
};

export default About;

Body:
The problem with your Route config is because not, all your Routes are inside the Switch

  <Switch>
    <Route exact path="/" component={MoviesList} />
    <Route path="/:id" component={MovieDetail} />
  </Switch>

  <Route exact path="/About" component={About} />

So what happens here is that when you go to /About, the route /:id matches and switch goes not further, but since the /about is outside of the switch, it is also matched and hence rendered. You would rather structure your Route like

 <Switch>
    <Route exact path="/" component={MoviesList} />
    <Route exact path="/About" component={About} />
    <Route path="/:id" component={MovieDetail} />
  </Switch>


问:
Biopython, import error with "import Bio"
I have installed Biopython by Anaconda on Windows.

When I try import Bio I get this error:

ModuleNotFoundError: No module named 'Bio'

Why?

答:
Simone.. it looks like your installation did go wrong somehow. Regardless of why and how try the following stepwise approach to see if your import error remains.

On Windows (the dots denote your installed program path specifics):

e.g. go to: C:\....\Anaconda...\Lib\site-packages

find and remove folders using delete.

folder 1: "\Bio"

folder 2: "\biopython-1.70.dist-info"

The version value 1.70 might be 1.69 when using conda for installation.

Empty your trashbin. This way the system can't do tricks and recover or link to deleted files and folders.

Install pip if its not and grab it from here.

try pip install biopython --no-cache-dir

Voila! Hope it works now for you too... Enjoy!

In case its not check windows environment variables\path.. via control panel>advanced system settings to include PATH to site-packages. Or do similar on other OS.


问:
How to set virtual host for specific files?
I am developing an application in Yii 1.1

I want to make separate both frontend and backend. Doc here : Yii 1.1: Organize directories for applications with front-end and back-end using WebApplicationEnd behavior

I have two files in my root index.php and admin.php

I want to index.php file access through frontend.dev and admin.php file access through backend.dev

Code:

```<code><VirtualHost *:80>
    ServerName frontend.dev
    DocumentRoot "C:\xampp\htdocs\myproject"
    <Directory "C:\xampp\htdocs\myproject">
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName backend.dev
    DocumentRoot "C:\xampp\htdocs\myproject"
    <Directory "C:\xampp\htdocs\myproject">
        AllowOverride All
        Order allow,deny
        Allow from all

        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . admin.php
        DirectoryIndex admin.php
        Require all granted
    </Directory>
</VirtualHost>
</code>```

If I opened http://backend.dev then this is working fine. My default admin.php page working which set in virtual DirectoryIndex. But when I access any other controller and action like http://backend.dev/post/test this URL is accessing index.php file. How to manage it?

Please help

EDIT:

```<code>AddDefaultCharset utf-8

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on

# Make the backend accessible via url: http://site/backend.
RewriteRule ^admin admin.php

# If a directory or a file exists, use it directly.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Otherwise forward it to index.php.
RewriteRule . index.php
</code>```

答:
the following can go into your vhost file

```<code><VirtualHost *:80>
    ServerName frontend.dev
    DocumentRoot "C:\xampp\htdocs\myproject"
    <Directory "C:\xampp\htdocs\myproject">
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName backend.dev
    DocumentRoot "C:\xampp\htdocs\myproject"
    <Directory "C:\xampp\htdocs\myproject">
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>
</code>```

and the following can go into your .htaccess file.

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^frontend.dev
RewriteRule ^(.*) index.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^backend.dev
RewriteRule ^(.*) admin.php [L]
</code>```

notice the
RewriteCond %{HTTP_HOST} ^frontend.dev
and
RewriteCond %{HTTP_HOST} ^backend.dev

this will correctly forward the request of the domains to its respective files.

Body:
I am developing an application in Yii 1.1

I want to make separate both frontend and backend. Doc here : Yii 1.1: Organize directories for applications with front-end and back-end using WebApplicationEnd behavior

I have two files in my root index.php and admin.php

I want to index.php file access through frontend.dev and admin.php file access through backend.dev

Code:

<VirtualHost *:80>
    ServerName frontend.dev
    DocumentRoot "C:\xampp\htdocs\myproject"
    <Directory "C:\xampp\htdocs\myproject">
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName backend.dev
    DocumentRoot "C:\xampp\htdocs\myproject"
    <Directory "C:\xampp\htdocs\myproject">
        AllowOverride All
        Order allow,deny
        Allow from all

        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . admin.php
        DirectoryIndex admin.php
        Require all granted
    </Directory>
</VirtualHost>

If I opened http://backend.dev then this is working fine. My default admin.php page working which set in virtual DirectoryIndex. But when I access any other controller and action like http://backend.dev/post/test this URL is accessing index.php file. How to manage it?

Please help

EDIT:

AddDefaultCharset utf-8

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on

# Make the backend accessible via url: http://site/backend.
RewriteRule ^admin admin.php

# If a directory or a file exists, use it directly.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Otherwise forward it to index.php.
RewriteRule . index.php

Body:
the following can go into your vhost file

<VirtualHost *:80>
    ServerName frontend.dev
    DocumentRoot "C:\xampp\htdocs\myproject"
    <Directory "C:\xampp\htdocs\myproject">
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName backend.dev
    DocumentRoot "C:\xampp\htdocs\myproject"
    <Directory "C:\xampp\htdocs\myproject">
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

and the following can go into your .htaccess file.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^frontend.dev
RewriteRule ^(.*) index.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^backend.dev
RewriteRule ^(.*) admin.php [L]

notice the
RewriteCond %{HTTP_HOST} ^frontend.dev
and
RewriteCond %{HTTP_HOST} ^backend.dev

this will correctly forward the request of the domains to its respective files.


问:
Make the parentheses in function calls optional
Hey, I am about to rewrite the core file for my JavaScript library and I am looking for better ways of doing everything. One of these is how I make parentheses optional, for example some function calls look like this.

```<code>Spark('p').content('Hello, World');
</code>```

And others like this.

```<code>Spark.browser();
</code>```

So I have optional parentheses for the Spark function. Am I right in saying this would be the best way?

```<code>window.Spark = function(arg1, arg2) {
    return {
        fn: function() {
            alert('run');
        }
    };
};

for(var f in Spark())
    Spark[f] = Spark()[f];

Spark.fn();
Spark(true, false).fn();
</code>```

It just seems wrong to me although it is the only method I have come up with that works.

答:
You're on the right path, but be careful. As it stands, the fn function will be instantiated every time you call Spark(...), which will cause minor performance and memory usage issues.

A cleaner approach would be to use a class and store all those functions in the prototype to avoid unnecessary memory usage:

```<code>window.Spark = (function(){

  function inner(arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;
  }

  inner.prototype = {
    fn : function() { alert('run') }
  };

  function S(arg1, arg2) { return new inner(arg1, arg2) }

  var dflt = S();
  for (var f in dflt) S[f] = dflt[f];

  return S;
})();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hey, I am about to rewrite the core file for my JavaScript library and I am looking for better ways of doing everything. One of these is how I make parentheses optional, for example some function calls look like this.

Spark('p').content('Hello, World');

And others like this.

Spark.browser();

So I have optional parentheses for the Spark function. Am I right in saying this would be the best way?

window.Spark = function(arg1, arg2) {
    return {
        fn: function() {
            alert('run');
        }
    };
};

for(var f in Spark())
    Spark[f] = Spark()[f];

Spark.fn();
Spark(true, false).fn();

It just seems wrong to me although it is the only method I have come up with that works.

Body:
You're on the right path, but be careful. As it stands, the fn function will be instantiated every time you call Spark(...), which will cause minor performance and memory usage issues.

A cleaner approach would be to use a class and store all those functions in the prototype to avoid unnecessary memory usage:

window.Spark = (function(){

  function inner(arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;
  }

  inner.prototype = {
    fn : function() { alert('run') }
  };

  function S(arg1, arg2) { return new inner(arg1, arg2) }

  var dflt = S();
  for (var f in dflt) S[f] = dflt[f];

  return S;
})();


问:
how to get value from html form and pass is to typescript in angular
Do anyone know how can I get value from HTML forms in typescript?

this is how my html page: login.component.html

```<code><form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser()" #userForm="ngForm">
<div class="container">
  <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><input type="email" formControlName="email" id="email" placeholder="Your email" [(ngModel)]="user.email" required></p>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><input type="password" formControlName="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required></p>
    </div>
  </div>
   <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><button class="btn btn-primary" type="submit" [disabled]="!bookForm.form.valid">Login</button> </p>
    </div>
  </div>
 </div>
</form>
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
        <strong>Successful Login!</strong>
</div>
</code>```

and this is my typescript: login.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  login = false;
  users: any;

  user = {};
  constructor(private fb: FormBuilder, private http: Http, private router: Router, private postsService: PostsService) {
    this.postsService.getAllPosts().subscribe(users => {
      this.users = users;
    });

  }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: 'a@b.com',
      password: 'abc123.'

    });
  }
  authUser() {
    var i:number;
    var email:string = this.loginForm.value.email;
    var password:string = this.loginForm.value.password;
    var userType:string;
    var userEmail:string;
    for(i=0;i<this.users.length;i++){
      if(this.users[i].email == email && this.users[i].password == password){
         this.login = true
         userEmail = this.users[i].email;
         userType = this.users[i].accountType;
        }
    }
    if(this.login){
      console.log("Sucessful");
    }
    else{
      console.log("Unsucessful");

    }
  }

}
</code>```

I have tried a lot of methods but none of them seems to work for now my login the way my code words is that once the button is press it will not check whats in the html forms. but it will check againce var email:string = this.loginForm.value.email; and my database for the email and the value thats in var email:string = this.loginForm.value.email; have been hardcoded.

答:
1.- don't mix Reactive form and Template forms.

```<code>//with ReactiveForm
<input type="password" formControlName="password" id="password" placeholder="Your password" >
//with template Drive Form
<input type="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required>
</code>```

2.- with Template driven Form you must have

```<code>this.user:any={
      email: 'a@b.com',
      password: 'abc123.'
}
//And in the submit function you have this.user.email and this.user.password
</code>```

3.- with Reactive Form

```<code>//the validators it's included when create the fbgroup
this.loginForm = this.fb.group({
      email: ['a@b.com',Required]
      password: ['abc123.',Required]

    });
//in the submit pass loginForm as argument
<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser(loginForm)">
//then in your authUser
authUser(form:any){
  if (form.valid)
  {
      console.log(form.value.email,form.value.password)
  }
}
</code>```

4.-You're checking email and password compared with a list of users, but you really have not a list of users. if really post.Service.getAllPost get a list of users the method have a "very bad" name. Ah! put the subscribe in a ngOnInit, not in de constructor

```<code>ngOnInit()
{
this.postsService.getAllPosts().subscribe(users => {
      this.users = users;
    });
    ....
}
</code>```

Body:
Do anyone know how can I get value from HTML forms in typescript?

this is how my html page: login.component.html

<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser()" #userForm="ngForm">

<input type="email" formControlName="email" id="email" placeholder="Your email" [(ngModel)]="user.email" required>

<input type="password" formControlName="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required>

<button class="btn btn-primary" type="submit" [disabled]="!bookForm.form.valid">Login</button>

</form>

        Successful Login!

and this is my typescript: login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  login = false;
  users: any;

  user = {};
  constructor(private fb: FormBuilder, private http: Http, private router: Router, private postsService: PostsService) {
    this.postsService.getAllPosts().subscribe(users => {
      this.users = users;
    });

  }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: 'a@b.com',
      password: 'abc123.'

    });
  }
  authUser() {
    var i:number;
    var email:string = this.loginForm.value.email;
    var password:string = this.loginForm.value.password;
    var userType:string;
    var userEmail:string;
    for(i=0;i<this.users.length;i++){
      if(this.users[i].email == email && this.users[i].password == password){
         this.login = true
         userEmail = this.users[i].email;
         userType = this.users[i].accountType;
        }
    }
    if(this.login){
      console.log("Sucessful");
    }
    else{
      console.log("Unsucessful");

    }
  }

}

I have tried a lot of methods but none of them seems to work for now my login the way my code words is that once the button is press it will not check whats in the html forms. but it will check againce var email:string = this.loginForm.value.email; and my database for the email and the value thats in var email:string = this.loginForm.value.email; have been hardcoded.

Body:
1.- don't mix Reactive form and Template forms.

//with ReactiveForm
<input type="password" formControlName="password" id="password" placeholder="Your password" >
//with template Drive Form
<input type="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required>

2.- with Template driven Form you must have

this.user:any={
      email: 'a@b.com',
      password: 'abc123.'
}
//And in the submit function you have this.user.email and this.user.password

3.- with Reactive Form

//the validators it's included when create the fbgroup
this.loginForm = this.fb.group({
      email: ['a@b.com',Required]
      password: ['abc123.',Required]

    });
//in the submit pass loginForm as argument
<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser(loginForm)">
//then in your authUser
authUser(form:any){
  if (form.valid)
  {
      console.log(form.value.email,form.value.password)
  }
}

4.-You're checking email and password compared with a list of users, but you really have not a list of users. if really post.Service.getAllPost get a list of users the method have a "very bad" name. Ah! put the subscribe in a ngOnInit, not in de constructor

ngOnInit()
{
this.postsService.getAllPosts().subscribe(users => {
      this.users = users;
    });
    ....
}


问:
SPLIT URL in PHP
I have below URL in my code and i want to split it and get the number from it

For example from the below URL  need to fetch 123456

https://review-test.com/#/c/123456/

I have tried this and it is not working

```<code>$completeURL  = https://review-test.com/#/c/123456/  ;

  list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
</code>```

答:
You can do this without using regex also - </p>

```<code>$completeURL  = 'https://review-test.com/#/c/123456/'  ;

list($url, $number) = explode('#c', str_replace('/', '', $completeURL));

echo $number;
</code>```

Title: SPLIT URL in PHP

Body:
I have below URL in my code and i want to split it and get the number from it

For example from the below URL  need to fetch 123456

https://review-test.com/#/c/123456/

I have tried this and it is not working

$completeURL  = https://review-test.com/#/c/123456/  ;

  list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));

Body:
You can do this without using regex also -

$completeURL  = 'https://review-test.com/#/c/123456/'  ;

list($url, $number) = explode('#c', str_replace('/', '', $completeURL));

echo $number;


问:
ASP.NET Ajax client-side framework failed to load. when put the ScriptManager on a blank page
I have an error Microsoft JScript runtime error: ASP.NET Ajax client-side framework failed to load. on a blank page using masterpage

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

    <div>

    </div>
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="True">
    </asp:ScriptManager>
    </form>
</body>
</html>
</code>```

This is what it render it the end

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
    <form method="post" action="WebForm2.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNjE2OTgwNTY5ZGTfWA/dEX85PXBlbkKsVxeLKyIn+mJQ9piW5cbeNE+qww==" />
</div>

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>

<script src="http://ajax.microsoft.com/ajax/4.0/2/WebForms.js" type="text/javascript"></script>

<script src="/ScriptResource.axd?d=6x_aX-LOcgUU-O_K6nM7ST5ViC_naT1e4_j-CY35ASRLpcKYpiapwTARuePHvx3llP-Xhl_AG_ubpM1BzkM5iyn9ThB3m7lmXKvkck0cxTcYiT-VbeKgamKxp9EwxBUyIQN6sSCU9SQm3tMtmzQWRg2&t=ffffffffbad362a4" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>

<script src="/ScriptResource.axd?d=khKEuZ4oUqBYvQxJ1ISpPVIW8_AWWc907q5_v74DI2ruWKTJpldq2osxPkAZ__hffe1Q6HTQUyTbL3Q1mD6MX7V65O5ibxKwb4NvN6ycdZ8vEJ-bz51MO-8uoaP2xioK6npm5n8vldI1d0sOCnH6yw2&t=ffffffffbad362a4" type="text/javascript"></script>

    <div>

    </div>
    <script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager1', 'form1', [], [], [], 90, '');
//]]>
</script>

    </form>
</body>
</html>
</code>```

The problems might be that i used to have AjaxControlToolkit in my project but later i use jquery instead. so somewhere in the project might try to add Ajaxcontroltoolkit which i can't find it. i don't know how to fix this error. i have tried to add bin file of ajaxcontroltoolkit back but it seems to not work.

答:
For anyone working with the Visual Studio 2015 ASP.NET 4.5 WebForms Web Application project template which bundles the ASP.NET AJAX scripts:

https://stackoverflow.com/a/47673606/313935

Body:
I have an error Microsoft JScript runtime error: ASP.NET Ajax client-side framework failed to load. on a blank page using masterpage

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="True">
    </asp:ScriptManager>
    </form>

This is what it render it the end

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>

</title>

    <form method="post" action="WebForm2.aspx" id="form1">

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNjE2OTgwNTY5ZGTfWA/dEX85PXBlbkKsVxeLKyIn+mJQ9piW5cbeNE+qww==" />

    </form>

The problems might be that i used to have AjaxControlToolkit in my project but later i use jquery instead. so somewhere in the project might try to add Ajaxcontroltoolkit which i can't find it. i don't know how to fix this error. i have tried to add bin file of ajaxcontroltoolkit back but it seems to not work.


问:
Group by date and count specific values in Python
I want to count how many files are produced per day. I have the code to output the files but i don't know what to use to group the files by date and count them.

How do i do this ?

```<code>import xlwt
import os
import datetime

now = datetime.date.today()

extension = '.txt'

envs = ['<foldername>']

for env in envs:
    file_path = '\\<servername>\<folder>\' + env + '\<folder>\'
    for files in os.listdir(file_path):
        list = []
        list.append(os.path.getmtime(file_path+files))
        for list_code_date in list:
            listt=[]
            listt.append(datetime.datetime.fromtimestamp(list_code_date).strftime('%d-%m-%Y'))
        for list_hn_date in listt:
            print list_hn_date
</code>```

答:
I used os.popen instead as i was using to much code originally for a simple task:</p>

```<code>dates = os.popen('cmd /c "cd /d R:\\'+env+'\\Crash_Reports && C:\\cygwin64\\bin\\find_linux.exe . -type f -printf "%TY-%Tm-%Td\\n" | sort |C:\\cygwin64\\bin\\uniq -c | C:\\cygwin64\\bin\\gawk "{print $2}""').read()
</code>```

Body:
I want to count how many files are produced per day. I have the code to output the files but i don't know what to use to group the files by date and count them.

How do i do this ?

import xlwt
import os
import datetime

now = datetime.date.today()

extension = '.txt'

envs = ['<foldername>']

for env in envs:
    file_path = '\\<servername>\<folder>\' + env + '\<folder>\'
    for files in os.listdir(file_path):
        list = []
        list.append(os.path.getmtime(file_path+files))
        for list_code_date in list:
            listt=[]
            listt.append(datetime.datetime.fromtimestamp(list_code_date).strftime('%d-%m-%Y'))
        for list_hn_date in listt:
            print list_hn_date

Body:
I used os.popen instead as i was using to much code originally for a simple task:

dates = os.popen('cmd /c "cd /d R:\\'+env+'\\Crash_Reports && C:\\cygwin64\\bin\\find_linux.exe . -type f -printf "%TY-%Tm-%Td\\n" | sort |C:\\cygwin64\\bin\\uniq -c | C:\\cygwin64\\bin\\gawk "{print $2}""').read()


答:
Here is how you can do it:

function change(o)
{
  var str = "";
  for (var p = 0; p<o ;p++)
  {
    str = str + "x";
  }
console.log(str);
}
change(5);   ```

Title: Javascript - A function that accepts parameter and return a string which contains "x"


问:
Which construction is faster?
Which construction is faster:

```<code>$a = $b * $c ? $b * $c : 0;
</code>```

or

```<code>$i = $b * $c;
$a = $i ? $i : 0;
</code>```

All variables are local ones.

Does speed differs for mulitplication, addition, substraction and division?

Update:

Here's some clarification:

This is a theoretical question about writing speed-optimized code from scratch. Not about "searching bottlenecks".

I can measure code speed by myself. But it's was not a question about homework of using microtime(). It was a question about how PHP-interpreter works (what I tried to figure out by digging google myself but was unseccusfull).

Moreover - I did measuring with myself and was a little confused. Different starting values of $a, $b and $c (combinations of zeros, negative, positive, integer and floats) produce different results between constructions. So I was confused.

BoltClock provide me usefull info but user576875 made my day by posting a link to opcode decoder! His answer contains also direct answer to my question. Thanks!

答:
Your two pieces of code have a drawback each.  One does an additional assignment; the other does an additional mathematical operation.  Best would be to do neither, which, with the ternary operator in PHP 5.3, you can:

```<code>$a = $b * $c ?: 0;
</code>```

Omitting the second part of the ternary causes PHP to put the result of the first part there instead.

Using Martin v. Löwis's benchmarking code, I reckon this is about 25% faster than either.

Title: Which construction is faster?

Body:
Which construction is faster:

$a = $b * $c ? $b * $c : 0;

or

$i = $b * $c;
$a = $i ? $i : 0;

All variables are local ones.

Does speed differs for mulitplication, addition, substraction and division?

Update:

Here's some clarification:

This is a theoretical question about writing speed-optimized code from scratch. Not about "searching bottlenecks".

I can measure code speed by myself. But it's was not a question about homework of using microtime(). It was a question about how PHP-interpreter works (what I tried to figure out by digging google myself but was unseccusfull).

Moreover - I did measuring with myself and was a little confused. Different starting values of $a, $b and $c (combinations of zeros, negative, positive, integer and floats) produce different results between constructions. So I was confused.

BoltClock provide me usefull info but user576875 made my day by posting a link to opcode decoder! His answer contains also direct answer to my question. Thanks!

Body:
Your two pieces of code have a drawback each.  One does an additional assignment; the other does an additional mathematical operation.  Best would be to do neither, which, with the ternary operator in PHP 5.3, you can:

$a = $b * $c ?: 0;

Omitting the second part of the ternary causes PHP to put the result of the first part there instead.

Using Martin v. Löwis's benchmarking code, I reckon this is about 25% faster than either.


问:
Warn me when binding to an undefined value
Is there a devmode setting to console.warn me when defining an angular binding to something undefined?

This would be helpful to catch typos and API changes during development, and could then be turned off in production.

Example:

JS:

```<code>$scope.user = {firstName:'Sam', lastName:null};
</code>```

HTML

```<code>First: <input ng-model="user.first_name"/> <!-- broken -->
Last: <input ng-model="user.lastName"/> <!-- good -->
</code>```

Ideally, Angular could notify that user.first_name resolves to undefined and warn me, while user.lastName resolves to null, so is all right.

答:
I think you can accomplish it with the help of Proxy. I demonstrated only the starting point example. So you can create base controller with "proxy" logic at constructor(and apply it only at case of development stage) and then inherit all other controllers from it:

angular.module('app', []).controller('ctrl', function($scope) {
  var handler = (function() {
    var arrUndef = [];
    return {
      get: function(target, name) {
        if (
          target[name] === undefined
          &&
          arrUndef.indexOf(name) == -1
          &&
          ['document', 'children', 'and other'].indexOf(name) == -1
        ) {
          arrUndef.push(name);
          console.log(`Warning: ${name} is undefined!`);
        }
        return target[name];
      }
    };
  })();
  $scope.__proto__ = new Proxy($scope.__proto__, handler);

  $scope.existed = 33;
  $scope.anotherexisted = 55;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  <input type='text' ng-model='existed' />
  <input type='text' ng-model='absent' />
  <p>{{notexisted}}</p>
  <p>{{anotherexisted}}</p>
</div></code>```

Body:
Is there a devmode setting to console.warn me when defining an angular binding to something undefined?

This would be helpful to catch typos and API changes during development, and could then be turned off in production.

Example:

JS:

$scope.user = {firstName:'Sam', lastName:null};

HTML

First: <input ng-model="user.first_name"/>
Last: <input ng-model="user.lastName"/>

Ideally, Angular could notify that user.first_name resolves to undefined and warn me, while user.lastName resolves to null, so is all right.

Body:
I think you can accomplish it with the help of Proxy. I demonstrated only the starting point example. So you can create base controller with "proxy" logic at constructor(and apply it only at case of development stage) and then inherit all other controllers from it:

angular.module('app', []).controller('ctrl', function($scope) {
  var handler = (function() {
    var arrUndef = [];
    return {
      get: function(target, name) {
        if (
          target[name] === undefined
          &&
          arrUndef.indexOf(name) == -1
          &&
          ['document', 'children', 'and other'].indexOf(name) == -1
        ) {
          arrUndef.push(name);
          console.log(`Warning: ${name} is undefined!`);
        }
        return target[name];
      }
    };
  })();
  $scope.__proto__ = new Proxy($scope.__proto__, handler);

  $scope.existed = 33;
  $scope.anotherexisted = 55;
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  <input type='text' ng-model='existed' />
  <input type='text' ng-model='absent' />
  <p>{{notexisted}}</p>
  <p>{{anotherexisted}}</p>
</div>


问:
How to stop url request to validate credit card number
I have a website (PHP Laravel site) that uses Brainstree to process credit card payments.  Today the site receives A LOT direct request to 1 url that passes in credit card information.  It seems the hacker figures out our parameters and is using my site trying to validate their stolen credit card numbers.

Here is an example of a request.

http://mysite/renew?card_nubmer=42693111111111&ccv=014&expiration_month=11&expiration_year=2019&first_name=beqnykit&last_name=fozwgfrpn&postal_code=44101&type=visa&price=12year=1&country_name=USA&currency=%24

It is causing the CPU usage to be 100%, slowing down my site.

Before our code was processing the request and display an error page. Now it validates the request and redirects invalid renew request to log in page.  The CPU load is still 100%.

What can I do to stop this or stop the CPU load, at the least?

答: Here is the update. The hacker really analyzes the site. It create free users. Each free user uses a credit card to submit an order for a paid membership. We are a target because the amount is small. Using POST doesn't fix this hack. So we have added account activation email and recaptcha in account creation and order page. Luckily, it is stopped pretty quickly. I am just putting the info here to share experience. Thanks for all the help! </p>


问:
Laravel ManyToMany Relationship - On Attach or Detach events
My approach to this problem may not be a good idea. I have to decided whether to use many pivot tables or just one table pivot table and filter the attach and detach events.

I have 4 models about an artist. These are; Artist, Venue, Event, Artwork. The models are there to help me identify which events, venues an artist has been to and which artwork he has exhibited. And also which artworks appear at what venues or events so that I can easily call the Venues(), Artworks(), Events(), Artists() for each model and I should get the collection. I have created a pivot table. The table contains 4 columns.

The pivot system works fine except as you can see in the image multiple rows are created where a single row may be appreciable. An artist may go to an event held at a venue with an artwork. So in this case you would expect a single row without any 0s. So the table above would be collapsed in about 3 rows.

THE ARTIST MODEL:

```<code>class Artist extends Model {

...

public function Artworks (){
    return $this->hasMany('App\Artwork','author_id');
}

public function Events (){
    return $this->belongsToMany('App\Event', 'exhibits', 'artist', 'event');
}

public function Venues (){
    return $this->belongsToMany('App\Venue', 'exhibits', 'artist', 'venue');
}

...
}
</code>```

THE ARTWORK MODEL:

```<code>class Artwork extends Model {
...
public function Events (){
    return $this->belongsToMany('App\Event', 'exhibits', 'artwork', 'event');
}

public function Venues (){
    return $this->belongsToMany('App\Artist', 'exhibits', 'artwork', 'venue');
}
...
}
</code>```

THE EVENT MODEL:

```<code>class Event extends Model {
...
public function Venue (){
    return $this->belongsTo('App\Venue', 'venue_id');
}

public function Artists (){
    return $this->belongsToMany('App\Artist', 'exhibits', 'event', 'artist');
}

public function Artworks (){
    return $this->belongsToMany('App\Artwork', 'exhibits', 'event', 'artwork');
}
...
}
</code>```

THE VENUE MODEL:

```<code>class Venue extends Model {
...
public function Events (){
    return $this->hasMany('App\Event', 'venue');
}

public function Artists (){
    return $this->belongsToMany('App\Artist', 'exhibits', 'venue', 'artist');
}

public function Artworks (){
    return $this->belongsToMany('App\Artworks', 'exhibits', 'venue', 'artworks');
}
...
}
</code>```

Just to clarify;

For the Artwork: I should be able to get at what events and venues the artwork has been exhibited.

For the Artist: I should be able to get what events and venues the artist has exhibit his/her artwork

For the Event: I should be able to get what artworks and artists have been at that event.

For the Venue: I should be able to get what artists, and artworks have been at the venue.

The pivot table creates multiple rows when a single row could be used. An artist can attend a venue for an event to exhibit an artwork.

EDIT:
This about optimizing the table. An artwork may already be attached to an event in the table as a relationship. So now suppose I wanted to attach an artist to the same event - artwork relationship, if I was doing it manually the best way to do it would be to search for where an event has artwork but no artist and attach the artist to the event - artwork relationship instead of creating a 2 new rows for the artist to event relationship and artist to artwork relationship which Laravel is doing at the moment with attach()

答:
Taylor Otwell refuses to add events for changes on belongsToMany relation, see more here https://github.com/laravel/framework/pull/14988
but this package solves a problem
https://github.com/fico7489/laravel-pivot</p>

Body:
My approach to this problem may not be a good idea. I have to decided whether to use many pivot tables or just one table pivot table and filter the attach and detach events.

I have 4 models about an artist. These are; Artist, Venue, Event, Artwork. The models are there to help me identify which events, venues an artist has been to and which artwork he has exhibited. And also which artworks appear at what venues or events so that I can easily call the Venues(), Artworks(), Events(), Artists() for each model and I should get the collection. I have created a pivot table. The table contains 4 columns.

The pivot system works fine except as you can see in the image multiple rows are created where a single row may be appreciable. An artist may go to an event held at a venue with an artwork. So in this case you would expect a single row without any 0s. So the table above would be collapsed in about 3 rows.

THE ARTIST MODEL:

class Artist extends Model {

...

public function Artworks (){
    return $this->hasMany('App\Artwork','author_id');
}

public function Events (){
    return $this->belongsToMany('App\Event', 'exhibits', 'artist', 'event');
}

public function Venues (){
    return $this->belongsToMany('App\Venue', 'exhibits', 'artist', 'venue');
}

...
}

THE ARTWORK MODEL:

class Artwork extends Model {
...
public function Events (){
    return $this->belongsToMany('App\Event', 'exhibits', 'artwork', 'event');
}

public function Venues (){
    return $this->belongsToMany('App\Artist', 'exhibits', 'artwork', 'venue');
}
...
}

THE EVENT MODEL:

class Event extends Model {
...
public function Venue (){
    return $this->belongsTo('App\Venue', 'venue_id');
}

public function Artists (){
    return $this->belongsToMany('App\Artist', 'exhibits', 'event', 'artist');
}

public function Artworks (){
    return $this->belongsToMany('App\Artwork', 'exhibits', 'event', 'artwork');
}
...
}

THE VENUE MODEL:

class Venue extends Model {
...
public function Events (){
    return $this->hasMany('App\Event', 'venue');
}

public function Artists (){
    return $this->belongsToMany('App\Artist', 'exhibits', 'venue', 'artist');
}

public function Artworks (){
    return $this->belongsToMany('App\Artworks', 'exhibits', 'venue', 'artworks');
}
...
}

Just to clarify;

For the Artwork: I should be able to get at what events and venues the artwork has been exhibited.

For the Artist: I should be able to get what events and venues the artist has exhibit his/her artwork

For the Event: I should be able to get what artworks and artists have been at that event.

For the Venue: I should be able to get what artists, and artworks have been at the venue.

The pivot table creates multiple rows when a single row could be used. An artist can attend a venue for an event to exhibit an artwork.

EDIT:
This about optimizing the table. An artwork may already be attached to an event in the table as a relationship. So now suppose I wanted to attach an artist to the same event - artwork relationship, if I was doing it manually the best way to do it would be to search for where an event has artwork but no artist and attach the artist to the event - artwork relationship instead of creating a 2 new rows for the artist to event relationship and artist to artwork relationship which Laravel is doing at the moment with attach()


问:
Excel: Identify 2+ Separate Instances of Values in a Row for a Given Range

The image above is a spreadsheet of staff members down the left and the days of the year across the top. Weekends are in blue.

What I would like to achieve for each row for a given range of dates is to identify two or more separate occurrences of absence. Some of the codes qualify as an absence i.e. IL - Illness, PR - Personal Reasons, some don't i.e. DE - Dentist, MW - Midwife.

The top row is a good example of a row that has two or more separate absences.

One absence is not limited to one day, so if there were concurrent absences a bit like the MA examples then they would count as one absence. Although MA wouldn't count as it stands for maternity.

Apologies for not providing any code as I'm stuck where to start. Even a hint in the right direction would be helpful.

答:
Do you need to have weekends in your data?

I have a solution using SUMPRODUCT but it doesn't handle absences over weekends as a single block (e.g. the MA block).
Here is a screenshot of some dummy data based on your request.

The formulae in column AI are based on this in AI3:

```<code>=SUMPRODUCT((B3:AG3<>"-")*(B3:AG3<>"")*(A3:AF3="-")*1)+SUMPRODUCT((B3:AG3<>"-")*(B3:AG3<>"")*(A3:AF3="")*1)
</code>```

The first term in the first sumproduct formula determines which columns in the range (B to AG) have no absences (indicated by the dash).

The second term determines which columns are weekends (blanks).

The third term determines which previous columns (half-days) have no absences (dash) - it will be necessary to have a blank column before the data (ie. column A as shown in this example - this can be hidden).

The second sumproduct formula does the same thing but the third term handles where the previous half-day was a weekend (blank).

As you can see this works for all except the single block of MA absence. If you were to remove the weekend columns the formula could be simplified.

Body:
Do you need to have weekends in your data?

I have a solution using SUMPRODUCT but it doesn't handle absences over weekends as a single block (e.g. the MA block).
Here is a screenshot of some dummy data based on your request.

The formulae in column AI are based on this in AI3:

=SUMPRODUCT((B3:AG3<>"-")*(B3:AG3<>"")*(A3:AF3="-")*1)+SUMPRODUCT((B3:AG3<>"-")*(B3:AG3<>"")*(A3:AF3="")*1)

The first term in the first sumproduct formula determines which columns in the range (B to AG) have no absences (indicated by the dash).

The second term determines which columns are weekends (blanks).

The third term determines which previous columns (half-days) have no absences (dash) - it will be necessary to have a blank column before the data (ie. column A as shown in this example - this can be hidden).

The second sumproduct formula does the same thing but the third term handles where the previous half-day was a weekend (blank).

As you can see this works for all except the single block of MA absence. If you were to remove the weekend columns the formula could be simplified.


问:
remove duplicate messages from kafka topic
I'm exporting data from a database into Kafka by sending the data in fixed sized batches. I just resend the whole batch, if there is a failure in one batch. My idea was rather than figuring out which messages got imported correctly to deal with the fact that some messages are imported twice.

Kafka implements this compaction step where from all messages with the same message key only the newest message is kept. The compaction would remove all duplicate messages since all the messages have a unique key.

Is there a way to only read from a Kafka topic up to the point where the compaction is complete? It's okay if I can't always read up until the most recent messages as long as I don't read any messages twice.

答:
AFAIK you can't force Kafka compaction, so the only option is to wait until compaction occures (and it could be very tricky).

I think the much better way to handle this situation is to make your consumer idempotent - an idempotent consumer doesn't care how much duplicates you have in your stream, the result remains the same.


问:
Serialize json object with date - javascript
How to serialize json object with specific date format ?

json object

```<code>{"date": "/Date(-62135596800000)/"}
</code>```

to string

```<code>{"date": "Jan 01,1"}
</code>```

and i am using extjs as a core library

答:
Thanks Martin for your answer
As i am using Extjs library so i have modify the code and work perfectly </p>

Body:
How to serialize json object with specific date format ?

json object

{"date": "/Date(-62135596800000)/"}

to string

{"date": "Jan 01,1"}

and i am using extjs as a core library


问:
Error and confusion when creating datatype and monad
Consider the next piece of code:

```<code>data Tile   = EmptyTile | X | O
data Player = Player1 | Player2

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

data Board = (Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile)

emptyBoard :: Board
emptyBoard = (EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile)

instance Monad Board where
    return x = x
    f >>= x = x
</code>```

I'd like that Board will be a monad. But the problem is that i get the following error -

```<code>[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:17:14: error:
    Illegal binding of built-in syntax: (,,,,,,,,)
</code>```

What needs to be changed so that Board can be defined later on as a monad

答:
You write data but mean type or newtype:

```<code>data Tile   = EmptyTile | X | O
data Player = Player1 | Player2

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

type Board = (Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile)

emptyBoard :: Board
emptyBoard = (EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile)
-- this won’t work
instance Monad Board where
    return x = x
    f >>= x = x
</code>```

Or

```<code>data Tile   = EmptyTile | X | O
data Player = Player1 | Player2

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

newtype Board = Board (Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile)

emptyBoard :: Board
emptyBoard = Board (EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile)
-- this also won’t work
instance Monad Board where
    return x = x
    f >>= x = x
</code>```

It’s also worth noting that a board in a game of tic tax toe isn’t going to be a Monad. For one thing it would need a type parameter and for another thing it will obviously never satisfy the laws.

Body:
Consider the next piece of code:

data Tile   = EmptyTile | X | O
data Player = Player1 | Player2

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

data Board = (Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile)

emptyBoard :: Board
emptyBoard = (EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile)

instance Monad Board where
    return x = x
    f >>= x = x

I'd like that Board will be a monad. But the problem is that i get the following error -

[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:17:14: error:
    Illegal binding of built-in syntax: (,,,,,,,,)

What needs to be changed so that Board can be defined later on as a monad

Body:
You write data but mean type or newtype:

data Tile   = EmptyTile | X | O
data Player = Player1 | Player2

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

type Board = (Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile)

emptyBoard :: Board
emptyBoard = (EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile)
-- this won’t work
instance Monad Board where
    return x = x
    f >>= x = x

Or

data Tile   = EmptyTile | X | O
data Player = Player1 | Player2

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

newtype Board = Board (Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile)

emptyBoard :: Board
emptyBoard = Board (EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile)
-- this also won’t work
instance Monad Board where
    return x = x
    f >>= x = x

It’s also worth noting that a board in a game of tic tax toe isn’t going to be a Monad. For one thing it would need a type parameter and for another thing it will obviously never satisfy the laws.


答:
You should try this: basename

basename — Returns trailing name component of path

```<code><?php

echo basename("https://review-test.com/#/c/123456/");

?>
</code>```

Demo : http://codepad.org/9Ah83qaP

Title: SPLIT URL in PHP

Body:
You should try this: basename

basename — Returns trailing name component of path

<?php

echo basename("https://review-test.com/#/c/123456/");

?>

Demo : http://codepad.org/9Ah83qaP


答:
Subsequently you can directly take from pure regex to fetch numbers from string,

```<code>preg_match('!\d+!', "https://review-test.com/#/c/123456/", $matches);
print_r($matches);
</code>```

Working demo

Title: SPLIT URL in PHP

Body:
Subsequently you can directly take from pure regex to fetch numbers from string,

preg_match('!\d+!', "https://review-test.com/#/c/123456/", $matches);
print_r($matches);

Working demo


问:
How to know current name of the database in Django?
I'm writing tests in my django project. For now, I have two database connections:

```<code>(settings.py)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_name'
        ...
    },
}
</code>```

and custom connection to MongoDB:

```<code>import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
try:
    connection = Connection(host="localhost", port=27017)
    db = connection['db_name']
    print "Connected successfully(Mongo, db_name)"
except ConnectionFailure, e:
    sys.stderr.write("Could not connect to MongoDB: %s" % e)
    sys.exit(1)
</code>```

and I want to know when my project is running through

```<code>python manage.py test myapp
</code>```

Because when you run tests, django automatically create separate DB(with name like test_db_name), but in this case Mongo will still run with db_name. I tried:

```<code>import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
from django.db import connections

try:
    connection = Connection(host="localhost", port=27017)
    db_name = connections['default'].settings_dict['NAME']
    db = connection[db_name]
    print "Connected successfully(Mongo, %s)" % (db_name,)
except ConnectionFailure, e:
    sys.stderr.write("Could not connect to MongoDB: %s" % e)
    sys.exit(1)
</code>```

but it does not work

答:
In case of mysql, raw query through django, can be a solution too.</p>

```<code>from django.db import connection
cursor = connection.cursor()
cursor.execute('select database()')
row = cursor.fetchone()

print row[0]
</code>```

Body:
I'm writing tests in my django project. For now, I have two database connections:

(settings.py)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_name'
        ...
    },
}

and custom connection to MongoDB:

import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
try:
    connection = Connection(host="localhost", port=27017)
    db = connection['db_name']
    print "Connected successfully(Mongo, db_name)"
except ConnectionFailure, e:
    sys.stderr.write("Could not connect to MongoDB: %s" % e)
    sys.exit(1)

and I want to know when my project is running through

python manage.py test myapp

Because when you run tests, django automatically create separate DB(with name like test_db_name), but in this case Mongo will still run with db_name. I tried:

import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
from django.db import connections

try:
    connection = Connection(host="localhost", port=27017)
    db_name = connections['default'].settings_dict['NAME']
    db = connection[db_name]
    print "Connected successfully(Mongo, %s)" % (db_name,)
except ConnectionFailure, e:
    sys.stderr.write("Could not connect to MongoDB: %s" % e)
    sys.exit(1)

but it does not work

Body:
In case of mysql, raw query through django, can be a solution too.

from django.db import connection
cursor = connection.cursor()
cursor.execute('select database()')
row = cursor.fetchone()

print row[0]

ContentLicense: CC BY-SA 4.0


问:
"Could not delete from specified tables" error only on published ASP.NET web site
I have written a simple delete query

```<code>delete from mails
</code>```

While I execute I get no problem and the query runs fine, but when I publish the website I get an error stating:

"Could not delete from specified
  tables"

What might be the problem?

I am getting this error when placed in IIS but when i run it in local drive through visual studio i am not getting this error...please help

答:
OK, so we had these exact symptoms on an IIS hosted WCF service.

What we needed in particular was to give the IIS user IIS_IUSR modify and write access rights to parent folder containing the database. In our case, it had not defaulted to have these rights.

Body:
I have written a simple delete query

delete from mails

While I execute I get no problem and the query runs fine, but when I publish the website I get an error stating:

"Could not delete from specified
  tables"

What might be the problem?

I am getting this error when placed in IIS but when i run it in local drive through visual studio i am not getting this error...please help


问:
with clause in oracle
I am trying to get below expected result with WITH clause in Oracle.

```<code>Sample Data
Id          C_Symbol    C_Id
1001        DD          201
1001        VR          202
1002        VR          203
1002        AS          205
1002        QA          206
1003        DD          207
1003        QA          208
1004        AS          209
1004        QA          210
</code>```

Expected

```<code>Id          IS_DD   C_Id(min c_id for each id)
1001        Y       201
1002        N       203
1003        Y       207
1004        N       209
</code>```

Meaning: If any id contains DD in c_symbol it should return flag Y with min c_id.

I tried to achieve this with WITH clause but it doesn't help.

```<code>WITH A_Info As
    (Select id, c_symbol, c_id from XYZ),
    DD_Info As
    (select id, (case when c_symbol = 'DD' then 'Y' else 'N' END As MD),
    row_number() over(partition by a_id order by c_id) as RN)
select * from DD_info where RN = 1;
</code>```

This executes row wise, so looking for some alternate solution.
Thank you,

答:
I would just use aggregation:

```<code>select id,
       max(case when c_symbol = 'DD' then 'Y' else 'N' end) as is_dd,
       min(c_id) as c_id
from sample
group by id;
</code>```

Here is an example.

Title: with clause in oracle

Body:
I am trying to get below expected result with WITH clause in Oracle.

Sample Data
Id          C_Symbol    C_Id
1001        DD          201
1001        VR          202
1002        VR          203
1002        AS          205
1002        QA          206
1003        DD          207
1003        QA          208
1004        AS          209
1004        QA          210

Expected

Id          IS_DD   C_Id(min c_id for each id)
1001        Y       201
1002        N       203
1003        Y       207
1004        N       209

Meaning: If any id contains DD in c_symbol it should return flag Y with min c_id.

I tried to achieve this with WITH clause but it doesn't help.

WITH A_Info As
    (Select id, c_symbol, c_id from XYZ),
    DD_Info As
    (select id, (case when c_symbol = 'DD' then 'Y' else 'N' END As MD),
    row_number() over(partition by a_id order by c_id) as RN)
select * from DD_info where RN = 1;

This executes row wise, so looking for some alternate solution.
Thank you,

Body:
I would just use aggregation:

select id,
       max(case when c_symbol = 'DD' then 'Y' else 'N' end) as is_dd,
       min(c_id) as c_id
from sample
group by id;

Here is an example.


问:
SQL - AVG and Group by
I have the following table:

```<code>Date      |   Product   |   Price
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40
</code>```

I am having hard time finding a query in SQL Server that can give me this result:

```<code>Date      |   Product |   Price
06-12-17  |    1      |   25
05-12-17  |    1      |   30
</code>```

I want the average price for each product everyday

Product starting from 1.1 to 24.4

Title: SQL - AVG and Group by

Body:
I have the following table:

Date      |   Product   |   Price
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40

I am having hard time finding a query in SQL Server that can give me this result:

Date      |   Product |   Price
06-12-17  |    1      |   25
05-12-17  |    1      |   30

I want the average price for each product everyday

Product starting from 1.1 to 24.4

Body:
Try this:

     SELECT date,cast(product AS int) product,avg(Price) Price FROM (
     SELECT * FROM (VALUES
     (cast('06-12-17' as date) ,    1.1      ,   10)
     ,(cast('06-12-17' as date) ,    1.2      ,   20)
     ,(cast('06-12-17' as date) ,    1.3      ,   30)
     ,(cast('06-12-17' as date) ,    1.4      ,   40)
     ,(cast('05-12-17' as date) ,    1.1      ,   20)
     ,(cast('05-12-17' as date) ,    1.2      ,   20)
     ,(cast('05-12-17' as date) ,    1.3      ,   40)
     ,(cast('05-12-17' as date) ,    1.4      ,   40)) a(Date      ,
     Product   ,   Price ))x
     GROUP BY date,cast(product AS int)


问:
Targeting ARM architecture with .NET compiler
When you compile windows application in .NET you can set "Platform Target" to be x86 or x64. This would optimize your code to a specific architecture of the processor and allow to escape IL.
Does anyone know if there's something that would allow to achieve the same result for Windows Mobile application? I'm only interested in running my application on ARM architecture.</p>

答:
Use Mono's Ahead-of-Time (AOT) compilation. That's how they got UNITY scripting onto the iPhone which is an ARM platform. It will probably take some labour to get it up and running on Windows Mobile since, afaik, noone has done that particular platform port yet but the compiler etc should already be there.

You can see Miguel de Icaza's presentation of it at MS PDC here.

OwnerDisplayName: Ilya Volodin

OwnerDisplayName: David Holm

LastEditorDisplayName: David Holm


问:
redirect user from one layout to another in same function - java thymeleaf spring
Hello all I am working on java using thymeleaf.

this is my method to load dashbaord page:

```<code>@Layout("layouts/default.html")
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView Dashboard() {
    ModelAndView mav = null;
    if (session.getAttribute("loginStatus") != "1") {
        mav = new ModelAndView("index.html");
    } else {
        mav = new ModelAndView("dashbaord.html");
    }
    return mav;
}
</code>```

In above method if user is logged in it will load dashbaord.html page which is designed to render layouts/default.html BUT if user is not logged in and tries to load dashboard page, it should go to index.html

BUT in my case index page doesn't contain any layout and when user tries to load dashboard page without login it gives me rendering error for layouts/default.html because index page is not designed to render anything from layouts. it is a separate page with no layout.

I have followed this configuration for my layouts rendering.

Index Page RequestHandler:

```<code>@Layout(Layout.NONE)
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
    ModelAndView mav = null;
    mav = new ModelAndView("index.html");
    return mav;
}
</code>```

Any idea, how can I set the layout conditionally ?

答:
Correct answer :

```<code>@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView Dashboard(HttpSession session) {

    ModelAndView mav = null;
    mav = new ModelAndView("dashbaord.html");
    if (session.getAttribute("loginStatus") != "1") {
        mav=new ModelAndView("redirect:/");
    } else {
        mav=new ModelAndView("dashbaord.html");
    }
    return mav;
}
</code>```

Body:
Hello all I am working on java using thymeleaf.

this is my method to load dashbaord page:

@Layout("layouts/default.html")
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView Dashboard() {
    ModelAndView mav = null;
    if (session.getAttribute("loginStatus") != "1") {
        mav = new ModelAndView("index.html");
    } else {
        mav = new ModelAndView("dashbaord.html");
    }
    return mav;
}

In above method if user is logged in it will load dashbaord.html page which is designed to render layouts/default.html BUT if user is not logged in and tries to load dashboard page, it should go to index.html

BUT in my case index page doesn't contain any layout and when user tries to load dashboard page without login it gives me rendering error for layouts/default.html because index page is not designed to render anything from layouts. it is a separate page with no layout.

I have followed this configuration for my layouts rendering.

Index Page RequestHandler:

@Layout(Layout.NONE)
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
    ModelAndView mav = null;
    mav = new ModelAndView("index.html");
    return mav;
}

Any idea, how can I set the layout conditionally ?

Body:
Correct answer :

@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView Dashboard(HttpSession session) {

    ModelAndView mav = null;
    mav = new ModelAndView("dashbaord.html");
    if (session.getAttribute("loginStatus") != "1") {
        mav=new ModelAndView("redirect:/");
    } else {
        mav=new ModelAndView("dashbaord.html");
    }
    return mav;
}


问:
How to read the JSON file in Angular 4 scripts
I need to read the JSON file which we have stored locally in the project workspace, because I need to read the component.ts file.

Are there any basic steps?

答:
You can read JSON data using HTTP request</p>

```<code>getJsonData(){
    let jsonUrl = 'Your json file path';
    return this.http.get(jsonUrl)
      .map( (response: Response) => {
        const data = response.json();
        return data; } );
}
</code>```

Body:
You can read JSON data using HTTP request

getJsonData(){
    let jsonUrl = 'Your json file path';
    return this.http.get(jsonUrl)
      .map( (response: Response) => {
        const data = response.json();
        return data; } );
}


问:
get service worker id or date from within service worker
Does anybody know if there is a way to get this number or date inside the service worker:

It would be handy to name my service worker cache either cache-1182 or cache-20171127171448

I guess the received date must be known before the install event.

答:
No, this thing does not exist in the Service Worker specs so we must assume it is an internal implementation detail of Google Chrome, thus unaccessible.

To simplify, you might use installation timestamp as the version number and then look for cached resources in the cache marked with the newest timestamp. You can inspect all the cache keys with caches.keys().


问:
SPLIT URL in PHP
I have below URL in my code and i want to split it and get the number from it

For example from the below URL  need to fetch 123456

https://review-test.com/#/c/123456/

I have tried this and it is not working

```<code>$completeURL  = https://review-test.com/#/c/123456/  ;

  list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
</code>```

答:
Use parse_url

It's specifically made for this sort of thing.

Title: SPLIT URL in PHP

Body:
I have below URL in my code and i want to split it and get the number from it

For example from the below URL  need to fetch 123456

https://review-test.com/#/c/123456/

I have tried this and it is not working

$completeURL  = https://review-test.com/#/c/123456/  ;

  list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));


问:
CSS flex layout and overflow: auto child
I'm trying to create a layout:

```<code><div style="display: flex; flex-direction: row;">

    <div id="first" style="flex: 1 1 200px;">...</div>

    <div id="second" style="">
       <div style="overflow: auto">
           <div style="min-width: 1000px"></div>
       </div>
    </div>

    <div id="third" style="flex: 1 1 600px;">...</div>

</div>
</code>```

As you can see, I need a three column layout with first and third column in fixed size. The second column should occupy rest of the space.

The problem is that inside the second column I need to display a large data table with optional scrollbar.

Is there any way how to accomplish this using flexbox?

The problem with my code is, that overflow: auto never works if I'm not specifying width of second child and whole layout ends up with width of 1800px. On the other side I cannot specify it because the second child is supposed to occupy rest of the space.

Thanks!

答:
div {
  border: 1px solid;
  min-height: 40px;
  min-width: 40px;
  padding: 8px;
  box-sizing: border-box;
}

#second>div>div {
  background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display: flex; flex-direction: row;">
  <div id="first" style="flex-basis: 100px;">...</div>
  <div id="second" style="flex: 1;">
    <div style="overflow: auto">
      <div style="min-width: 100px"></div>
    </div>
  </div>
  <div id="third" style="flex-basis: 300px;">...</div>
</div>
<br>
<div style="display: flex; flex-direction: row;">
  <div id="first" style="flex-basis: 100px;">...</div>
  <div id="second" style="flex: 1;">
    <div style="overflow: auto">
      <div style="min-width: 200px"></div>
    </div>
  </div>
  <div id="third" style="flex-basis: 300px;">...</div>
</div>
<br>
<div style="display: flex; flex-direction: row;">
  <div id="first" style="flex-basis: 100px;">...</div>
  <div id="second" style="flex: 1;">
    <div style="overflow: auto">
      <div style="min-width: 1000px"></div>
    </div>
  </div>
  <div id="third" style="flex-basis: 300px;">...</div>
</div></code>```

Body:
I'm trying to create a layout:

...

...

As you can see, I need a three column layout with first and third column in fixed size. The second column should occupy rest of the space.

The problem is that inside the second column I need to display a large data table with optional scrollbar.

Is there any way how to accomplish this using flexbox?

The problem with my code is, that overflow: auto never works if I'm not specifying width of second child and whole layout ends up with width of 1800px. On the other side I cannot specify it because the second child is supposed to occupy rest of the space.

Thanks!

Body:
div {
  border: 1px solid;
  min-height: 40px;
  min-width: 40px;
  padding: 8px;
  box-sizing: border-box;
}

#second>div>div {
  background-color: yellow;
}

<div style="display: flex; flex-direction: row;">
  <div id="first" style="flex-basis: 100px;">...</div>
  <div id="second" style="flex: 1;">
    <div style="overflow: auto">
      <div style="min-width: 100px"></div>
    </div>
  </div>
  <div id="third" style="flex-basis: 300px;">...</div>
</div>
<br>
<div style="display: flex; flex-direction: row;">
  <div id="first" style="flex-basis: 100px;">...</div>
  <div id="second" style="flex: 1;">
    <div style="overflow: auto">
      <div style="min-width: 200px"></div>
    </div>
  </div>
  <div id="third" style="flex-basis: 300px;">...</div>
</div>
<br>
<div style="display: flex; flex-direction: row;">
  <div id="first" style="flex-basis: 100px;">...</div>
  <div id="second" style="flex: 1;">
    <div style="overflow: auto">
      <div style="min-width: 1000px"></div>
    </div>
  </div>
  <div id="third" style="flex-basis: 300px;">...</div>
</div>


问:
Reg-Ex for filtering out, parsing and replacing a specific string? (php)
While developing a private CMS for a client, I've had an idea to implement a php-underlying, yet server-side and flexible "language".

I'm in trouble finding a reqular-expression finding (filter..) the following string ( [..] is the code, which'll be parsed after it's been filtered out ), I want to filter the string out with the line-breaks.

```<code><(
    [..]
)>
</code>```

I was looking for a solution all night, but I didn't find a solution.

答:
First off: Listen to Dan Grossmans advice above.

From my current understanding of your question, you want to get the verbatim content between <( and )> - no exceptions, no comment handling.

If so, try this RegExp

```<code>'/<\(((?:.|\s)*?)\)>/'
</code>```

which you can use like this

```<code>preg_match_all('/<\(((?:.|\s)*?)\)>/', $yourstring, $matches)
</code>```

It doesn't need case insensitivity, and it does lazy matching (so you can apply it to a string with several instances of matches).

Explanation of the RegExp: Starting with <(, ending with )> (brackets escaped of course), in between is the capturing group. At its core, we take either regular characters . or whitespace \s (which solves your problem, since line breaks are whitespace too). We don't want to capture every single character, so the inner group is non capturing - just either whitespace or character: (?:.|\s). This is repeated any number of times (including zero), but only until the first match is complete: *? for lazy 0-n. That's about it, hope it helps.

Body:
While developing a private CMS for a client, I've had an idea to implement a php-underlying, yet server-side and flexible "language".

I'm in trouble finding a reqular-expression finding (filter..) the following string ( [..] is the code, which'll be parsed after it's been filtered out ), I want to filter the string out with the line-breaks.

<(
    [..]
)>

I was looking for a solution all night, but I didn't find a solution.

Body:
First off: Listen to Dan Grossmans advice above.

From my current understanding of your question, you want to get the verbatim content between <( and )> - no exceptions, no comment handling.

If so, try this RegExp

'/<\(((?:.|\s)*?)\)>/'

which you can use like this

preg_match_all('/<\(((?:.|\s)*?)\)>/', $yourstring, $matches)

It doesn't need case insensitivity, and it does lazy matching (so you can apply it to a string with several instances of matches).

Explanation of the RegExp: Starting with <(, ending with )> (brackets escaped of course), in between is the capturing group. At its core, we take either regular characters . or whitespace \s (which solves your problem, since line breaks are whitespace too). We don't want to capture every single character, so the inner group is non capturing - just either whitespace or character: (?:.|\s). This is repeated any number of times (including zero), but only until the first match is complete: *? for lazy 0-n. That's about it, hope it helps.


问:
interval missing first item
I've written some js to the word displaying in #changingword loops through several different words. It mostly works however when it first loads it skips through the second word so it goes from 'design' straight to 'e-commerce solutions', without showing the 'development'. After the first loop it works correctly. My code is below.

The html:

```<code> <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
    <h1>Creative Development</h1>
    <h2 id="changingword">Design</h2>
  </div>
</code>```

The JS:

```<code><script>
(function(){
    var words = [
        'Development',
        'E-commerce Solutions',
        'Optimisation',
        'Support',
        'Design'
        ], i = 0;
    setInterval(function(){
        $('#changingword').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn("slow");
        });
    }, 1500);

})();
</script>
</code>```

Any ideas why this is happening?

答:
It can be tricky to do increment and use result in the same line, you need to be sure how the expression is evaluated.

Change:

```<code>words[i=(i+1)%words.length]
</code>```

to:

```<code>words[i=(++i)%words.length]
</code>```

And set i=-1; to start.

Now the (++i) makes sure i is incremented by 1 immediately, before rest of the expression, that's why we need to start at -1. From there it's all good.

It's an alternative to already posted answer if you wanna keep the expression with increment instead breaking the increment to another row.

General difference of ++i and i++ is same across many languages so it's worth looking into it:

SO post with quick explanation

SO post with better explanation but in diff language

Title: interval missing first item

Body:
I've written some js to the word displaying in #changingword loops through several different words. It mostly works however when it first loads it skips through the second word so it goes from 'design' straight to 'e-commerce solutions', without showing the 'development'. After the first loop it works correctly. My code is below.

The html:

Creative Development

Design

The JS:

Any ideas why this is happening?

Body:
It can be tricky to do increment and use result in the same line, you need to be sure how the expression is evaluated.

Change:

words[i=(i+1)%words.length]

to:

words[i=(++i)%words.length]

And set i=-1; to start.

Now the (++i) makes sure i is incremented by 1 immediately, before rest of the expression, that's why we need to start at -1. From there it's all good.

It's an alternative to already posted answer if you wanna keep the expression with increment instead breaking the increment to another row.

General difference of ++i and i++ is same across many languages so it's worth looking into it:

SO post with quick explanation

SO post with better explanation but in diff language


问:
Add submenu items from an MS Access DB file to a menustrip programmatically
I want to load programmatically some stored titles from an MS Access DB file and add them to a MenuStrip as subitems to existing submenus.

I am using this way to load my DB file, I just don't know how to add those titles into my Menustrip control as subitems...

```<code>Imports System.Data.OleDb

Public Class MainForm
    Public Provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    Public DataFile As String = "database.accdb"
    Public ConnString As String = Provider & DataFile
    Public MyConnection As OleDbConnection = New OleDbConnection
    Public DataReader As OleDbDataReader

    Public Sub ApplicationsMenu_Load()
        MyConnection.ConnectionString = ConnString
        MyConnection.Open()

        Dim str As String = "SELECT * FROM ApplicationsPaths"

        Dim cmd As OleDbCommand = New OleDbCommand(str, MyConnection)
        DataReader = cmd.ExecuteReader

        Try
            While DataReader.Read()
                'Add submenu items code here!!!
            End While
            MyConnection.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class
</code>```

Into an other project I used this way below to add some labels into a FlowLayoutPanel control. I want to do something similar... I just missing the syntax!!!

```<code>While DataReader.Read()
            Dim lbl As New Label()
            Dim count As Integer = StandardPaths_HiddenFlowLayoutPanel.Controls.OfType(Of Label)().ToList().Count
            lbl.Name = "Path_" & DataReader("TagNum").ToString
            lbl.Tag = DataReader("TagNum").ToString
            lbl.Text = DataReader("Path").ToString
            lbl.AutoEllipsis = True
            lbl.AutoSize = True
            lbl.TextAlign = ContentAlignment.MiddleRight
            StandardPaths_HiddenFlowLayoutPanel.Controls.Add(lbl)
        End While
</code>```

EDIT:

I found this way below to add titles from DB file to MenuStrip but it loads them as top menus.

```<code>While DataReader.Read()
            Dim SubItems As New ToolStripMenuItem
            SubItems.Text = DataReader("AppName").ToString
            MainForm_MenuStrip.Items.Add(SubItems)
        End While
</code>```

How can I add them as items to an existing submenu? I am trying MainForm_MenuStrip.DropDownItems.Add(SubItems) and I get 'DropDownItems' is not a member of 'MenuStrip'.

答:
Load the text/menuitems/whatever that is in the database file into a textbox,listbox or simillar control.Make it invisible.Then on form load, use this :

```<code> For each item in listbox1.items
 'this is untested
 'for example, if your menustrip's item name is FILE then
 FileToolStripMenuItem.items.add(item)
 NEXT
</code>```

that's all

Body:
I want to load programmatically some stored titles from an MS Access DB file and add them to a MenuStrip as subitems to existing submenus.

I am using this way to load my DB file, I just don't know how to add those titles into my Menustrip control as subitems...

Imports System.Data.OleDb

Public Class MainForm
    Public Provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    Public DataFile As String = "database.accdb"
    Public ConnString As String = Provider & DataFile
    Public MyConnection As OleDbConnection = New OleDbConnection
    Public DataReader As OleDbDataReader

    Public Sub ApplicationsMenu_Load()
        MyConnection.ConnectionString = ConnString
        MyConnection.Open()

        Dim str As String = "SELECT * FROM ApplicationsPaths"

        Dim cmd As OleDbCommand = New OleDbCommand(str, MyConnection)
        DataReader = cmd.ExecuteReader

        Try
            While DataReader.Read()
                'Add submenu items code here!!!
            End While
            MyConnection.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class

Into an other project I used this way below to add some labels into a FlowLayoutPanel control. I want to do something similar... I just missing the syntax!!!

While DataReader.Read()
            Dim lbl As New Label()
            Dim count As Integer = StandardPaths_HiddenFlowLayoutPanel.Controls.OfType(Of Label)().ToList().Count
            lbl.Name = "Path_" & DataReader("TagNum").ToString
            lbl.Tag = DataReader("TagNum").ToString
            lbl.Text = DataReader("Path").ToString
            lbl.AutoEllipsis = True
            lbl.AutoSize = True
            lbl.TextAlign = ContentAlignment.MiddleRight
            StandardPaths_HiddenFlowLayoutPanel.Controls.Add(lbl)
        End While

EDIT:

I found this way below to add titles from DB file to MenuStrip but it loads them as top menus.

While DataReader.Read()
            Dim SubItems As New ToolStripMenuItem
            SubItems.Text = DataReader("AppName").ToString
            MainForm_MenuStrip.Items.Add(SubItems)
        End While

How can I add them as items to an existing submenu? I am trying MainForm_MenuStrip.DropDownItems.Add(SubItems) and I get 'DropDownItems' is not a member of 'MenuStrip'.

Body:
Load the text/menuitems/whatever that is in the database file into a textbox,listbox or simillar control.Make it invisible.Then on form load, use this :

 For each item in listbox1.items
 'this is untested
 'for example, if your menustrip's item name is FILE then
 FileToolStripMenuItem.items.add(item)
 NEXT

that's all


问:
Calculate total elapsed time of Promises till reject?
I want to test how much requests i can do and get their total time elapsed. My Promise function

```<code>async execQuery(response, query) {
    let request = new SQL.Request();

    return new Promise((resolve, reject) => {
        request.query(query, (error, result) => {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        });
    });
}
</code>```

And my api

```<code>app.get('/api/bookings/:uid', (req, res) => {
    let st = new stopwatch();
    let id = req.params.uid;

    let query = `SELECT * FROM booking.TransactionDetails WHERE UID='${id}'`;
    for (let i = 0; i < 10000; i++) {
        st.start();
        db.execQuery(res, query);
    }
});
</code>```

I can't stop the for loop since its async but I also don't know how can I stop executing other calls after the one which first rejects so i can get the counter and the elapsed time of all successful promises. How can i achieve that?

答:
You made 2 comments that would indicate you want to stop all on going queries when a promise fails but fail to mention what SQL is and if request.query is something that you can cancel.

In your for loop you already ran all the request.query statements, if you want to run only one query and then the other you have to do request.query(query).then(-=>request.query(query)).then... but it'll take longer because you don't start them all at once.

Here is code that would tell you how long all the queries took but I think you should tell us what SQL is so we could figure out how to set connection pooling and caching (probably the biggest performance gainer).

```<code>//removed the async, this function does not await anything
//  so there is no need for async
//removed initializing request, you can re use the one created in
//  the run function, that may shave some time off total runtime
//  but not sure if request can share connections (in that case)
//  it's better to create a couple and pass them along as their
//  connection becomes available (connection pooling)
const execQuery = (response, query, request) =>
  new Promise(
    (resolve, reject) =>
      request.query(
        query
        ,(error, result) =>
          (error)
            ? reject(error)
            : resolve(result)
      )
    );

// save failed queries and resolve them with Fail object
const Fail = function(detail){this.detail=detail;};
//  let request = new SQL.Request();
const run = (numberOfTimes) => {
  const start = new Date().getTime();
  const request = new SQL.Request();
  Promise.all(
    (x=>{
      for (let i = 0; i < numberOfTimes; i++) {
        let query = `SELECT * FROM booking.TransactionDetails WHERE UID='${i}'`;
        db.execQuery(res, query, request)
        .then(
          x=>[x,query]
          ,err=>[err,query]
        )
      }
    })()//IIFE creating array of promises
  )
  .then(
    results => {
      const totalRuntime = new Date().getTime()-start;
      const failed = results.filter(r=>(r&&r.constructor)===Fail);
      console.log(`Total runtime in ms:${totalRuntime}
      Failed:${failed.length}
      Succeeded:${results.length-failed.length}`);
    }
  )
};

//start the whole thing with:
run(10000);
</code>```

Body:
I want to test how much requests i can do and get their total time elapsed. My Promise function

async execQuery(response, query) {
    let request = new SQL.Request();

    return new Promise((resolve, reject) => {
        request.query(query, (error, result) => {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        });
    });
}

And my api

app.get('/api/bookings/:uid', (req, res) => {
    let st = new stopwatch();
    let id = req.params.uid;

    let query = `SELECT * FROM booking.TransactionDetails WHERE UID='${id}'`;
    for (let i = 0; i < 10000; i++) {
        st.start();
        db.execQuery(res, query);
    }
});

I can't stop the for loop since its async but I also don't know how can I stop executing other calls after the one which first rejects so i can get the counter and the elapsed time of all successful promises. How can i achieve that?

Body:
You made 2 comments that would indicate you want to stop all on going queries when a promise fails but fail to mention what SQL is and if request.query is something that you can cancel.

In your for loop you already ran all the request.query statements, if you want to run only one query and then the other you have to do request.query(query).then(-=>request.query(query)).then... but it'll take longer because you don't start them all at once.

Here is code that would tell you how long all the queries took but I think you should tell us what SQL is so we could figure out how to set connection pooling and caching (probably the biggest performance gainer).

//removed the async, this function does not await anything
//  so there is no need for async
//removed initializing request, you can re use the one created in
//  the run function, that may shave some time off total runtime
//  but not sure if request can share connections (in that case)
//  it's better to create a couple and pass them along as their
//  connection becomes available (connection pooling)
const execQuery = (response, query, request) =>
  new Promise(
    (resolve, reject) =>
      request.query(
        query
        ,(error, result) =>
          (error)
            ? reject(error)
            : resolve(result)
      )
    );

// save failed queries and resolve them with Fail object
const Fail = function(detail){this.detail=detail;};
//  let request = new SQL.Request();
const run = (numberOfTimes) => {
  const start = new Date().getTime();
  const request = new SQL.Request();
  Promise.all(
    (x=>{
      for (let i = 0; i < numberOfTimes; i++) {
        let query = `SELECT * FROM booking.TransactionDetails WHERE UID='${i}'`;
        db.execQuery(res, query, request)
        .then(
          x=>[x,query]
          ,err=>[err,query]
        )
      }
    })()//IIFE creating array of promises
  )
  .then(
    results => {
      const totalRuntime = new Date().getTime()-start;
      const failed = results.filter(r=>(r&&r.constructor)===Fail);
      console.log(`Total runtime in ms:${totalRuntime}
      Failed:${failed.length}
      Succeeded:${results.length-failed.length}`);
    }
  )
};

//start the whole thing with:
run(10000);


问:
Turn off iPhone/Safari input element rounding
My website renders well on the iPhone/Safari browser, with one exception: My text input fields have a weird rounded style which doesn't look good at all with the rest of my website.

Is there a way to instruct Safari (via CSS or metadata) not to round the input fields and render them rectangular as intended?

答:
input -webkit-appearance: none; alone does not work.

Try adding -webkit-border-radius:0px; in addition.