问:
How to replace icon-font source with normal image source in CSS file
I want to replace the images with new ones but the problem is that the images are in font style.

Now I want to replace the following with normal image source, like

```<code><img src="images/upload.png>
</code>```

Below is the CSS file in which I want to make changes

```<code>@font-face {
    font-family: "fl-bigmug-line";
    src: url("../fonts/fl-bigmug-line.eot");
    src: url("../fonts/fl-bigmug-line.eot#iefix") format("embedded-opentype"),
    url("../fonts/fl-bigmug-line.woff") format("woff"),
    url("../fonts/fl-bigmug-line.ttf") format("truetype"),
    url("../fonts/fl-bigmug-line.svg") format("svg");
    font-weight: normal;
    font-style: normal;
}

.fl-bigmug-line-ico,
[class^="fl-bigmug-line-"]:before, [class*=" fl-bigmug-line-"]:before,
[class^="fl-bigmug-line-"]:after, [class*=" fl-bigmug-line-"]:after {
    font-family: 'fl-bigmug-line';
    font-size: inherit;
    font-weight: 400;
    font-style: normal;
}

.fl-bigmug-line-add137:before {
    content: "\e000";
}
.fl-bigmug-line-add139:before {
    content: "\e001";
}
.fl-bigmug-line-add149:before {
    content: "\e002";
</code>```

I tried to change the content like content: url("images/upload.png"); but it's not working.

答:
You can do something like this:

.the-icon {
    display: inline-block;
    width: 30px;
    height: 30px;
}

.the-icon:before {
    content: url("https://www.gravatar.com/avatar/3116de43059d7ea110181a5bb773bcdd?s=30");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <i class="the-icon"></i> Upload
</div></code>```

Body:
I want to replace the images with new ones but the problem is that the images are in font style.

Now I want to replace the following with normal image source, like

Below is the CSS file in which I want to make changes

@font-face {
    font-family: "fl-bigmug-line";
    src: url("../fonts/fl-bigmug-line.eot");
    src: url("../fonts/fl-bigmug-line.eot#iefix") format("embedded-opentype"),
    url("../fonts/fl-bigmug-line.woff") format("woff"),
    url("../fonts/fl-bigmug-line.ttf") format("truetype"),
    url("../fonts/fl-bigmug-line.svg") format("svg");
    font-weight: normal;
    font-style: normal;
}

.fl-bigmug-line-ico,
[class^="fl-bigmug-line-"]:before, [class*=" fl-bigmug-line-"]:before,
[class^="fl-bigmug-line-"]:after, [class*=" fl-bigmug-line-"]:after {
    font-family: 'fl-bigmug-line';
    font-size: inherit;
    font-weight: 400;
    font-style: normal;
}

.fl-bigmug-line-add137:before {
    content: "\e000";
}
.fl-bigmug-line-add139:before {
    content: "\e001";
}
.fl-bigmug-line-add149:before {
    content: "\e002";

I tried to change the content like content: url("images/upload.png"); but it's not working.

Body:
You can do something like this:

.the-icon {
    display: inline-block;
    width: 30px;
    height: 30px;
}

.the-icon:before {
    content: url("https://www.gravatar.com/avatar/3116de43059d7ea110181a5bb773bcdd?s=30");
}

<div class="container">
    <i class="the-icon"></i> Upload
</div>


来源: stackexchange

问:
Low latency capture of button click
I want to have a physical button (not a software button) that I put into my custom rig. When I click this button, I want to receive a signal in my software e.g. by registering my callback function.

The goal is to have a panel of physical button that when click will perform certain tasks in the software. The interrupt (for lack of a better word) should be as low latency as possible.

What I have looked at so far:

Arduino: Use an Arduino board that is connected via RS232 and manually do the soldering necessary to hook a button from RadioShack to it. (Too much hardware work for my skill/time availability)

An Android application: Well not truly a hard button to click but it is a hardware. The Android app will communicate with my computer via Bluetooth. (I doubt the latency is good. But I would love to be proved wrong.)

A cross-platform solution is much appreciated.

Targeted platforms: 64-bit Linux and
Windows (in that order)

Language:
C++

Any idea what type of connection/device I should look into to achieve this?

答:
You can use the device driver dev kit to write an hardware interrupt handling object

Connectivity wise - easiest way is a parrallel port - ideally a real one on a card not a USB adaptor, otherwise somethign like a an arduino talking to thePC as a serial port over the USB link is easiest.

Edit - for 50 buttons you will need some sort of keyboard matrix processing as well as a link to the PC. Go for an ardunio. There  is a demo app of reading values from the Arduino's USB cable as a serial port/

ContentLicense: CC BY-SA 2.5

Title: Low latency capture of button click


问:
The issue with using Rollup.js
I'm learning TypeScript and want to use export/import mechanism. I have 3 .ts files and the code looks as following:

1) MyClass.ts:

```<code>/// <reference path="../Scripts/jquery.d.ts" />
/// <reference path="../Scripts/dx.all.d.ts" />
/// <reference path="../Scripts/go.d.ts" />

export class MyClass {
    render(divId: string, text: string): void {
        ...
    }
    getData(): void {
        ...
    }
}
</code>```

2) Caller.ts:

```<code>import { MyClass } from './MyClass';

export class Caller {
    execute() {
        let myClass: MyClass = new MyClass();
        myClass.render("content", "Hello World");
        myClass.getData();
    }
}
</code>```

3) Main.ts:

```<code>import { Caller } from './Caller';

window.onload = () => {
    let caller: Caller = new Caller();
    caller.execute();
};
</code>```

4) HTML:

```<code><script src="~/Scripts/MyClass.js"></script>
<script src="~/Scripts/Caller.js"></script>>
<script src="~/Scripts/Main.js"></script>
</code>```

5) tsconfig.json:

```<code>{
    "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es5",
        "outDir": "../Scripts",
        "allowSyntheticDefaultImports": true,
        "lib": [ "es2015", "dom" ],
        "module": "commonjs"
    },
    "exclude": [
        "node_modules",
        "wwwroot"
    ]
}
</code>```

As I understand the last step is to use some module loader or module bundler. I've picked up module bundler Rollup.js. Again, as I understand Rollaup.js should produce one bundle file that will contain all TypeScript (JavaScript) code I wrote. Is that right?

If so, I've downloaded Rollup.js and went to Scripts sub folder of my MVC 5 web application where are all .ts, .d.ts, .js and other files. I use in my TypeScript code JQuery, DevExtreme and GoJS JavaScript libraries as well.

After that I use the following Rollup command:

```<code>rollup Main.js -o bundle.js -f cjs
</code>```

I've understood that Main.js file was entry point and Rollup will automatically resolve export/import dependencies and create 1 output bundle.js file that I can use in this way in HTML code:

```<code><script src="~/Scripts/bundle.js"></script>
</code>```

The bundle.js file created, but there is nothing except for the content of Main.js file. So, in this way my apllication displayes nothing.

The code I've shown here is just for presentation the issue purposes and the real code is more complex.

What I did wrong?

答: Try using rollup-plugin-typescript rather than pre-compiling your .ts files — here's an example config. (To use a config file, run rollup -c.)

ContentLicense: CC BY-SA 3.0

Title: The issue with using Rollup.js

Body:
I'm learning TypeScript and want to use export/import mechanism. I have 3 .ts files and the code looks as following:

1) MyClass.ts:

/// <reference path="../Scripts/jquery.d.ts" />
/// <reference path="../Scripts/dx.all.d.ts" />
/// <reference path="../Scripts/go.d.ts" />

export class MyClass {
    render(divId: string, text: string): void {
        ...
    }
    getData(): void {
        ...
    }
}

2) Caller.ts:

import { MyClass } from './MyClass';

export class Caller {
    execute() {
        let myClass: MyClass = new MyClass();
        myClass.render("content", "Hello World");
        myClass.getData();
    }
}

3) Main.ts:

import { Caller } from './Caller';

window.onload = () => {
    let caller: Caller = new Caller();
    caller.execute();
};

4) HTML:

>

5) tsconfig.json:

{
    "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es5",
        "outDir": "../Scripts",
        "allowSyntheticDefaultImports": true,
        "lib": [ "es2015", "dom" ],
        "module": "commonjs"
    },
    "exclude": [
        "node_modules",
        "wwwroot"
    ]
}

As I understand the last step is to use some module loader or module bundler. I've picked up module bundler Rollup.js. Again, as I understand Rollaup.js should produce one bundle file that will contain all TypeScript (JavaScript) code I wrote. Is that right?

If so, I've downloaded Rollup.js and went to Scripts sub folder of my MVC 5 web application where are all .ts, .d.ts, .js and other files. I use in my TypeScript code JQuery, DevExtreme and GoJS JavaScript libraries as well.

After that I use the following Rollup command:

rollup Main.js -o bundle.js -f cjs

I've understood that Main.js file was entry point and Rollup will automatically resolve export/import dependencies and create 1 output bundle.js file that I can use in this way in HTML code:

The bundle.js file created, but there is nothing except for the content of Main.js file. So, in this way my apllication displayes nothing.

The code I've shown here is just for presentation the issue purposes and the real code is more complex.

What I did wrong?


问:
how can print big string from a string array or get its index
I want to do a function that takes array of strings and print the big string and the num of chars, for example

```<code>String[] names = { "Microsoft", "lg", "apple","Samsung"}
</code>```

the output is:

bigger name is :Microsoft

num of chars 9

I have done num of chars but i don't know how to print the name**

```<code>String[] names = { "microsoft", "lg", "apple","samsung"};
int big = 0;
for (int i = 0; i < names.Length; i++) {
    if (big<names[i].Length) {
        big = names[i].Length;
    }
}
Console.WriteLine("bigger name is{0}chars  ",big);

</code>```

答:
Instead of storing the length in big, store the biggest string:

```<code>String biggerString = "";
</code>```

And compare the biggerString length inside the loop.

Body:
I want to do a function that takes array of strings and print the big string and the num of chars, for example

String[] names = { "Microsoft", "lg", "apple","Samsung"}

the output is:

bigger name is :Microsoft

num of chars 9

I have done num of chars but i don't know how to print the name**

String[] names = { "microsoft", "lg", "apple","samsung"};
int big = 0;
for (int i = 0; i < names.Length; i++) {
    if (big<names[i].Length) {
        big = names[i].Length;
    }
}
Console.WriteLine("bigger name is{0}chars  ",big);

Body:
Instead of storing the length in big, store the biggest string:

String biggerString = "";

And compare the biggerString length inside the loop.


问:
Time complexity optimisation of a "nested for loop" method
I am trying to find the largest differences between indexes of two equal elements, in an zero-index array of integers.

My for loop currently looks like this, with a "nested for loops" structure
which means its time complexity is O(N^2).

Is it possible of reducing its time complexity to O(N * log(N)) or lower?

```<code>public static Integer solution(Integer[] arr) {
    Integer l = arr.length;
    int result = 0;
    for (int i = 0; i < l; i++) {
        for (int j = 0; j < l; j++) {
            if (arr[i] == arr[j]) {
                result = Math.max(result, Math.abs(i - j));
            }
        }
    }
    return result;
}
</code>```

答:
I assume you are trying to find the highest difference of two indexes of equal numbers in an array. You don't need to run through the entire array 2 times. The inner loop can simply end at i which will greatly reduce complexity.

```<code>public static int solution(int[] arr) {
  int l = arr.length;
  int result = 0;
  for (int i = 0; i < l; i++) {
    for (int j = 0; j < i; j++) {
    if (arr[i] == arr[j]) {
        result = Math.max(result, Math.abs(i - j));
    }
    }
  }
  return result;
}
</code>```

The complexity should just about be O(N * log(N)).

Body:
I am trying to find the largest differences between indexes of two equal elements, in an zero-index array of integers.

My for loop currently looks like this, with a "nested for loops" structure
which means its time complexity is O(N^2).

Is it possible of reducing its time complexity to O(N * log(N)) or lower?

public static Integer solution(Integer[] arr) {
    Integer l = arr.length;
    int result = 0;
    for (int i = 0; i < l; i++) {
        for (int j = 0; j < l; j++) {
            if (arr[i] == arr[j]) {
                result = Math.max(result, Math.abs(i - j));
            }
        }
    }
    return result;
}

Body:
I assume you are trying to find the highest difference of two indexes of equal numbers in an array. You don't need to run through the entire array 2 times. The inner loop can simply end at i which will greatly reduce complexity.

public static int solution(int[] arr) {
  int l = arr.length;
  int result = 0;
  for (int i = 0; i < l; i++) {
    for (int j = 0; j < i; j++) {
    if (arr[i] == arr[j]) {
        result = Math.max(result, Math.abs(i - j));
    }
    }
  }
  return result;
}

The complexity should just about be O(N * log(N)).


问:
Can't create table with jpa+spring boot
I'm trying to generate table using JPA. but i can't create it. There is no error in the code, but it seems that there is configuration error. but i can't find it, i tried many configurations but nothing happen.
Thanks a lot.

This is application.property:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/springapp
spring.datasource.username= root
spring.datasource.password= me
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
</code>```

this is my class:

```<code>@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private String phone;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public Customer(String name, String phone) {
        super();
        this.name = name;
        this.phone = phone;
    }
    public Customer() {
        super();
    }
}
</code>```

This is the application:

```<code>@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

And this is the controller:

@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    CustomerRepository customerRepository;

```<code>@RequestMapping("/findall")
@ResponseBody
public List<Customer> findAll() {
    return customerRepository.findAll();
}
</code>```

}

Pom.xml

```<code>    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>GStock-3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>GStock-3</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
execute following on your mysql:

mysql> create database db_example; -- Create the new database

mysql> create user 'springuser'@'localhost' identified by 'ThePassword'; -- Creates the user

mysql> grant all on db_example.* to 'springuser'@'localhost'; -- Gives all the privileges to the new user on the newly created database

and add into application.xml:

```<code>spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
</code>```

OR

you can go through this link

Title: Can't create table with jpa+spring boot

Body:
I'm trying to generate table using JPA. but i can't create it. There is no error in the code, but it seems that there is configuration error. but i can't find it, i tried many configurations but nothing happen.
Thanks a lot.

This is application.property:

spring.datasource.url=jdbc:mysql://localhost:3306/springapp
spring.datasource.username= root
spring.datasource.password= me
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create

this is my class:

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private String phone;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public Customer(String name, String phone) {
        super();
        this.name = name;
        this.phone = phone;
    }
    public Customer() {
        super();
    }
}

This is the application:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

And this is the controller:

@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    CustomerRepository customerRepository;

@RequestMapping("/findall")
@ResponseBody
public List<Customer> findAll() {
    return customerRepository.findAll();
}

}

Pom.xml

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>GStock-3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>GStock-3</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Body:
execute following on your mysql:

mysql> create database db_example; -- Create the new database

mysql> create user 'springuser'@'localhost' identified by 'ThePassword'; -- Creates the user

mysql> grant all on db_example.* to 'springuser'@'localhost'; -- Gives all the privileges to the new user on the newly created database

and add into application.xml:

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword

OR

you can go through this link


问:
Laravel validating space character always failed
Trying to validate if there are only spaces in input box.

This is my validations:

```<code><?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use App\Rules\allAreSpaces;

class StoreUser extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            'email' => 'required|email|max:64',
            'phone' => 'bail|required|numeric|phone_min|phone_max|unique:users|not_in:0',
            'password' => [new allAreSpaces, 'required', 'min:8', 'max:16', 'confirmed'],
            'password_confirmation' => 'required',
        ];

    }

    public function messages()
    {
        return [
            'email.required'     => 'Email address cannot be empty',
            'email.email'     => 'Enter a valid Email address',
            'email.max'     => 'Email address cannot exceed 64 characters',
            'email.unique'     => 'Email already exists',

            'phone.required'     => 'Mobile number cannot be empty',
            'phone.numeric'     => 'Mobile number has to be numeric',
            'phone.phone_min'     => 'Mobile number should contain a minimum 5 characters',
            'phone.phone_max'     => 'Mobile number cannot exceed 11 characters',
            'phone.unique'     => 'Mobile number already exists',
            'phone.not_in'     => 'Enter a valid mobile number ',

            'password.required'     => 'Password cannot be empty',
            'password.min'     => 'Password should contain minimum 8 characters',
            'password.max'     => 'Password cannot exceed 16 characters',
            'password.confirmed'     => 'Password mismatch.Retry',

            'password_confirmation.required'     => 'Confirm Password cannot be empty',
        ];
    }

    public function withValidator(Validator $validator)
    {

        $email = $this->request->get( 'email' );  // Start with

        $user = \App\User::Where('email', $email)->first();

        if($user && $user->activated == 0){

            $row = \App\User::find($user->id);
            $row->delete();

        }else{

            $validator->sometimes('email', 'unique:users', function ($input) {
                return true;
            });
        }

    }

}
</code>```

The following is the custom rule object that i was created:

```<code><?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class allAreSpaces implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {

        if(strlen($value) > 0){
            if (strlen(trim($value)) == 0){
                return false;
            }
        }
        return true;

    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Password cannot contain space character alone';
    }
}
</code>```

Initially its returning, 'Password cannot contain space character alone'. but after i type some spaces then submit it shows 'Password cannot be empty'. But i want 'Password cannot contain space character alone' if the typed characters are only spaces.

Eventhough i did use the following code, its not showing if the input has some spaces, instead it shows, 'Password cannot be empty'.

```<code> public function passes($attribute, $value)
    {
        return false;

    }
</code>```

i was wondering why is that?

答:
Have you checked the global middleware, that is ran for all routes in your application which is set in your HTTP Kernel? These might come into play:

"By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.

If you would like to disable this behavior, you may remove the two middleware from your application's middleware stack by removing them from the $middleware property of your App\Http\Kernel class."

Laravel 5.5 Docs - Requests - Input trimming and normalization

This might be relevant as well, goes into some complications that can happen because of these middleware:

"By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid. "

Laravel 5.5 Docs - Validation - A note on optional fields

Body:
Trying to validate if there are only spaces in input box.

This is my validations:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use App\Rules\allAreSpaces;

class StoreUser extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            'email' => 'required|email|max:64',
            'phone' => 'bail|required|numeric|phone_min|phone_max|unique:users|not_in:0',
            'password' => [new allAreSpaces, 'required', 'min:8', 'max:16', 'confirmed'],
            'password_confirmation' => 'required',
        ];

    }

    public function messages()
    {
        return [
            'email.required'     => 'Email address cannot be empty',
            'email.email'     => 'Enter a valid Email address',
            'email.max'     => 'Email address cannot exceed 64 characters',
            'email.unique'     => 'Email already exists',

            'phone.required'     => 'Mobile number cannot be empty',
            'phone.numeric'     => 'Mobile number has to be numeric',
            'phone.phone_min'     => 'Mobile number should contain a minimum 5 characters',
            'phone.phone_max'     => 'Mobile number cannot exceed 11 characters',
            'phone.unique'     => 'Mobile number already exists',
            'phone.not_in'     => 'Enter a valid mobile number ',

            'password.required'     => 'Password cannot be empty',
            'password.min'     => 'Password should contain minimum 8 characters',
            'password.max'     => 'Password cannot exceed 16 characters',
            'password.confirmed'     => 'Password mismatch.Retry',

            'password_confirmation.required'     => 'Confirm Password cannot be empty',
        ];
    }

    public function withValidator(Validator $validator)
    {

        $email = $this->request->get( 'email' );  // Start with

        $user = \App\User::Where('email', $email)->first();

        if($user && $user->activated == 0){

            $row = \App\User::find($user->id);
            $row->delete();

        }else{

            $validator->sometimes('email', 'unique:users', function ($input) {
                return true;
            });
        }

    }

}

The following is the custom rule object that i was created:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class allAreSpaces implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {

        if(strlen($value) > 0){
            if (strlen(trim($value)) == 0){
                return false;
            }
        }
        return true;

    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Password cannot contain space character alone';
    }
}

Initially its returning, 'Password cannot contain space character alone'. but after i type some spaces then submit it shows 'Password cannot be empty'. But i want 'Password cannot contain space character alone' if the typed characters are only spaces.

Eventhough i did use the following code, its not showing if the input has some spaces, instead it shows, 'Password cannot be empty'.

 public function passes($attribute, $value)
    {
        return false;

    }

i was wondering why is that?


问:
Run Selenium Commands For Zalenium from another Docker Container
Due to my circumstances for the current project I need to use 2 docker images together for selenium testing.

One is called Zalenium.  I have it up and working via the docker-compose demo.  Its basically like the selenium docker repo except that this can record video and show you live progress.

```<code>zalenium:
        image: "dosel/zalenium"
        container_name: zalenium
        hostname: zalenium
        tty: true
        volumes:
            - /Users/josephastrahan/seluser/videos:/home/seluser/videos
            - /var/run/docker.sock:/var/run/docker.sock
            - /usr/bin/docker:/usr/bin/docker
        ports:
            - 4444:4444
        command: >
          start --chromeContainers 1
                --firefoxContainers 1
                --maxDockerSeleniumContainers 8
                --screenWidth 800 --screenHeight 600
                --timeZone "Europe/Berlin"
                --videoRecordingEnabled true
                --sauceLabsEnabled false
                --browserStackEnabled false
                --testingBotEnabled false
                --startTunnel false
        environment:
          - HOST_UID
          - HOST_GID
          - SAUCE_USERNAME
          - SAUCE_ACCESS_KEY
          - BROWSER_STACK_USER
          - BROWSER_STACK_KEY
          - TESTINGBOT_KEY
          - TESTINGBOT_SECRET
</code>```

The other image is a NodeJS server pre-installed with Mocha and the nodejs (npm package) of selenium-webdriver so that I can run the commands to trigger browser automation.  Details on this here (https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver) and here (https://hub.docker.com/r/qmu1/selenium-webdriver-node/)

You can see Zalenium running from docker compose just fine here.  I can see the time updating every second correctly so its definitely showing a live view.

According to the documentation for the other docker container I'm using which is here (https://hub.docker.com/r/qmu1/selenium-webdriver-node/), I should be able to run tests simply with a docker command like this.

```<code>HERE=$(pwd)

echo ""
echo "----------------------------"
echo "Running an example"
echo "----------------------------"
echo ""

docker run -it --rm \
    -v $HERE:/workspace \
    qmu1/selenium-webdriver-node:latest /bin/sh -c "
        mocha sample.js --timeout=10000
"
</code>```

I changed this command to fit my needs until it seemed liked it worked.

```<code>docker run -it --rm --net=distributiontech_default -v $HERE:/workspace qmu1/selenium-webdriver-node:latest /bin/sh -c "mocha tests/seleniumtest.js --timeout=10000"
</code>```

I got the response:

```<code>all modules are ready!

  0 passing (1ms)
</code>```

Problem is... on Zalenium I didn't see anything happen on the viewer to verify it was even working?

My selenium script looks like below.

```<code>//Run using this project (https://github.com/qmu/dockerfiles/blob/master/src/selenium-webdriver-node/example/bin/run)

"use strict";

const webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until,
    test = require('selenium-webdriver/testing');

const expect = require('expect.js');
const assert = require('assert');

// var driver = new webdriver.Builder()
//    .withCapabilities(webdriver.Capabilities.chrome())
//    .usingServer('http://localhost:4444/wd/hub')
//    .build();

var driver = new webdriver.Builder()
    .forBrowser('firefox')
    .usingServer('http://zalenium:4444/wd/hub')
    .build();

driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('simple programmer');
driver.findElement(webdriver.By.name('btnG')).click();
//driver.quit();

console.log('all modules are ready!');
</code>```

I tried without the --net command and with... and no luck.  Just so you can see the network details and containers running.  You can see that zalenium is added to the distributiontech_default network.

How do I connect the docker container running the selenium code to the docker hub running Zalenium?

I tried changing this to...

```<code>var driver = new webdriver.Builder()
    .forBrowser('firefox')
    .usingServer('http://localhost:4444/wd/hub')
    .build();
</code>```

but no luck either.  I can put any fake address I want where it says localhost and it doesn't seem to throw any errors or anything either oddly enough.

答:
I had a similar issue and I found I could use the --link command so I could link a named Zalenium grid instance with the docker instance which executes my tests:

```<code>docker run --privileged --name stg-selenium-client --rm=true --link zalenium:hub hub.platformservices.io/sbg_core_automation/core-test-runner-with-maven-dependencies:0.12 <command to execute tests>
</code>```

Body:
Due to my circumstances for the current project I need to use 2 docker images together for selenium testing.

One is called Zalenium.  I have it up and working via the docker-compose demo.  Its basically like the selenium docker repo except that this can record video and show you live progress.

zalenium:
        image: "dosel/zalenium"
        container_name: zalenium
        hostname: zalenium
        tty: true
        volumes:
            - /Users/josephastrahan/seluser/videos:/home/seluser/videos
            - /var/run/docker.sock:/var/run/docker.sock
            - /usr/bin/docker:/usr/bin/docker
        ports:
            - 4444:4444
        command: >
          start --chromeContainers 1
                --firefoxContainers 1
                --maxDockerSeleniumContainers 8
                --screenWidth 800 --screenHeight 600
                --timeZone "Europe/Berlin"
                --videoRecordingEnabled true
                --sauceLabsEnabled false
                --browserStackEnabled false
                --testingBotEnabled false
                --startTunnel false
        environment:
          - HOST_UID
          - HOST_GID
          - SAUCE_USERNAME
          - SAUCE_ACCESS_KEY
          - BROWSER_STACK_USER
          - BROWSER_STACK_KEY
          - TESTINGBOT_KEY
          - TESTINGBOT_SECRET

The other image is a NodeJS server pre-installed with Mocha and the nodejs (npm package) of selenium-webdriver so that I can run the commands to trigger browser automation.  Details on this here (https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver) and here (https://hub.docker.com/r/qmu1/selenium-webdriver-node/)

You can see Zalenium running from docker compose just fine here.  I can see the time updating every second correctly so its definitely showing a live view.

According to the documentation for the other docker container I'm using which is here (https://hub.docker.com/r/qmu1/selenium-webdriver-node/), I should be able to run tests simply with a docker command like this.

HERE=$(pwd)

echo ""
echo "----------------------------"
echo "Running an example"
echo "----------------------------"
echo ""

docker run -it --rm \
    -v $HERE:/workspace \
    qmu1/selenium-webdriver-node:latest /bin/sh -c "
        mocha sample.js --timeout=10000
"

I changed this command to fit my needs until it seemed liked it worked.

docker run -it --rm --net=distributiontech_default -v $HERE:/workspace qmu1/selenium-webdriver-node:latest /bin/sh -c "mocha tests/seleniumtest.js --timeout=10000"

I got the response:

all modules are ready!

  0 passing (1ms)

Problem is... on Zalenium I didn't see anything happen on the viewer to verify it was even working?

My selenium script looks like below.

//Run using this project (https://github.com/qmu/dockerfiles/blob/master/src/selenium-webdriver-node/example/bin/run)

"use strict";

const webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until,
    test = require('selenium-webdriver/testing');

const expect = require('expect.js');
const assert = require('assert');

// var driver = new webdriver.Builder()
//    .withCapabilities(webdriver.Capabilities.chrome())
//    .usingServer('http://localhost:4444/wd/hub')
//    .build();

var driver = new webdriver.Builder()
    .forBrowser('firefox')
    .usingServer('http://zalenium:4444/wd/hub')
    .build();

driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('simple programmer');
driver.findElement(webdriver.By.name('btnG')).click();
//driver.quit();

console.log('all modules are ready!');

I tried without the --net command and with... and no luck.  Just so you can see the network details and containers running.  You can see that zalenium is added to the distributiontech_default network.

How do I connect the docker container running the selenium code to the docker hub running Zalenium?

I tried changing this to...

var driver = new webdriver.Builder()
    .forBrowser('firefox')
    .usingServer('http://localhost:4444/wd/hub')
    .build();

but no luck either.  I can put any fake address I want where it says localhost and it doesn't seem to throw any errors or anything either oddly enough.

Body:
I had a similar issue and I found I could use the --link command so I could link a named Zalenium grid instance with the docker instance which executes my tests:

docker run --privileged --name stg-selenium-client --rm=true --link zalenium:hub hub.platformservices.io/sbg_core_automation/core-test-runner-with-maven-dependencies:0.12 <command to execute tests>


问:
What's the best way to select multiple M:N relationships in SQL?
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

```<code>books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)
</code>```

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

答: I don't typically find it useful to get data back shaped this way. Multiple resultsets that I can relate to each other tend to be more useful. You won't have extraneous data in your resultset this way either (8 rows returned each with the same columns for the book).</p>

OwnerDisplayName: Ben Blank

Body:
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

LastEditorDisplayName: Ben Blank

OwnerDisplayName: Jim Petkus


问:
PHP Array sort by number of repeats
I have an array with non-unique values, I need the array to be unique and ordered by the number of times each value returns.

I have got to place where I have an array with every unique value and the number of times that this value repeated - problem is, I need the array ordered with the values when the most repeated is first and the lowest repeated at last. (used array_count_values)

The array has a lot of results to handle..

un-ordered array:

```<code>array(14) {
  [0]=>
  int(1)
  [1]=>
  int(3)
  [2]=>
  int(4)
  [3]=>
  int(2)
  [4]=>
  int(3)
  [5]=>
  int(4)
  [6]=>
  int(5)
  [7]=>
  int(1)
  [8]=>
  int(2)
  [9]=>
  int(3)
  [10]=>
  int(4)
  [11]=>
  int(1)
  [12]=>
  int(2)
  [13]=>
  int(3)
}
</code>```

Ordered array (value refers to repeats):

```<code>array(5) {
  [1]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(3)
  [2]=>
  int(3)
  [5]=>
  int(1)
}
</code>```

答: I am not sure of your problem, wouldn't just asort() fix the array_count_values() array?

Title: PHP Array sort by number of repeats

Body:
I have an array with non-unique values, I need the array to be unique and ordered by the number of times each value returns.

I have got to place where I have an array with every unique value and the number of times that this value repeated - problem is, I need the array ordered with the values when the most repeated is first and the lowest repeated at last. (used array_count_values)

The array has a lot of results to handle..

un-ordered array:

array(14) {
  [0]=>
  int(1)
  [1]=>
  int(3)
  [2]=>
  int(4)
  [3]=>
  int(2)
  [4]=>
  int(3)
  [5]=>
  int(4)
  [6]=>
  int(5)
  [7]=>
  int(1)
  [8]=>
  int(2)
  [9]=>
  int(3)
  [10]=>
  int(4)
  [11]=>
  int(1)
  [12]=>
  int(2)
  [13]=>
  int(3)
}

Ordered array (value refers to repeats):

array(5) {
  [1]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(3)
  [2]=>
  int(3)
  [5]=>
  int(1)
}


问:
Dropdown Menu is not overlapping Slick Gallery
I have jQuery Slick Gallery and inside it I have a Dropdown Menu. A button shows the currently selected entry and the menu entries are an unordered list which appear when the button is clicked.

The unordered list is hidden at the bottom edge but should appear above the dots. You can see the problem also on the image below:

An example what I try to do you can find here: http://jsfiddle.net/45cst6nq/

HTML

```<code><section class="slider">
  <div>
    <ul class="list">
      <li>Please select</li>
      <li>Point 1</li>
      <li>Point 2</li>
      <li>Point 3</li>
      <li>Point 4</li>
      <li>Point 5</li>
      <li>Point 6</li>
      <li>Point 7</li>
      <li>Point 8</li>
      <li>Point 9</li>
      <li>Point 10</li>
    </ul>
  </div>
  <div>slide2</div>
  <div>slide3</div>
  <div>slide4</div>
  <div>slide5</div>
  <div>slide6</div>
</section>
</code>```

CSS

```<code>$c1: #3a8999;
$c2: #e84a69;

.slider {
    width: auto;
    margin: 30px 50px 50px;
}

.slick-slide {
    background: $c1;
    color: white;
    padding: 40px 0;
    font-size: 30px;
    font-family: "Arial", "Helvetica";
    text-align: center;
}

.slick-prev:before,
.slick-next:before {
    color: black;
}

.slick-dots {
    bottom: -30px;
}

.slick-slide:nth-child(odd) {
     background: $c2;
}

.list {
  position: absolute;
  top: 0;
}
</code>```

JS

```<code>$(".slider").slick({
    autoplay: false,
    dots: true,
    responsive: [{
        breakpoint: 500,
        settings: {
            dots: false,
            arrows: false,
            infinite: false,
            slidesToShow: 2,
            slidesToScroll: 2
        }
    }]
});
</code>```

This is a simplyfied example to demonstrate the issue. The components I am showing on my customor project are a little bit more complex.

I already tried to fix this with changing z-index and overflows. It looks like it's working when I set overflow-x to visible but than the cloned slides also get visible. Using overflow-y: visible; doesn't work.
Why does only overflow-x: visible shows the list correctly overlapping, but overflow-y: visible; does not? For me this doesn't make sense.

Is there a possibility to solve the issue? I like the slick gallery in general and don't want to write my own for this case.

答:
The error is in the class slick.list. I added some colour to your Li elements to show it clearer. Add this and you will see them:

```<code>.list li {
  background-color: white;
  color: black;
  border-bottom: 2px solid black;
}
.slick-list {
  overflow: visible;
}
</code>```

Preview: http://jsfiddle.net/62sdgv5a/

Body:
I have jQuery Slick Gallery and inside it I have a Dropdown Menu. A button shows the currently selected entry and the menu entries are an unordered list which appear when the button is clicked.

The unordered list is hidden at the bottom edge but should appear above the dots. You can see the problem also on the image below:

An example what I try to do you can find here: http://jsfiddle.net/45cst6nq/

HTML

Please select

Point 1

Point 2

Point 3

Point 4

Point 5

Point 6

Point 7

Point 8

Point 9

Point 10

slide2

slide3

slide4

slide5

slide6

CSS

$c1: #3a8999;
$c2: #e84a69;

.slider {
    width: auto;
    margin: 30px 50px 50px;
}

.slick-slide {
    background: $c1;
    color: white;
    padding: 40px 0;
    font-size: 30px;
    font-family: "Arial", "Helvetica";
    text-align: center;
}

.slick-prev:before,
.slick-next:before {
    color: black;
}

.slick-dots {
    bottom: -30px;
}

.slick-slide:nth-child(odd) {
     background: $c2;
}

.list {
  position: absolute;
  top: 0;
}

JS

$(".slider").slick({
    autoplay: false,
    dots: true,
    responsive: [{
        breakpoint: 500,
        settings: {
            dots: false,
            arrows: false,
            infinite: false,
            slidesToShow: 2,
            slidesToScroll: 2
        }
    }]
});

This is a simplyfied example to demonstrate the issue. The components I am showing on my customor project are a little bit more complex.

I already tried to fix this with changing z-index and overflows. It looks like it's working when I set overflow-x to visible but than the cloned slides also get visible. Using overflow-y: visible; doesn't work.
Why does only overflow-x: visible shows the list correctly overlapping, but overflow-y: visible; does not? For me this doesn't make sense.

Is there a possibility to solve the issue? I like the slick gallery in general and don't want to write my own for this case.

Body:
The error is in the class slick.list. I added some colour to your Li elements to show it clearer. Add this and you will see them:

.list li {
  background-color: white;
  color: black;
  border-bottom: 2px solid black;
}
.slick-list {
  overflow: visible;
}

Preview: http://jsfiddle.net/62sdgv5a/


问:
Should I include adminlte in packages.json / composer.json file?
Should I include adminlte in packages.json / composer.json file?

Is there necessary to include it in my packages.json / composer.json for my FE library?

Or I just download the zip file add to my public/ folder will be easier?

Since I am using version control, I will easily find out the file changes.

Is anyone added to their packages.json / composer.json? What is the advantage?

Anyone mind to share their workflow. I found that everytime have new update. That will be challenged to update.

I think it is same goes to other Front End Framework.

答:
Forget everything. AdminLTE can be installed using multiple methods.
Try this:

Via npm

```<code>npm install admin-lte --save
</code>```

Via composer

```<code>composer require "almasaeed2010/adminlte=~2.4"
</code>```

Via composer

```<code>bower install admin-lte
</code>```

Body:
Forget everything. AdminLTE can be installed using multiple methods.
Try this:

Via npm

npm install admin-lte --save

Via composer

composer require "almasaeed2010/adminlte=~2.4"

Via composer

bower install admin-lte


问:
Unreasonable height of vertical swiper
I've created a vertical swiper inside a bootstrap 4 row and have applied height limits to the row. But the vertical swiper is going out of bounds.

Any help will be appreciated.

Thanks.

HTML:

```<code><div class="row">
  <div class="col-6 mh-50">
    <div class="v-swiper-container">
      <div class="swiper-wrapper">
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-1" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-2" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-3" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-4" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-5" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-6" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-7" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-8" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-9" /></div>
        <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-10" /></div>
      </div>
      <div class="swiper-pagination"></div>
    </div>
  </div>

  <div class="col-6 mh-50">
    <img src="//placehold.it/200x100?text=Col-2" />
  </div>
</div>
<div class="row">
  <img src="//placehold.it/500x100?text=Row-2" />

</div>
</code>```

CSS:

```<code>.mh-50 {
  max-height: 50vh;
}
</code>```

JS:

```<code>var vswiper = new Swiper('.v-swiper-container', {
  direction: 'vertical',
  speed: 2000,
  autoplay: {
    delay: 2000,
  },
  loop: true,
  pagination: {
    el: '.swiper-pagination',
    clickable: true,
  },
});
</code>```

JS Fiddle: https://jsfiddle.net/4ogo3vcg/4/

答:
The cause of your problem is that a child of an html tag does not get clipped automatically by the boundaries of it's parent. The example below models this phenomenon.

.box {
    box-sizing: border-box;
    width: 100px;
    height: 100px;
}

.clip {
    overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="float: left; margin: 20px;">
    <div class="box" style="background-color: red; padding: 20px;">
        <div class="box" style="background-color: green;"></div>
    </div>
</div>

<div style="float: left; margin: 20px;">
    <div class="box clip" style="background-color: red; padding: 20px;">
        <div class="box" style="background-color: green;"></div>
    </div>
</div></code>```

As you can also see from the example, that the solution is to use the overflow css property which specifies what to do when content is too large to fit in its block-level container.

In your case, the quickest fix would be to put overflow: hidden; into the .mh-50 class, however that would affect other parts of your project as well, so I would rather put that into a separate class.

Also, a couple of notes on other aspects of your markup:

According to Bootstrap Docs “in a grid layout, content must be placed within columns (.col) and only columns may be immediate children of rows (.row).”

Similarly, content should be placed into .container or .container-fluid tags. (This will remove horizontal scrollbar from your example.)

With that said, your code could look something like this:

var vswiper = new Swiper('.v-swiper-container', {
    direction: 'vertical',
    speed: 2000,
    autoplay: {
        delay: 2000,
    },
    loop: true,
    pagination: {
        el: '.swiper-pagination',
        clickable: true,
    },
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mh-50 {
    max-height: 50vh;
}

.clip {
    overflow: hidden;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.6/css/swiper.css" rel="stylesheet"/>
```

Title: Unreasonable height of vertical swiper

Body:
I've created a vertical swiper inside a bootstrap 4 row and have applied height limits to the row. But the vertical swiper is going out of bounds.

Any help will be appreciated.

Thanks.

HTML:

CSS:

.mh-50 {
  max-height: 50vh;
}

JS:

var vswiper = new Swiper('.v-swiper-container', {
  direction: 'vertical',
  speed: 2000,
  autoplay: {
    delay: 2000,
  },
  loop: true,
  pagination: {
    el: '.swiper-pagination',
    clickable: true,
  },
});

JS Fiddle: https://jsfiddle.net/4ogo3vcg/4/

Body:
The cause of your problem is that a child of an html tag does not get clipped automatically by the boundaries of it's parent. The example below models this phenomenon.

.box {
    box-sizing: border-box;
    width: 100px;
    height: 100px;
}

.clip {
    overflow: hidden;
}

<div style="float: left; margin: 20px;">
    <div class="box" style="background-color: red; padding: 20px;">
        <div class="box" style="background-color: green;"></div>
    </div>
</div>

<div style="float: left; margin: 20px;">
    <div class="box clip" style="background-color: red; padding: 20px;">
        <div class="box" style="background-color: green;"></div>
    </div>
</div>

As you can also see from the example, that the solution is to use the overflow css property which specifies what to do when content is too large to fit in its block-level container.

In your case, the quickest fix would be to put overflow: hidden; into the .mh-50 class, however that would affect other parts of your project as well, so I would rather put that into a separate class.

Also, a couple of notes on other aspects of your markup:

According to Bootstrap Docs “in a grid layout, content must be placed within columns (.col) and only columns may be immediate children of rows (.row).”

Similarly, content should be placed into .container or .container-fluid tags. (This will remove horizontal scrollbar from your example.)

With that said, your code could look something like this:

var vswiper = new Swiper('.v-swiper-container', {
    direction: 'vertical',
    speed: 2000,
    autoplay: {
        delay: 2000,
    },
    loop: true,
    pagination: {
        el: '.swiper-pagination',
        clickable: true,
    },
});

.mh-50 {
    max-height: 50vh;
}

.clip {
    overflow: hidden;
}

<div class="container-fluid">
    <div class="row">
        <div class="col-6 mh-50 clip">
            <div class="v-swiper-container">
                <div class="swiper-wrapper">
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-1" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-2" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-3" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-4" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-5" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-6" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-7" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-8" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-9" /></div>
                    <div class="swiper-slide"><img src="//placehold.it/100x100?text=Week-10" /></div>
                </div>

                <div class="swiper-pagination"></div>
            </div>
        </div>

        <div class="col-6 mh-50">
            <img class="img-fluid" src="//placehold.it/800x100?text=Col-2" />
        </div>
    </div>

    <div class="row">
        <div class="col">
            <img class="img-fluid" src="//placehold.it/1600x100?text=Row-2" />
        </div>
    </div>
</div>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.6/css/swiper.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.6/js/swiper.js"></script>


问:
CloseMainWindow not work in invoke-command
I want to stop a winform application on remote from local powershell script, but CloseMainWindow function seem not work

---This is local command to connect remote server to execute closeApp.ps1 which is stored on server--

```<code>$remoteSession = New-PSSession -computerName 'xxx' -credential $cred
Invoke-Command -session $remoteSession -command {F:\AutoDeployment\closeApp.ps1}
Remove-pSSession -session $remoteSession
</code>```

---This is main content of closeApp.ps1 which get active process and try to close it--

```<code>$app = Get-Process AppName -ErrorAction SilentlyContinue
if($app)
{
  $app.MainWindowTitle
  $app.CloseMainWindow()
}
</code>```

I expect it should be act as local did which shall close app properly.

But now it returns null for mainWindowTitle line and False for closeMainWindow.
This script works fine if directly run on server, but when it comes to be execute through invoke-command, MainWindow seem to be invalid and not work .

I'm calling this command through jenkins plugin powershell

Updates:

There's no error log through invoke-command for closeMainWindow but it always return 'False' which expected to be 'True'.

What's more I have a further step that will try to send key actions to make that app stop if closeMainWindow failed. I use [System.Windows.Forms.SendKeys]::SendWait to achieve that.
It also works in local but fails through invoke-command on server with log:

error log for sendkeys:

Exception calling "SendWait" with "1" argument(s): "Access is denied"
    + CategoryInfo          : NotSpecified: (Exception calli...cess is denied":String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

答:
I suspect that assemblies for Winforms are not loaded during a remote call and as a result you don't have the CloseMainWindow function available to you. Try to load the assemblies explicitly as in:

```<code>Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form
</code>```

Since you haven't supplied enough information about error codes, you can try the below to rule out an execution policy restriction by bypassing it for that run:

```<code>$remoteSession = New-PSSession -computerName 'xxx' -credential $cred

Invoke-Command -session $remoteSession -command {powershell.exe -execution Bypass -file 'F:\AutoDeployment\closeApp.ps1'}

Remove-pSSession -session $remoteSession
</code>```

Body:
I want to stop a winform application on remote from local powershell script, but CloseMainWindow function seem not work

---This is local command to connect remote server to execute closeApp.ps1 which is stored on server--

$remoteSession = New-PSSession -computerName 'xxx' -credential $cred
Invoke-Command -session $remoteSession -command {F:\AutoDeployment\closeApp.ps1}
Remove-pSSession -session $remoteSession

---This is main content of closeApp.ps1 which get active process and try to close it--

$app = Get-Process AppName -ErrorAction SilentlyContinue
if($app)
{
  $app.MainWindowTitle
  $app.CloseMainWindow()
}

I expect it should be act as local did which shall close app properly.

But now it returns null for mainWindowTitle line and False for closeMainWindow.
This script works fine if directly run on server, but when it comes to be execute through invoke-command, MainWindow seem to be invalid and not work .

I'm calling this command through jenkins plugin powershell

Updates:

There's no error log through invoke-command for closeMainWindow but it always return 'False' which expected to be 'True'.

What's more I have a further step that will try to send key actions to make that app stop if closeMainWindow failed. I use [System.Windows.Forms.SendKeys]::SendWait to achieve that.
It also works in local but fails through invoke-command on server with log:

error log for sendkeys:

Exception calling "SendWait" with "1" argument(s): "Access is denied"
    + CategoryInfo          : NotSpecified: (Exception calli...cess is denied":String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Body:
I suspect that assemblies for Winforms are not loaded during a remote call and as a result you don't have the CloseMainWindow function available to you. Try to load the assemblies explicitly as in:

Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form

Since you haven't supplied enough information about error codes, you can try the below to rule out an execution policy restriction by bypassing it for that run:

$remoteSession = New-PSSession -computerName 'xxx' -credential $cred

Invoke-Command -session $remoteSession -command {powershell.exe -execution Bypass -file 'F:\AutoDeployment\closeApp.ps1'}

Remove-pSSession -session $remoteSession


问:
Creating Classes and Outputting
I'm trying to create a person class, enter details and output the specific person class however at the moment i just have a bunch of variables and I'm outputting from the variables, not the class

```<code>class Person:

def __init__(self, _firstname, _surname, d, m, y):
    self._firstname = _firstname
    self._surname = _surname
    self.d = d
    self.m = m
    self.y = y

john = Person('John','Lennon','8','10','1940')
paul = Person('Paul','McCartney','7','7','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._day = '18'
paul._month = '6'
paul._year = '1943'

print('{} {} \n{} {} {}'.format(john._firstname,
john._surname, john.d, john.m, john.y))
</code>```

As you can see in the code I've simply made variables, assigned something to the variable, and printed the variable, I'm not sure how to use the class system correctly, any help would be great thank you

答:
I think you want to just print the class instance and receive a formatted output. For this you need to implement this method in the class:

```<code>def __repr__(self):
    return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)
</code>```

Then you can just print the class instance:

```<code>print(john)
</code>```

So this would be the complete code:

```<code>class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)

john = Person('John','Lennon','8','10','1940')
paul = Person('Paul','McCartney','7','7','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._day = '18'
paul._month = '6'
paul._year = '1943'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d,      john.m, john.y))
print(john)
</code>```

Title: Creating Classes and Outputting

Body:
I'm trying to create a person class, enter details and output the specific person class however at the moment i just have a bunch of variables and I'm outputting from the variables, not the class

class Person:

def __init__(self, _firstname, _surname, d, m, y):
    self._firstname = _firstname
    self._surname = _surname
    self.d = d
    self.m = m
    self.y = y

john = Person('John','Lennon','8','10','1940')
paul = Person('Paul','McCartney','7','7','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._day = '18'
paul._month = '6'
paul._year = '1943'

print('{} {} \n{} {} {}'.format(john._firstname,
john._surname, john.d, john.m, john.y))

As you can see in the code I've simply made variables, assigned something to the variable, and printed the variable, I'm not sure how to use the class system correctly, any help would be great thank you

Body:
I think you want to just print the class instance and receive a formatted output. For this you need to implement this method in the class:

def __repr__(self):
    return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)

Then you can just print the class instance:

print(john)

So this would be the complete code:

class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)

john = Person('John','Lennon','8','10','1940')
paul = Person('Paul','McCartney','7','7','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._day = '18'
paul._month = '6'
paul._year = '1943'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d,      john.m, john.y))
print(john)


问:
Too much recursion in Firefox when using custom elements
I am trying to create new custom elements.

I have a very simple html index file :

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="dist/webcomponents-lite.js"></script>
    </head>

    <body>

        <h1>WebComponents</h1>
        <hello-world></hello-world>

        <script src="src/components/hello-world.js"></script>
    </body>
</html>
</code>```

My hello-world component is as follows :

```<code>class HelloWorldElement extends HTMLElement {

    constructor(){
        super()

        this.innerHTML = `<h1>Hello Meetup !</h1>`;
    }

    connectedCallback(){
        console.log("I'm here!");
    }

    disconnectedCallback(){
        console.log("I'm gone!");
    }

}

    window.customElements.define(
                    'hello-world',
                     HelloWorldElement);
</code>```

This code snippet works perfectly fine in Chrome and Safari.

I have added the webcomponents-lite.js import to add support for other browsers.

However when trying to run the code in Firefox I get the following error:

```<code>too much recursion
[Learn More]
webcomponents-lite.js:93:170
</code>```

I have found very little info on the web as to what can be going on.

I think I am following the recommended path explained in the polyfills page from the web components website.

Any idea what is going on?

Thanks

EDIT:

I am able to get the custom element showing by enabling dom.webcomponents.customelements.enabled and dom.webcomponents.enabled in the firefox config and removing the polyfill, but that's obviously not something desired on production.

答:
Alright, it looks like I was missing another polyfill?

If I also import

```<code>    <script type="text/javascript" src="bower_components/custom-elements/custom-elements.min.js"></script>
</code>```

before the web-components-lite.js polyfill then I have no issues any more. I found the resource via google documentation

This is weird, as I thought that custom-elements was one of the subparts of the web-components polyfill itself...

Body:
I am trying to create new custom elements.

I have a very simple html index file :

<!DOCTYPE html>

        <meta charset="UTF-8">

WebComponents

        <hello-world></hello-world>

My hello-world component is as follows :

class HelloWorldElement extends HTMLElement {

    constructor(){
        super()

        this.innerHTML = `<h1>Hello Meetup !</h1>`;
    }

    connectedCallback(){
        console.log("I'm here!");
    }

    disconnectedCallback(){
        console.log("I'm gone!");
    }

}

    window.customElements.define(
                    'hello-world',
                     HelloWorldElement);

This code snippet works perfectly fine in Chrome and Safari.

I have added the webcomponents-lite.js import to add support for other browsers.

However when trying to run the code in Firefox I get the following error:

too much recursion
[Learn More]
webcomponents-lite.js:93:170

I have found very little info on the web as to what can be going on.

I think I am following the recommended path explained in the polyfills page from the web components website.

Any idea what is going on?

Thanks

EDIT:

I am able to get the custom element showing by enabling dom.webcomponents.customelements.enabled and dom.webcomponents.enabled in the firefox config and removing the polyfill, but that's obviously not something desired on production.

Body:
Alright, it looks like I was missing another polyfill?

If I also import

    <script type="text/javascript" src="bower_components/custom-elements/custom-elements.min.js"></script>

before the web-components-lite.js polyfill then I have no issues any more. I found the resource via google documentation

This is weird, as I thought that custom-elements was one of the subparts of the web-components polyfill itself...


问:
Java signing XML File - prevent standard XML signature namespace inside signature
I'm signing an XML File where I'm using the Java XML Digital Signature API, available from Java 6 up to now.

Web-Source: http://www.oracle.com/technetwork/articles/javase/dig-signature-api-140772.html

The Signature looks like following:

```<code><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">[...]</Signature>
</code>```

Now I want to know, is there any way, to sign the XML File, to prevent the API to determine this xmlns="http://www.w3.org/2000/09/xmldsig#"inside my tag, so that I just have following:

```<code><Signature>...</Signature>
</code>```

I'm very thankful for any clues.

Thank you @Vadim for your answer. Lets give more details for my problem. I got a XML Structure like:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<tests xmlns="schema1">
<test>
</test>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
</Signature>
</tests>
</code>```

How can I get this working? Because in a third party system I Need to check it against a Schema, where I define the structure of the signature by myself, so there should be like two xmlns inside my

答:
Per XML standard you have to have namespace defined for <Signature> element, so  it can be as you have it or outside on parent element with prefix. As

```<code> <rootElemnt xmlns:sig="http://....">
     <sig:Signature>....
</code>```

But, why it bother you? Without it <Signature> tag belongs to default namespace of parent element and not to proper Signature namespace.

UPDATED If you have two namespaces you have to have two xmlns declarations. One can be default second must have prefix. or both must have prefixes.

If your custom elements are in xmlns="schema1", I think you need to look either how to make <sig:Signature xmlns:sig="http://www.w3.org/2000/09/xmldsig#"> or

```<code><sch1:tests xmlns:sch1="schema1">
  <sch1:test>
  </sch1:test>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
     ...
     <sch1:customElement>...</sch1:customElement>
  </Signature>
</sch1:tests>
</code>```

It depends on how you build full XML. Sorry, I'do not know how to do that in Java XML Digital Signature API (never used it directly, just through WSDL policy), but all other tools have an ability to handle namespace prefixes

also it can look like:

```<code><tests xmlns="schema1">
  <test>
  </test>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
     ...
     <sch1:customElement xmlns:sch1="schema1">...</sch1:customElement>
  </Signature>
</tests>
</code>```

Perhaps it should look like that by defualt, but if not I guess if you marshal customElement into XML separately and then add it into Signature it must be like that.

Body:
I'm signing an XML File where I'm using the Java XML Digital Signature API, available from Java 6 up to now.

Web-Source: http://www.oracle.com/technetwork/articles/javase/dig-signature-api-140772.html

The Signature looks like following:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">[...]</Signature>

Now I want to know, is there any way, to sign the XML File, to prevent the API to determine this xmlns="http://www.w3.org/2000/09/xmldsig#"inside my tag, so that I just have following:

<Signature>...</Signature>

I'm very thankful for any clues.

Thank you @Vadim for your answer. Lets give more details for my problem. I got a XML Structure like:

<?xml version="1.0" encoding="UTF-8" ?>
<tests xmlns="schema1">
<test>
</test>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
</Signature>
</tests>

How can I get this working? Because in a third party system I Need to check it against a Schema, where I define the structure of the signature by myself, so there should be like two xmlns inside my

Body:
Per XML standard you have to have namespace defined for <Signature> element, so  it can be as you have it or outside on parent element with prefix. As

 <rootElemnt xmlns:sig="http://....">
     <sig:Signature>....

But, why it bother you? Without it <Signature> tag belongs to default namespace of parent element and not to proper Signature namespace.

UPDATED If you have two namespaces you have to have two xmlns declarations. One can be default second must have prefix. or both must have prefixes.

If your custom elements are in xmlns="schema1", I think you need to look either how to make <sig:Signature xmlns:sig="http://www.w3.org/2000/09/xmldsig#"> or

<sch1:tests xmlns:sch1="schema1">
  <sch1:test>
  </sch1:test>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
     ...
     <sch1:customElement>...</sch1:customElement>
  </Signature>
</sch1:tests>

It depends on how you build full XML. Sorry, I'do not know how to do that in Java XML Digital Signature API (never used it directly, just through WSDL policy), but all other tools have an ability to handle namespace prefixes

also it can look like:

<tests xmlns="schema1">
  <test>
  </test>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
     ...
     <sch1:customElement xmlns:sch1="schema1">...</sch1:customElement>
  </Signature>
</tests>

Perhaps it should look like that by defualt, but if not I guess if you marshal customElement into XML separately and then add it into Signature it must be like that.


问:
Selenium Webdriver C# - how can I remove this hard wait?
I am having a really hard time with the following issue. I am trying to navigate through some web pages that have various inputs (text boxes/dropdowns/buttons) followed by a continue button at the bottom to move onto the next screen. My tests frequently fall over because they can't always locate the first element in order to interact with it.

As far as I'm aware the page doesn't do any fancy AJAX post loading or anything, so once the page has loaded then Webdriver should be able to locate every element.

My code:

FRAMEWORK

```<code>public static void WaitOnPageForXPathClickable(string selector)
    {
        new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable((By.XPath(selector))));
    }
</code>```

TEST CASE

```<code>Utilities.WaitOnPageForXPathClickable("the xpath of the continue button and checks that it is clickable");
Driver.Instance.FindElement(By.XPath("the xpath of the first button that I want to click")).Click();
</code>```

Do I need to try and include a function to ensure that the page is fully loaded before test execution? I am confused about this because I have read that Selenium already waits for the page to load by default. I would have thought that waiting for one element (the continue button) to be clickable should mean that all other elements are ready by then too? I really want to avoid having to wait for every single element before clicking it.

答:
You have made things much more complicated by waiting for the Continue Button Utilities.WaitOnPageForXPathClickable("the xpath of the continue button and checks that it is clickable"); where as in the next step trying to click() on the First Button Driver.Instance.FindElement(By.XPath("the xpath of the first button that I want to click")).Click();

Test Scenario:

Ideally your Test Scenario should have been :

TEST CASE:

```<code>Utilities.WaitOnPageForXPathClickable("the xpath of the first button that I want to click");
Driver.Instance.FindElement(By.XPath("the xpath of the first button that I want to click")).Click();
</code>```

FRAMEWORK:

```<code>public static void WaitOnPageForXPathClickable(string selector)
{
    IWebElement element = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable((By.XPath(//label[@class='replaced-input-label replaced-input-label--radio']))));
    elementClick();
}
</code>```

Body:
I am having a really hard time with the following issue. I am trying to navigate through some web pages that have various inputs (text boxes/dropdowns/buttons) followed by a continue button at the bottom to move onto the next screen. My tests frequently fall over because they can't always locate the first element in order to interact with it.

As far as I'm aware the page doesn't do any fancy AJAX post loading or anything, so once the page has loaded then Webdriver should be able to locate every element.

My code:

FRAMEWORK

public static void WaitOnPageForXPathClickable(string selector)
    {
        new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable((By.XPath(selector))));
    }

TEST CASE

Utilities.WaitOnPageForXPathClickable("the xpath of the continue button and checks that it is clickable");
Driver.Instance.FindElement(By.XPath("the xpath of the first button that I want to click")).Click();

Do I need to try and include a function to ensure that the page is fully loaded before test execution? I am confused about this because I have read that Selenium already waits for the page to load by default. I would have thought that waiting for one element (the continue button) to be clickable should mean that all other elements are ready by then too? I really want to avoid having to wait for every single element before clicking it.

Body:
You have made things much more complicated by waiting for the Continue Button Utilities.WaitOnPageForXPathClickable("the xpath of the continue button and checks that it is clickable"); where as in the next step trying to click() on the First Button Driver.Instance.FindElement(By.XPath("the xpath of the first button that I want to click")).Click();

Test Scenario:

Ideally your Test Scenario should have been :

TEST CASE:

Utilities.WaitOnPageForXPathClickable("the xpath of the first button that I want to click");
Driver.Instance.FindElement(By.XPath("the xpath of the first button that I want to click")).Click();

FRAMEWORK:

public static void WaitOnPageForXPathClickable(string selector)
{
    IWebElement element = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable((By.XPath(//label[@class='replaced-input-label replaced-input-label--radio']))));
    elementClick();
}


问:
Getting error - "Encountered the symbol " " when expecting one of the following" while creating Job
I am getting below error while creating new job.

```<code>Error report -
ORA-06550: line 2, column 2:
PLS-00103: Encountered the symbol " " when expecting one of the following:

   ( begin case declare exit for goto if loop mod null pragma
   raise return select update while with <an identifier>
   <a double-quoted delimited-identifier> <a bind variable> <<
   continue close current delete fetch lock insert open rollback
   savepoint set sql execute commit forall merge pipe purge
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:
</code>```

This is the code that I am using for creating Job. Can you please help me in that.

```<code>BEGIN
  DBMS_SCHEDULER.create_job (
    job_name        => 'P_DELETE',
    job_type        => 'PLSQL_BLOCK',
    job_action      => 'BEGIN ADMIN.DELETE_REG; COMMIT; END;',
    start_date      => SYSTIMESTAMP,
    repeat_interval => 'FREQ=WEEKLY; BYDAY=FRI; BYHOUR=3; ',
    enabled         => TRUE);
END;
</code>```

Please help!

答:
PLS-00103: Encountered the symbol " " when expecting one of the following:

I think the problem is in your repeat_interval argument.

The ; is used to separate different period elements, with no semi-colon after the last element. However, your string ends '; ' which explains why Oracle hurls.

The solution would be to pass this instead:

```<code>repeat_interval => 'FREQ=WEEKLY; BYDAY=FRI; BYHOUR=3'
</code>```

Body:
I am getting below error while creating new job.

Error report -
ORA-06550: line 2, column 2:
PLS-00103: Encountered the symbol " " when expecting one of the following:

   ( begin case declare exit for goto if loop mod null pragma
   raise return select update while with <an identifier>
     <<
   continue close current delete fetch lock insert open rollback
   savepoint set sql execute commit forall merge pipe purge
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

This is the code that I am using for creating Job. Can you please help me in that.

BEGIN
  DBMS_SCHEDULER.create_job (
    job_name        => 'P_DELETE',
    job_type        => 'PLSQL_BLOCK',
    job_action      => 'BEGIN ADMIN.DELETE_REG; COMMIT; END;',
    start_date      => SYSTIMESTAMP,
    repeat_interval => 'FREQ=WEEKLY; BYDAY=FRI; BYHOUR=3; ',
    enabled         => TRUE);
END;

Please help!

Body:
PLS-00103: Encountered the symbol " " when expecting one of the following:

I think the problem is in your repeat_interval argument.

The ; is used to separate different period elements, with no semi-colon after the last element. However, your string ends '; ' which explains why Oracle hurls.

The solution would be to pass this instead:

repeat_interval => 'FREQ=WEEKLY; BYDAY=FRI; BYHOUR=3'


问:
Best practices to deal with the lack of inheritance in Go
I am about to start writing a new application and I was thinking about programming it in Go, which I have no experience with. As Go doesn't support inheritance how would I faithfully translate a domain like this into Go, while still being in accordance with the philosophy of Go?:

A person has 2 legs and 2 arms and can walk.

A musician is a person, has an instrument and can play it, has partitions and can read them. But nobody can be only a musician, as a musicien has and plays a specific instrument.

A violonist is a musician that has a violon and can play the violon

A pianist is a musician that has a piano and can play the piano.

When a violonist/pianist is walking in the streets, everybody only sees him as a person.

Maybe we could reformulate the domain like this to remove any 'is a' relationships so that it would be translatable into Go:

A violinist has a person part, a musician part, a violin and can play the violin

The musician part of a violinist/pianist has partitions and can read them

When a violinist/pianist is walking in the streets, everybody can only see his person part

Etc

Would it be the best practice to model such a domain like this before translating into Go? Is it the way of thinking that the authors of Go want their users to have, when they decided to exclude inheritance in Go?

答:
It's not "the way of thinking that the authors of Go want their users to have"; Go does not have inheritance because it is not an object-oriented language, in much the same way C doesn't have inheritance.

It does have composition and interfaces, which are all you need to model what you've described: an object that "has a" other object should have a field of that type (composition), and an object that "can" perform some action can be modeled by an interface.

This question might be easier to answer if it described an actual programming problem rather than a metaphor, however; unless, of course, your application intends to model the limbs and instruments of various kinds of musicians.


问:
Excel VBA - Weekday and/or datediff function not working properly
I have the code below which is supposed to parse a column with dates/times and advise (by highlighting) if the value is older than 24 hours ago as of 6:30am on the current day.  If the day is Monday, it is supposed to look back 72 hours (since Saturday and Sunday are not work days) and advise if the value is older than 72 hours as of 6:30am.

Something is amiss as it is not highlighting values that are breaching the 24 hours threshold, but I don't know what it is.

```<code>'Highlight breached tickets
Dim updateRange As Range, updateCell As Range
Set updateRange = Range("D2:D" & lastRow)
If Weekday(Date, vbMonday) Then
    For Each updateCell In updateRange
        If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > 72 Then
            updateCell.Interior.Color = 13311
            updateCell.Offset(0, -3).Interior.Color = 13311
        End If
    Next updateCell
Else
    For Each updateCell In updateRange
        If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > 24 Then
            updateCell.Interior.Color = 13311
            updateCell.Offset(0, -3).Interior.Color = 13311
        End If
    Next updateCell
End If
</code>```

答:
As others have said you need to test Weekday against something as it doesn't return a Boolean value. However, thought I'd add this as you could re-write your code so you don't repeat yourself as nearly all of it is doing exactly the same

```<code>'Highlight breached tickets
Dim updateRange As Range, updateCell As Range
Dim TimeDiff As Long
Set updateRange = Range("D2:D" & Lastrow)

TimeDiff = IIf(Weekday(Date, vbMonday) = 1, 72, 40)

For Each updateCell In updateRange
    If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > TimeDiff Then
        updateCell.Interior.Color = 13311
        updateCell.Offset(0, -3).Interior.Color = 13311
    End If
Next updateCell
</code>```

Writing it this way makes it much easier to maintain

Update after comments
To modify this to cope with other days as well, the simplest (and easiest to read) would be to change the TimeDiff = line and using a Select Case statement to set the value

```<code>'Highlight breached tickets
Dim updateRange As Range, updateCell As Range
Dim TimeDiff As Long
Set updateRange = Range("D2:D" & Lastrow)

Select Case Weekday(Date, vbMonday)
    ' Monday
    Case 1
        TimeDiff = 72
    ' Tuesday
    Case 2
        TimeDiff = 96
    ' Any other day
    Case Else
        TimeDiff = 40
End Select

For Each updateCell In updateRange
    If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > TimeDiff Then
        updateCell.Interior.Color = 13311
        updateCell.Offset(0, -3).Interior.Color = 13311
    End If
Next updateCell
</code>```

Body:
I have the code below which is supposed to parse a column with dates/times and advise (by highlighting) if the value is older than 24 hours ago as of 6:30am on the current day.  If the day is Monday, it is supposed to look back 72 hours (since Saturday and Sunday are not work days) and advise if the value is older than 72 hours as of 6:30am.

Something is amiss as it is not highlighting values that are breaching the 24 hours threshold, but I don't know what it is.

'Highlight breached tickets
Dim updateRange As Range, updateCell As Range
Set updateRange = Range("D2:D" & lastRow)
If Weekday(Date, vbMonday) Then
    For Each updateCell In updateRange
        If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > 72 Then
            updateCell.Interior.Color = 13311
            updateCell.Offset(0, -3).Interior.Color = 13311
        End If
    Next updateCell
Else
    For Each updateCell In updateRange
        If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > 24 Then
            updateCell.Interior.Color = 13311
            updateCell.Offset(0, -3).Interior.Color = 13311
        End If
    Next updateCell
End If

Body:
As others have said you need to test Weekday against something as it doesn't return a Boolean value. However, thought I'd add this as you could re-write your code so you don't repeat yourself as nearly all of it is doing exactly the same

'Highlight breached tickets
Dim updateRange As Range, updateCell As Range
Dim TimeDiff As Long
Set updateRange = Range("D2:D" & Lastrow)

TimeDiff = IIf(Weekday(Date, vbMonday) = 1, 72, 40)

For Each updateCell In updateRange
    If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > TimeDiff Then
        updateCell.Interior.Color = 13311
        updateCell.Offset(0, -3).Interior.Color = 13311
    End If
Next updateCell

Writing it this way makes it much easier to maintain

Update after comments
To modify this to cope with other days as well, the simplest (and easiest to read) would be to change the TimeDiff = line and using a Select Case statement to set the value

'Highlight breached tickets
Dim updateRange As Range, updateCell As Range
Dim TimeDiff As Long
Set updateRange = Range("D2:D" & Lastrow)

Select Case Weekday(Date, vbMonday)
    ' Monday
    Case 1
        TimeDiff = 72
    ' Tuesday
    Case 2
        TimeDiff = 96
    ' Any other day
    Case Else
        TimeDiff = 40
End Select

For Each updateCell In updateRange
    If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > TimeDiff Then
        updateCell.Interior.Color = 13311
        updateCell.Offset(0, -3).Interior.Color = 13311
    End If
Next updateCell