问:
Insert parent and children records
I have 2 tables a parent called emp_infoand a child called emp_attendance, which are connected by empid.

Currently, I am using 2 different sequences, one for each table to create the empid.  For the emp_attendance table I create a record which has null values than I do insert or update with random date time fields. Ses code below.

I would like to get rid of the sequence emp_attendance_seq and the MERGE code and do either nested inserts or use the empid from the emp_info table to populate the emp_attendance table.

Can you provide the workaround to my request.

Drop sequence emp_info_seq;
Drop table emp_info;
Drop sequence
    emp_attendance_seq;
Drop table emp_attendance;

```<code>Create sequence  emp_info_seq;

CREATE TABLE emp_info(
   empid INTEGER,
 empname VARCHAR2(50)
);

INSERT INTO  emp_info
SELECT emp_info_seq.NEXTVAL,
DBMS_RANDOM.string('U',
  DBMS_RANDOM.value(3,15))
FROM    dual
CONNECT BY  LEVEL  <=3;

Create sequence
emp_attendance_seq;

CREATE TABLE  emp_attendance
(empid INTEGER,
 start_date DATE,
 end_date DATE );

INSERT INTO  emp_attendance
(empid)
SELECT
emp_attendance_seq.NEXTVAL
FROM    dual
CONNECT BY  LEVEL  <= 3   ;

MERGE INTO  emp_attendance  dst
USING  (
           WITH    cntr (n)  AS
           (
               SELECT  LEVEL  AS n
               FROM    dual
               CONNECT BY  LEVEL <=5

       )
       ,    got_start_date (rid, empid, start_date)   AS
       (
           SELECT  CASE
                       WHEN  cntr.n  = 1
                       THEN  e.ROWID
                   END
    ,       e.empid
           ,       trunc(sysdate)
                       + dbms_random.value (1, 30)
           FROM    emp_attendance  e
           CROSS JOIN              cntr
           WHERE   e.start_date  IS NULL
       )
       SELECT  rid
       ,       empid
       ,       start_date
       ,       start_date + dbms_random.value (0, .75)  AS end_date
       FROM    got_start_date
   )  src
ON  (dst.ROWID  = src.rid)
WHEN MATCHED THEN UPDATE
    SET  dst.start_date = src.start_date
    ,    dst.end_date   = src.end_date
WHEN NOT MATCHED THEN.
INSERT (dst.empid, dst.start_date, dst.end_date)
       VALUES (src.empid,  src.start_date, src.end_date)
;
</code>```

/

```<code>EMPID    START_DATE     END_DATE
1    20200603 20:06:47    20200603 21:51:02
1    20200611 08:07:12    20200611 20:34:13
1    20200614 10:24:01    20200614 17:16:12
2    20200616 04:50:04    20200616 19:08:22
2    20200608 19:39:52    20200608 21:01:01
2    20200613 00:56:53    20200613 08:23:10
3    20200615 13:46:58    20200616 01:30:50
3    20200621 03:15:32    20200621 07:54:38
3    20200613 04:13:58    20200613 06:38:28
</code>```

答:
I already answered similiar question somewhere, but can't find it. My suggestion is to use insert all. Example below generates 3 rows in first table and 5 rows for each of them in child table:

```<code>insert all
  when rn = 1 then into emp_info (empid, empname) values (id, name)
  when  1 = 1 then into emp_attendance (empid, start_date, end_date)
                   values (id, d1, d1 + dbms_random.value (0, .75))
select ceil(level/5) id,
       case mod(level, 5) when 1 then 1 end rn,
       dbms_random.string('U', dbms_random.value(3, 15)) name,
       trunc(sysdate) + dbms_random.value (1, 30) d1
  from dual connect by level <= 3 * 5
</code>```

dbfiddle

Edit: I will try to explain best as I can, so step by step. This is our main query, which generates 15 rows containing random data:

```<code>select ceil(level/5) id,
       case mod(level, 5) when 1 then 1 end rn,
       dbms_random.string('U', dbms_random.value(3, 15)) name,
       trunc(sysdate) + dbms_random.value (1, 30) d1
  from dual connect by level <= 3 * 5
</code>```

ceil(level/5) changes id, so 1, 2, 3, 4, 5 becomes '1', values 6-10 becomes 10.

case mod(level, 5) when 1 then 1 end rn prepares value which decides if this row will be put to emp_info, only first row of each five is marked with 1

connect by level <= 3 * 5 is responsible for generating 15 rows

Next we have conditional insert all which allows us to put row into only first table or both tables:

```<code>insert all
  when rn = 1 then into emp_info (empid, empname) values (id, name)
  when  1 = 1 then into emp_attendance (empid, start_date, end_date)
                  values (id, d1, d1 + dbms_random.value (0, .75))
</code>```

I also added this part with max(id) + level to allow further uses of this insert. Please read about hierarchical queries and conditional insert, practice and everything will be clear.

Title: Insert parent and children records

Body:
I have 2 tables a parent called emp_infoand a child called emp_attendance, which are connected by empid.

Currently, I am using 2 different sequences, one for each table to create the empid.  For the emp_attendance table I create a record which has null values than I do insert or update with random date time fields. Ses code below.

I would like to get rid of the sequence emp_attendance_seq and the MERGE code and do either nested inserts or use the empid from the emp_info table to populate the emp_attendance table.

Can you provide the workaround to my request.

Drop sequence emp_info_seq;
Drop table emp_info;
Drop sequence
    emp_attendance_seq;
Drop table emp_attendance;

Create sequence  emp_info_seq;

CREATE TABLE emp_info(
   empid INTEGER,
 empname VARCHAR2(50)
);

INSERT INTO  emp_info
SELECT emp_info_seq.NEXTVAL,
DBMS_RANDOM.string('U',
  DBMS_RANDOM.value(3,15))
FROM    dual
CONNECT BY  LEVEL  <=3;

Create sequence
emp_attendance_seq;

CREATE TABLE  emp_attendance
(empid INTEGER,
 start_date DATE,
 end_date DATE );

INSERT INTO  emp_attendance
(empid)
SELECT
emp_attendance_seq.NEXTVAL
FROM    dual
CONNECT BY  LEVEL  <= 3   ;

MERGE INTO  emp_attendance  dst
USING  (
           WITH    cntr (n)  AS
           (
               SELECT  LEVEL  AS n
               FROM    dual
               CONNECT BY  LEVEL <=5

       )
       ,    got_start_date (rid, empid, start_date)   AS
       (
           SELECT  CASE
                       WHEN  cntr.n  = 1
                       THEN  e.ROWID
                   END
    ,       e.empid
           ,       trunc(sysdate)
                       + dbms_random.value (1, 30)
           FROM    emp_attendance  e
           CROSS JOIN              cntr
           WHERE   e.start_date  IS NULL
       )
       SELECT  rid
       ,       empid
       ,       start_date
       ,       start_date + dbms_random.value (0, .75)  AS end_date
       FROM    got_start_date
   )  src
ON  (dst.ROWID  = src.rid)
WHEN MATCHED THEN UPDATE
    SET  dst.start_date = src.start_date
    ,    dst.end_date   = src.end_date
WHEN NOT MATCHED THEN.
INSERT (dst.empid, dst.start_date, dst.end_date)
       VALUES (src.empid,  src.start_date, src.end_date)
;

/

EMPID    START_DATE     END_DATE
1    20200603 20:06:47    20200603 21:51:02
1    20200611 08:07:12    20200611 20:34:13
1    20200614 10:24:01    20200614 17:16:12
2    20200616 04:50:04    20200616 19:08:22
2    20200608 19:39:52    20200608 21:01:01
2    20200613 00:56:53    20200613 08:23:10
3    20200615 13:46:58    20200616 01:30:50
3    20200621 03:15:32    20200621 07:54:38
3    20200613 04:13:58    20200613 06:38:28

Body:
I already answered similiar question somewhere, but can't find it. My suggestion is to use insert all. Example below generates 3 rows in first table and 5 rows for each of them in child table:

insert all
  when rn = 1 then into emp_info (empid, empname) values (id, name)
  when  1 = 1 then into emp_attendance (empid, start_date, end_date)
                   values (id, d1, d1 + dbms_random.value (0, .75))
select ceil(level/5) id,
       case mod(level, 5) when 1 then 1 end rn,
       dbms_random.string('U', dbms_random.value(3, 15)) name,
       trunc(sysdate) + dbms_random.value (1, 30) d1
  from dual connect by level <= 3 * 5

dbfiddle

Edit: I will try to explain best as I can, so step by step. This is our main query, which generates 15 rows containing random data:

select ceil(level/5) id,
       case mod(level, 5) when 1 then 1 end rn,
       dbms_random.string('U', dbms_random.value(3, 15)) name,
       trunc(sysdate) + dbms_random.value (1, 30) d1
  from dual connect by level <= 3 * 5

ceil(level/5) changes id, so 1, 2, 3, 4, 5 becomes '1', values 6-10 becomes 10.

case mod(level, 5) when 1 then 1 end rn prepares value which decides if this row will be put to emp_info, only first row of each five is marked with 1

connect by level <= 3 * 5 is responsible for generating 15 rows

Next we have conditional insert all which allows us to put row into only first table or both tables:

insert all
  when rn = 1 then into emp_info (empid, empname) values (id, name)
  when  1 = 1 then into emp_attendance (empid, start_date, end_date)
                  values (id, d1, d1 + dbms_random.value (0, .75))

I also added this part with max(id) + level to allow further uses of this insert. Please read about hierarchical queries and conditional insert, practice and everything will be clear.


来源: stackexchange

问:
How to set Spring profile from system variable?
I have a Spring project which uses another project. Each project has its own spring profile initialize from java code using applicationContext.xml and *.properties for each profile. I inject the profile from args[]. The problem is that second project uses the default configuration for the env from the applicationContext.xml
I can not inject the env from args[] to the second project and I tried looking for an article which will explain how Spring profile works.

Is there a hierarchy on which it will look the profile when default is not configured at applicationContext.xml ?

Is System var stronger than applicationContext.xml configuration?

What you think is the best solution to my challenge?

Articles on that subject or even examples would be most appreciated.

答:
You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by
System.getProperty("spring.profiles.active")

For java files in test directory you can supply

SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

```<code>test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by
System.getProperty("spring.profiles.active")

For java files in test directory you can supply

SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}


问:
How to right click on a link and open the link in a new tab using Selenium through Java
I am trying to right click on the Forgotten account? link on the Facebook login page using Selenium but it is not working.

I am trying to send.Keys() after contextClick() but the key press is happening on the page and not on the context menu.

```<code>package keyboardandmouseaction;

import java.awt.AWTException;
import java.util.Iterator;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class testcase8 {
    public static void main(String[] args) throws AWTException, InterruptedException {

        System.out.println("Running keyboardandmouseactions > testcase8");

        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();

        driver.manage().window().maximize();
        driver.get("https://www.facebook.com/");

        WebElement link=driver.findElement(By.xpath("//a[contains(text(),\"Forgotten account?\")]"));
        Actions a=new Actions(driver);

        // defective code start
        Action builder=a.moveToElement(link).contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build();
        // defective code end
        builder.perform();

        Set<String> windowid =driver.getWindowHandles();
        Iterator<String> itr =windowid.iterator();

        String mainwindow=itr.next();
        String childwindow=itr.next();
        System.out.println("The mainwindow id is "+mainwindow);
        System.out.println("The childwindow id is "+childwindow);
        driver.switchTo().window(childwindow);
        driver.get("http://demo.automationtesting.in/Alerts.html");
        driver.close();

}
}
</code>```

答:
```<code>WebDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/");
WebElement link=driver.findElement(By.xpath("//a[contains(text(),\"Forgotten account?\")]"));
Actions actions = new Actions(driver);

actions.keyDown(Keys.LEFT_CONTROL)
        .click(element)
        .keyUp(Keys.LEFT_CONTROL)
        .build()
        .perform();

ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
</code>```

<p>}</p>

Body:
I am trying to right click on the Forgotten account? link on the Facebook login page using Selenium but it is not working.

I am trying to send.Keys() after contextClick() but the key press is happening on the page and not on the context menu.

package keyboardandmouseaction;

import java.awt.AWTException;
import java.util.Iterator;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class testcase8 {
    public static void main(String[] args) throws AWTException, InterruptedException {

        System.out.println("Running keyboardandmouseactions > testcase8");

        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();

        driver.manage().window().maximize();
        driver.get("https://www.facebook.com/");

        WebElement link=driver.findElement(By.xpath("//a[contains(text(),\"Forgotten account?\")]"));
        Actions a=new Actions(driver);

        // defective code start
        Action builder=a.moveToElement(link).contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build();
        // defective code end
        builder.perform();

        Set<String> windowid =driver.getWindowHandles();
        Iterator<String> itr =windowid.iterator();

        String mainwindow=itr.next();
        String childwindow=itr.next();
        System.out.println("The mainwindow id is "+mainwindow);
        System.out.println("The childwindow id is "+childwindow);
        driver.switchTo().window(childwindow);
        driver.get("http://demo.automationtesting.in/Alerts.html");
        driver.close();

}
}

Body:
WebDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/");
WebElement link=driver.findElement(By.xpath("//a[contains(text(),\"Forgotten account?\")]"));
Actions actions = new Actions(driver);

actions.keyDown(Keys.LEFT_CONTROL)
        .click(element)
        .keyUp(Keys.LEFT_CONTROL)
        .build()
        .perform();

ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));

}


问:
How to pass in the done() parameter on an async jest test.each case
I'm trying write a jest test case that tests an async method, I want to pass in the done() parameter so jest waits for it to be fired before it ends the test, however, I'm not sure where to put it.

Any ideas?

const testcases = [
        [
            'Crew',
            [1,2,3],
            Enum.Level1
        ],
        [
            'Staff',
            [4,5,6],
            Enum.Level2
        ]
    ];
test.each(testcases )(
        'Should be able to load differing cases %p',
        (
            typeName: string,
            initalVals: string[],
            type: LevelType
        ) => {
            // some call that updates mobx store state

            when(
                () => mobxstoreProperty.length == initalVals.length,
                () => {
                    // my assertions

                    done();
                }
            );
        }
    );
```
<p>For a single jest test I can do this:</p>
<pre class="lang-js prettyprint-override"><code>test('my single test', done => {
  // some call that updates mobx store state

     when(
       () => mobxstoreProperty.length == initalVals.length,
       () => {
         // my assertions
         done();
       }
    );
});
</code>```

Just unsure how to do it for when I use the test.each method.

答:
I use named parameters and I can add the done() method as the last function parameter. For example like so:

const testcases: {
    typeName: string;
    initalVals: string[],
    type: LevelType
}[] = [
    {
        typeName: 'Crew',
        initalVals: [1,2,3],
        type: Enum.Level1
    },
    {
        typeName: 'Staff',
        initalVals: [4,5,6],
        type: Enum.Level2
    },
];
test.each(testcases)(
    'Should be able to load differing cases %p',
    // Must use `any` for `done`, as TypeScript infers the wrong type:
    ({typeName, initalVals, type}, done: any) => {
        // some call that updates mobx store state
        when(
            () => mobxstoreProperty.length == initalVals.length,
            () => {
                // my assertions

                done();
            }
        );
    }
);
```

I haven't tested if you can just add the done() method as last parameters with array arguments, but maybe that works, too.

Body:
I'm trying write a jest test case that tests an async method, I want to pass in the done() parameter so jest waits for it to be fired before it ends the test, however, I'm not sure where to put it.

Any ideas?

const testcases = [
        [
            'Crew',
            [1,2,3],
            Enum.Level1
        ],
        [
            'Staff',
            [4,5,6],
            Enum.Level2
        ]
    ];
test.each(testcases )(
        'Should be able to load differing cases %p',
        (
            typeName: string,
            initalVals: string[],
            type: LevelType
        ) => {
            // some call that updates mobx store state

            when(
                () => mobxstoreProperty.length == initalVals.length,
                () => {
                    // my assertions

                    done();
                }
            );
        }
    );

For a single jest test I can do this:

test('my single test', done => {
  // some call that updates mobx store state

     when(
       () => mobxstoreProperty.length == initalVals.length,
       () => {
         // my assertions
         done();
       }
    );
});

Just unsure how to do it for when I use the test.each method.

Body:
I use named parameters and I can add the done() method as the last function parameter. For example like so:

const testcases: {
    typeName: string;
    initalVals: string[],
    type: LevelType
}[] = [
    {
        typeName: 'Crew',
        initalVals: [1,2,3],
        type: Enum.Level1
    },
    {
        typeName: 'Staff',
        initalVals: [4,5,6],
        type: Enum.Level2
    },
];
test.each(testcases)(
    'Should be able to load differing cases %p',
    // Must use `any` for `done`, as TypeScript infers the wrong type:
    ({typeName, initalVals, type}, done: any) => {
        // some call that updates mobx store state
        when(
            () => mobxstoreProperty.length == initalVals.length,
            () => {
                // my assertions

                done();
            }
        );
    }
);

I haven't tested if you can just add the done() method as last parameters with array arguments, but maybe that works, too.


问:
Use tcl twapi getting "Could not get ITypeInfo for coclass: object does not support IProvideClassInfo and clsid not specified." error ( office365)
I am using tcl8.5 and twapi 4.2a1 to control outlook via component object module
as following code

This Code can use in office 2016 outlook but in office365 outlook
I got error "Could not get ITypeInfo for coclass: object does not support IProvideClassInfo and clsid not specified" in "set biid [$::items -bind eventhandler]"

Could someone give me a idea to solve this problem?

or Am I missing something ?

package require twapi_com

proc eventhandler {args} {
    global ns
    set event  [lindex $args 0]
    set handle [lindex $args 1]
    puts $event
    puts $handle
    set s ""
    set sdr2 ""
    #return $s
}

set outlook [::twapi::objcom Outlook.Application -active]
set ns [$outlook GetNamespace "MAPI"]
set contacts [$ns GetDefaultFolder 6]
set ::items [$contacts Items]
set biid [$::items -bind eventhandler]
```

答:
It seems your windows registry keys are corrupted. I'd suggest repairing your Office installation.

Also, you may try to automate Outlook from another programming language to make sure the issue is not related to TCL.

See HRESULT:0x80040154 COM object with CLSID {} is either not valid or not registered for more information about the issue.


问:
arcs constraints for jobshop Scheduling
I have built a job shop scheduling algorithm using the ortools optimization library for python.
the problem is when i made a flexible jobshop model with setup times it doesn't work and i think  it is due to the arcs that i made, if there is anybody here who can explain more the circuit constraint, that would help me. By the way when i use a single machine it works.

Code:

```<code>from __future__ import print_function

import collections

from google.protobuf import text_format
from ortools.sat.python import cp_model

# Import Python wrapper for or-tools CP-SAT solver.
from ortools.sat.python import cp_model

# Intermediate solution printer
class SolutionPrinter(cp_model.CpSolverSolutionCallback):
    """Print intermediate solutions."""

    def __init__(self):
        cp_model.CpSolverSolutionCallback.__init__(self)
        self.__solution_count = 0

    def on_solution_callback(self):
        """Called after each new solution found."""
        print('Solution %i, time = %f s, objective = %i' %
              (self.__solution_count, self.WallTime(), self.ObjectiveValue()))
        self.__solution_count += 1

def MinimalJobshopSat():
    """Minimal jobshop problem."""
    # Create the model.
    model = cp_model.CpModel()

    jobs_data = [[(0, 2546), (1, 2000), (2, 1400)],
 [(0, 1289), (1, 2546), (2, 2546)],
 [(0, 2839), (1, 1576), (2, 1200)]
]

    setup_times = [
        [
        [3559, 1638, 2000],
        [1442, 3010, 1641],
        [1728, 3583, 3243]],
        [
        [3559, 1638, 2000],
        [1442, 3010, 1641],
        [1728, 3583, 3243]],
        [
        [3559, 1638, 2000],
        [1442, 3010, 1641],
        [1728, 3583, 3243]]
        ]

    all_jobs = range(len(jobs_data))

    machines_count = 1 + max(task[0] for job in jobs_data for task in job)
    all_machines = range(machines_count)

    for machine in all_machines:
        for job_id in all_jobs:
            min_incoming_setup = min(
                setup_times[machine][j][job_id] for j in all_jobs)
            if min_incoming_setup == 0:
                continue

            print('job %i at machine %i has a min incoming setup of %i' %
                  (job_id, machine, min_incoming_setup))
            # We can transfer some setup times to the duration of the job.
            jobs_data[job_id][machine] = (machine, jobs_data[job_id][machine][1] + min_incoming_setup)
            # Decrease corresponding incoming setup times.
            for j in all_jobs:
                setup_times[machine][j][job_id] -= min_incoming_setup

    # Computes horizon dynamically as the sum of all durations.
    horizon = sum(task[1] for job in jobs_data for task in job)

    for times in setup_times:
        for  time in times:
            horizon += max(time)

    # Named tuple to store information about created variables.
    task_type = collections.namedtuple('task_type', 'start end interval')
    # Named tuple to manipulate solution information.
    assigned_task_type = collections.namedtuple('assigned_task_type',
                                                'start job index duration')

    # Creates job intervals and add to the corresponding machine lists.
    all_tasks = {}
    machine_to_intervals = collections.defaultdict(list)
    starts = collections.defaultdict(list)
    ends = collections.defaultdict(list)

    for job_id, job in enumerate(jobs_data):
        for task_id, task in enumerate(job):
            machine = task[0]
            duration = task[1]
            suffix = '_%i_%i' % (job_id, task_id)
            start_var = model.NewIntVar(0, horizon, 'start' + suffix)
            end_var = model.NewIntVar(0, horizon, 'end' + suffix)
            interval_var = model.NewIntervalVar(start_var, duration, end_var,
                                                'interval' + suffix)
            all_tasks[job_id, task_id] = task_type(
                start=start_var, end=end_var, interval=interval_var)
            machine_to_intervals[machine].append(interval_var)
            starts[machine].append(start_var)
            ends[machine].append(end_var)

    # Create and add disjunctive constraints.
    for machine in all_machines:
        model.AddNoOverlap(machine_to_intervals[machine])
    #----------------------------------------------------------------------------
    # Transition times using a circuit constraint.
    list_arcs = []
    for machine in all_machines:
        arcs = []
        for i in all_jobs:
            # Initial arc from the dummy node (0) to a task.
            start_lit = model.NewBoolVar('')
            arcs.append([0, i + 1, start_lit])
            # If this task is the first, set to minimum starting time.
            min_start_time = min(0,setup_times[machine][0][i])
            model.Add(starts[machine][i] == min_start_time).OnlyEnforceIf(start_lit)
            # Final arc from an arc to the dummy node.
            arcs.append([i + 1, 0, model.NewBoolVar('')])

            for j in all_jobs:
                if i == j:
                    continue

                lit = model.NewBoolVar('%i_%i follows %i_%i' % (j, machine, i, machine))
                arcs.append([i + 1, j + 1, lit])

                # We add the reified precedence to link the literal with the times of the
                # two tasks.
                # If release_dates[j] == 0, we can strenghten this precedence into an
                # equality as we are minimizing the makespan.

                model.Add(starts[machine][j] >=
                          ends[machine][i] + setup_times[machine][i][j]).OnlyEnforceIf(lit)
        list_arcs.append(arcs)
        model.AddCircuit(arcs)

    #----------------------------------------------------------------------------

    # Precedences inside a job.
    for job_id, job in enumerate(jobs_data):
        for task_id in range(len(job) - 1):
            model.Add(all_tasks[job_id, task_id +
                                1].start >= all_tasks[job_id, task_id].end)

    # Makespan objective.
    obj_var = model.NewIntVar(0, horizon, 'makespan')
    model.AddMaxEquality(obj_var, [
        all_tasks[job_id, len(job) - 1].end
        for job_id, job in enumerate(jobs_data)
    ])
    model.Minimize(obj_var)

    # Solve model.
    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = 60
    status=solver.Solve(model)
    solver.parameters
    solution_printer = SolutionPrinter()
    solver.SolveWithSolutionCallback(model, solution_printer)
    print(solver.ResponseStats())

    if status == cp_model.FEASIBLE:
        # Create one list of assigned tasks per machine.
        assigned_jobs = collections.defaultdict(list)
        for job_id, job in enumerate(jobs_data):
            for task_id, task in enumerate(job):
                machine = task[0]
                assigned_jobs[machine].append(
                    assigned_task_type(
                        start=solver.Value(all_tasks[job_id, task_id].start),
                        job=job_id,
                        index=task_id,
                        duration=task[1]))

        # Create per machine output lines.
        output = ''
        for machine in all_machines:
            # Sort by starting time.
            assigned_jobs[machine].sort()
            sol_line_tasks = 'Machine ' + str(machine) + ': '
            sol_line = '           '

            for assigned_task in assigned_jobs[machine]:
                name = 'job_%i_%i' % (assigned_task.job, assigned_task.index)
                # Add spaces to output to align columns.
                sol_line_tasks += '%-10s' % name

                start = assigned_task.start
                duration = assigned_task.duration
                sol_tmp = '[%i,%i]' % (start, start + duration)
                # Add spaces to output to align columns.
                sol_line += '%-10s' % sol_tmp

            sol_line += '\n'
            sol_line_tasks += '\n'
            output += sol_line_tasks
            output += sol_line

        # Finally print the solution found.
        print('Optimal Schedule Length: %i' % solver.ObjectiveValue())
        print(output)
if __name__ == '__main__':
    MinimalJobshopSat()()
</code>```

答:
If a task is optional, you need to add a self looping arc on the node that corresponds to this arc.

So let's assume task_i with Boolean presence literal lit_i, you need to add

```<code>arcs.append([i + 1, i + 1, lit_i.Not()])
</code>```

Title: arcs constraints for jobshop Scheduling

Body:
I have built a job shop scheduling algorithm using the ortools optimization library for python.
the problem is when i made a flexible jobshop model with setup times it doesn't work and i think  it is due to the arcs that i made, if there is anybody here who can explain more the circuit constraint, that would help me. By the way when i use a single machine it works.

Code:

from __future__ import print_function

import collections

from google.protobuf import text_format
from ortools.sat.python import cp_model

# Import Python wrapper for or-tools CP-SAT solver.
from ortools.sat.python import cp_model

# Intermediate solution printer
class SolutionPrinter(cp_model.CpSolverSolutionCallback):
    """Print intermediate solutions."""

    def __init__(self):
        cp_model.CpSolverSolutionCallback.__init__(self)
        self.__solution_count = 0

    def on_solution_callback(self):
        """Called after each new solution found."""
        print('Solution %i, time = %f s, objective = %i' %
              (self.__solution_count, self.WallTime(), self.ObjectiveValue()))
        self.__solution_count += 1

def MinimalJobshopSat():
    """Minimal jobshop problem."""
    # Create the model.
    model = cp_model.CpModel()

    jobs_data = [[(0, 2546), (1, 2000), (2, 1400)],
 [(0, 1289), (1, 2546), (2, 2546)],
 [(0, 2839), (1, 1576), (2, 1200)]
]

    setup_times = [
        [
        [3559, 1638, 2000],
        [1442, 3010, 1641],
        [1728, 3583, 3243]],
        [
        [3559, 1638, 2000],
        [1442, 3010, 1641],
        [1728, 3583, 3243]],
        [
        [3559, 1638, 2000],
        [1442, 3010, 1641],
        [1728, 3583, 3243]]
        ]

    all_jobs = range(len(jobs_data))

    machines_count = 1 + max(task[0] for job in jobs_data for task in job)
    all_machines = range(machines_count)

    for machine in all_machines:
        for job_id in all_jobs:
            min_incoming_setup = min(
                setup_times[machine][j][job_id] for j in all_jobs)
            if min_incoming_setup == 0:
                continue

            print('job %i at machine %i has a min incoming setup of %i' %
                  (job_id, machine, min_incoming_setup))
            # We can transfer some setup times to the duration of the job.
            jobs_data[job_id][machine] = (machine, jobs_data[job_id][machine][1] + min_incoming_setup)
            # Decrease corresponding incoming setup times.
            for j in all_jobs:
                setup_times[machine][j][job_id] -= min_incoming_setup

    # Computes horizon dynamically as the sum of all durations.
    horizon = sum(task[1] for job in jobs_data for task in job)

    for times in setup_times:
        for  time in times:
            horizon += max(time)

    # Named tuple to store information about created variables.
    task_type = collections.namedtuple('task_type', 'start end interval')
    # Named tuple to manipulate solution information.
    assigned_task_type = collections.namedtuple('assigned_task_type',
                                                'start job index duration')

    # Creates job intervals and add to the corresponding machine lists.
    all_tasks = {}
    machine_to_intervals = collections.defaultdict(list)
    starts = collections.defaultdict(list)
    ends = collections.defaultdict(list)

    for job_id, job in enumerate(jobs_data):
        for task_id, task in enumerate(job):
            machine = task[0]
            duration = task[1]
            suffix = '_%i_%i' % (job_id, task_id)
            start_var = model.NewIntVar(0, horizon, 'start' + suffix)
            end_var = model.NewIntVar(0, horizon, 'end' + suffix)
            interval_var = model.NewIntervalVar(start_var, duration, end_var,
                                                'interval' + suffix)
            all_tasks[job_id, task_id] = task_type(
                start=start_var, end=end_var, interval=interval_var)
            machine_to_intervals[machine].append(interval_var)
            starts[machine].append(start_var)
            ends[machine].append(end_var)

    # Create and add disjunctive constraints.
    for machine in all_machines:
        model.AddNoOverlap(machine_to_intervals[machine])
    #----------------------------------------------------------------------------
    # Transition times using a circuit constraint.
    list_arcs = []
    for machine in all_machines:
        arcs = []
        for i in all_jobs:
            # Initial arc from the dummy node (0) to a task.
            start_lit = model.NewBoolVar('')
            arcs.append([0, i + 1, start_lit])
            # If this task is the first, set to minimum starting time.
            min_start_time = min(0,setup_times[machine][0][i])
            model.Add(starts[machine][i] == min_start_time).OnlyEnforceIf(start_lit)
            # Final arc from an arc to the dummy node.
            arcs.append([i + 1, 0, model.NewBoolVar('')])

            for j in all_jobs:
                if i == j:
                    continue

                lit = model.NewBoolVar('%i_%i follows %i_%i' % (j, machine, i, machine))
                arcs.append([i + 1, j + 1, lit])

                # We add the reified precedence to link the literal with the times of the
                # two tasks.
                # If release_dates[j] == 0, we can strenghten this precedence into an
                # equality as we are minimizing the makespan.

                model.Add(starts[machine][j] >=
                          ends[machine][i] + setup_times[machine][i][j]).OnlyEnforceIf(lit)
        list_arcs.append(arcs)
        model.AddCircuit(arcs)

    #----------------------------------------------------------------------------

    # Precedences inside a job.
    for job_id, job in enumerate(jobs_data):
        for task_id in range(len(job) - 1):
            model.Add(all_tasks[job_id, task_id +
                                1].start >= all_tasks[job_id, task_id].end)

    # Makespan objective.
    obj_var = model.NewIntVar(0, horizon, 'makespan')
    model.AddMaxEquality(obj_var, [
        all_tasks[job_id, len(job) - 1].end
        for job_id, job in enumerate(jobs_data)
    ])
    model.Minimize(obj_var)

    # Solve model.
    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = 60
    status=solver.Solve(model)
    solver.parameters
    solution_printer = SolutionPrinter()
    solver.SolveWithSolutionCallback(model, solution_printer)
    print(solver.ResponseStats())

    if status == cp_model.FEASIBLE:
        # Create one list of assigned tasks per machine.
        assigned_jobs = collections.defaultdict(list)
        for job_id, job in enumerate(jobs_data):
            for task_id, task in enumerate(job):
                machine = task[0]
                assigned_jobs[machine].append(
                    assigned_task_type(
                        start=solver.Value(all_tasks[job_id, task_id].start),
                        job=job_id,
                        index=task_id,
                        duration=task[1]))

        # Create per machine output lines.
        output = ''
        for machine in all_machines:
            # Sort by starting time.
            assigned_jobs[machine].sort()
            sol_line_tasks = 'Machine ' + str(machine) + ': '
            sol_line = '           '

            for assigned_task in assigned_jobs[machine]:
                name = 'job_%i_%i' % (assigned_task.job, assigned_task.index)
                # Add spaces to output to align columns.
                sol_line_tasks += '%-10s' % name

                start = assigned_task.start
                duration = assigned_task.duration
                sol_tmp = '[%i,%i]' % (start, start + duration)
                # Add spaces to output to align columns.
                sol_line += '%-10s' % sol_tmp

            sol_line += '\n'
            sol_line_tasks += '\n'
            output += sol_line_tasks
            output += sol_line

        # Finally print the solution found.
        print('Optimal Schedule Length: %i' % solver.ObjectiveValue())
        print(output)
if __name__ == '__main__':
    MinimalJobshopSat()()

Body:
If a task is optional, you need to add a self looping arc on the node that corresponds to this arc.

So let's assume task_i with Boolean presence literal lit_i, you need to add

arcs.append([i + 1, i + 1, lit_i.Not()])


问:
html send array inside form onsubmit
I'm wondering if it's possible to send array of values for javascript function via onsubmit inside the form.
Let's say I have five inputs in form, and in the form I have:

```<code>onsubmit="return checkvalues(value1, value2, value3, value4, value5)"
</code>```

So the checkvalues() function can validate the inputed values.
But I'm wondering how not to send 5 values but one array, so something like:

```<code>onsubmit="return checkvalues(array(value1, value2, value3, value4, value5))"
</code>```

is it possible so the Javascript function will recognize "someArray" as array?:

```<code>function checkvalues(array someArray) {
    somehow_loop_through_array someArray
}
</code>```

答:
You can check if the given param is an array and loop through it:

function checkvalues(someArray) {
  // check if someArray is an array (if its for sure an array you can skip this part of course)
  if(someArray.isArray()){
    // loop array ES5 way
    someArray.forEach(function (item, index) {
      // do the check for each item here
    });

    //loop array old way
    for (var i = 0; i < someArray.length; i++) {
      // do the check for each item here with someArray[i]
    }
  }
}```

I've added two possible ways. forEach is the "cleaner" version, but won't work on older browsers. So if you have to support old browsers, you have to use the second option

Title: html send array inside form onsubmit

Body:
I'm wondering if it's possible to send array of values for javascript function via onsubmit inside the form.
Let's say I have five inputs in form, and in the form I have:

onsubmit="return checkvalues(value1, value2, value3, value4, value5)"

So the checkvalues() function can validate the inputed values.
But I'm wondering how not to send 5 values but one array, so something like:

onsubmit="return checkvalues(array(value1, value2, value3, value4, value5))"

is it possible so the Javascript function will recognize "someArray" as array?:

function checkvalues(array someArray) {
    somehow_loop_through_array someArray
}

Body:
You can check if the given param is an array and loop through it:

function checkvalues(someArray) {
  // check if someArray is an array (if its for sure an array you can skip this part of course)
  if(someArray.isArray()){
    // loop array ES5 way
    someArray.forEach(function (item, index) {
      // do the check for each item here
    });

    //loop array old way
    for (var i = 0; i < someArray.length; i++) {
      // do the check for each item here with someArray[i]
    }
  }
}

I've added two possible ways. forEach is the "cleaner" version, but won't work on older browsers. So if you have to support old browsers, you have to use the second option


问:
Export RSA key pair with WebCrypto in Chromium
The following code works in Firefox 76.0.1:

```<code>"use strict"
let RSAKeys
(async () => {
  RSAKeys = await crypto.subtle.generateKey({
      name: "RSA-OAEP",
      modulusLength: 3072,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256"},
    true,
    ["wrapKey", "unwrapKey"])
  alert(JSON.stringify(Object.fromEntries(
    await Promise.all(Object.entries(RSAKeys).map(async ([k, v], i) =>
      [k, await cryptoBase64("exportKey", ["pkcs8", "spki"][i], v)])))))
})()

async function cryptoBase64(primitive, ...args) {
  return ArrayBufferToBase64(await crypto.subtle[primitive](...args))
}

function ArrayBufferToBase64(buf) {
  return btoa([...new Uint8Array(buf)].map(x => String.fromCharCode(x)).join(""))
}
</code>```

but in Chromium 80 I get:

Uncaught (in promise) DOMException: The key is not of the expected type

Whence the difference? Is it a bug in Chromium? And is there a workaround?

(Related to this question. After applying the solution I still had a problem and it turns out there's another discrepancy between browsers I'm running into.)

答:
Object.entries returns an array with the properties of the object as key-value pairs. The order of the key-value pairs is arbitrary, see Object.entries():

The Object.entries() method returns an array of a given object's own
  enumerable string-keyed property [key, value] pairs, in the same order
  as that provided by a for...in loop...

and for...in:

A for...in loop iterates over the properties of an object in an
  arbitrary order...

On the other hand, ["pkcs8", "spki"][i] assumes that the key order is private key (i = 0) followed by the public key (i = 1). In the Firfox browser the order matches coincidentally, in the Chromium browser not, which causes the exception.

The problem can be solved by sorting the array, e.g. using sort() and localeCompare(), see also the recommendation in Object.entries():

```<code>sort((key1, key2) => key1[0].localeCompare(key2[0]))
</code>```

Another approach would be to set the format (pkcs8, spki) depending on the key type (private, public) instead of sorting.

Your JavaScript code completed with one of the two approaches runs in both, the Firefox and the Chromium browsers:

"use strict"

let RSAKeys
(async () => {
  RSAKeys = await crypto.subtle.generateKey({
    name: "RSA-OAEP",
    modulusLength: 3072,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: "SHA-256"},
    true,
    ["wrapKey", "unwrapKey"])

  // Approach 1
  var result1 = JSON.stringify(Object.fromEntries(
    await Promise.all(Object.entries(RSAKeys)
      .sort((key1, key2) => key1[0].localeCompare(key2[0]))
        .map(async ([k, v], i) => [k, await cryptoBase64("exportKey", ["pkcs8", "spki"][i], v)]))))

  console.log(result1.replace(/(.{64})/g, "$1\n"));

  // Approach 2
  var result2 = JSON.stringify(Object.fromEntries(
    await Promise.all(Object.entries(RSAKeys)
      .map(async ([k, v], i) => [k, await cryptoBase64("exportKey", k == "privateKey" ? "pkcs8" : "spki", v)]))))

  console.log(result2.replace(/(.{64})/g, "$1\n"));

})()

async function cryptoBase64(primitive, ...args) {
  return ArrayBufferToBase64(await crypto.subtle[primitive](...args))
}

function ArrayBufferToBase64(buf) {
  return btoa([...new Uint8Array(buf)].map(x => String.fromCharCode(x)).join(""))
}```

Body:
The following code works in Firefox 76.0.1:

"use strict"
let RSAKeys
(async () => {
  RSAKeys = await crypto.subtle.generateKey({
      name: "RSA-OAEP",
      modulusLength: 3072,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256"},
    true,
    ["wrapKey", "unwrapKey"])
  alert(JSON.stringify(Object.fromEntries(
    await Promise.all(Object.entries(RSAKeys).map(async ([k, v], i) =>
      [k, await cryptoBase64("exportKey", ["pkcs8", "spki"][i], v)])))))
})()

async function cryptoBase64(primitive, ...args) {
  return ArrayBufferToBase64(await crypto.subtle[primitive](...args))
}

function ArrayBufferToBase64(buf) {
  return btoa([...new Uint8Array(buf)].map(x => String.fromCharCode(x)).join(""))
}

but in Chromium 80 I get:

Uncaught (in promise) DOMException: The key is not of the expected type

Whence the difference? Is it a bug in Chromium? And is there a workaround?

(Related to this question. After applying the solution I still had a problem and it turns out there's another discrepancy between browsers I'm running into.)

Body:
Object.entries returns an array with the properties of the object as key-value pairs. The order of the key-value pairs is arbitrary, see Object.entries():

The Object.entries() method returns an array of a given object's own
  enumerable string-keyed property [key, value] pairs, in the same order
  as that provided by a for...in loop...

and for...in:

A for...in loop iterates over the properties of an object in an
  arbitrary order...

On the other hand, ["pkcs8", "spki"][i] assumes that the key order is private key (i = 0) followed by the public key (i = 1). In the Firfox browser the order matches coincidentally, in the Chromium browser not, which causes the exception.

The problem can be solved by sorting the array, e.g. using sort() and localeCompare(), see also the recommendation in Object.entries():

sort((key1, key2) => key1[0].localeCompare(key2[0]))

Another approach would be to set the format (pkcs8, spki) depending on the key type (private, public) instead of sorting.

Your JavaScript code completed with one of the two approaches runs in both, the Firefox and the Chromium browsers:

"use strict"

let RSAKeys
(async () => {
  RSAKeys = await crypto.subtle.generateKey({
    name: "RSA-OAEP",
    modulusLength: 3072,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: "SHA-256"},
    true,
    ["wrapKey", "unwrapKey"])

  // Approach 1
  var result1 = JSON.stringify(Object.fromEntries(
    await Promise.all(Object.entries(RSAKeys)
      .sort((key1, key2) => key1[0].localeCompare(key2[0]))
        .map(async ([k, v], i) => [k, await cryptoBase64("exportKey", ["pkcs8", "spki"][i], v)]))))

  console.log(result1.replace(/(.{64})/g, "$1\n"));

  // Approach 2
  var result2 = JSON.stringify(Object.fromEntries(
    await Promise.all(Object.entries(RSAKeys)
      .map(async ([k, v], i) => [k, await cryptoBase64("exportKey", k == "privateKey" ? "pkcs8" : "spki", v)]))))

  console.log(result2.replace(/(.{64})/g, "$1\n"));

})()

async function cryptoBase64(primitive, ...args) {
  return ArrayBufferToBase64(await crypto.subtle[primitive](...args))
}

function ArrayBufferToBase64(buf) {
  return btoa([...new Uint8Array(buf)].map(x => String.fromCharCode(x)).join(""))
}


问:
How to expose my Elastic Search server to the internet?
I've done installed my ElasticSearch (ES) Server on a VPS Centos. I did test the ES inside the Server and it response correctly.

My next step, is to allow my website which is host on a different web host to access and index its data content into my ES server.

My question is, what is the recommended way of exposed the ES to the internet, so my website can access to it to perform index and search? Is there's authentication method that I need to install ?

答:
You need to include network.host:0.0.0.0 in your elasticsearch.yml file so that it listens on the non-loopback address and after that, if your app-server and ES are both in the same VPC, app-server will be able to connect to ES(provided if you exposed 9200 port in security group(in case of AWS).

And hopefully, your app-server port is exposed to the internet which internally connects to ES, you should not expose 9200 port of ES or Elasticsearch to the internet.

If you want an extra layer of security, you can enable x-pack basic which is included in the free tier and can be enabled using xpack.security.enabled: true in elasticsearch.config.

Refer x-pack features and configuration for more info.


问:
Is it possible to run a PHP function after each line of a PHP script is executed?
My question is similar to this: Is it possible to run code after each line in Ruby?
However I want to do it in PHP.

Is it possible and if so, how?

答:
You can register a tick handler:

Ticks

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.

As you can see, it's not exactly as "each line of code" unless you only write one tickable statement each line. But it's the closest you can get.

Example:

```<code>declare(ticks=1);
register_tick_function(function() {
    echo "tick_handler() called\n";
});

echo 'Line 1', PHP_EOL;
echo 'Line 2', PHP_EOL;
echo strtoupper('Line 3'), PHP_EOL;
</code>```

will output (demo):

```<code>tick_handler() called
Line 1
tick_handler() called
Line 2
tick_handler() called
LINE 3
tick_handler() called
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can register a tick handler:

Ticks

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.

As you can see, it's not exactly as "each line of code" unless you only write one tickable statement each line. But it's the closest you can get.

Example:

declare(ticks=1);
register_tick_function(function() {
    echo "tick_handler() called\n";
});

echo 'Line 1', PHP_EOL;
echo 'Line 2', PHP_EOL;
echo strtoupper('Line 3'), PHP_EOL;

will output (demo):

tick_handler() called
Line 1
tick_handler() called
Line 2
tick_handler() called
LINE 3
tick_handler() called


问:
How to get round value if value is in decimal in php?
```<code>$str = 6.87;
$x = ceil($str/5) * 5;
echo $x;
</code>```

I have a variable str and I want to covert str round value. In above I have 6.87 and I want 6.9 and if I have 6.43 then it should be 6.4 similarly if $str = 6.45 then it become 6.5. So, How can I do this? Please help me.

Thank You

答:
Use:

```<code>$str = 6.87;
echo round($str,1);
</code>```

where the first parameter is the variable, then the second is the decimal point to round.

this will output

6.9

Body:
$str = 6.87;
$x = ceil($str/5) * 5;
echo $x;

I have a variable str and I want to covert str round value. In above I have 6.87 and I want 6.9 and if I have 6.43 then it should be 6.4 similarly if $str = 6.45 then it become 6.5. So, How can I do this? Please help me.

Thank You

Body:
Use:

$str = 6.87;
echo round($str,1);

where the first parameter is the variable, then the second is the decimal point to round.

this will output

6.9


问:
List container images in Kubernetes cluster with SIZE (like docker image ls)
In the Kubernetes documentation List All Container Images Running in a Cluster we can list all containers by:

```<code>kubectl get pods --all-namespaces -o jsonpath="{..image}" |\
tr -s '[[:space:]]' '\n' |\
sort |\
uniq -c
</code>```

Here is an example of output:

```<code>  1 cdkbot/addon-resizer-amd64:1.8.1
  1 cdkbot/hostpath-provisioner-amd64:1.0.0
  1 cdkbot/registry-amd64:2.6
  1 coredns/coredns:1.6.6
  1 docker.io/cdkbot/addon-resizer-amd64:1.8.1
  1 docker.io/cdkbot/hostpath-provisioner-amd64:1.0.0
  1 docker.io/cdkbot/registry-amd64:2.6
  1 docker.io/coredns/coredns:1.6.6
  1 docker.io/grafana/grafana:6.4.3
  2 docker.io/istio/citadel:1.5.1
  2 docker.io/istio/examples-bookinfo-details-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-productpage-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-ratings-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v2:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v3:1.15.0
  2 docker.io/istio/galley:1.5.1
  4 docker.io/istio/kubectl:1.5.1
  4 docker.io/istio/mixer:1.5.1
  2 docker.io/istio/pilot:1.5.1
 34 docker.io/istio/proxyv2:1.5.1
  2 docker.io/istio/sidecar_injector:1.5.1
  2 docker.io/jaegertracing/all-in-one:1.16
  1 docker.io/kubernetesui/dashboard:v2.0.0
  1 docker.io/kubernetesui/metrics-scraper:v1.0.4
  2 docker.io/library/nginx:latest
  2 docker.io/prom/prometheus:v2.12.0
  1 docker.io/radial/busyboxplus:curl
  1 grafana/grafana:6.4.3
  2 k8s.gcr.io/metrics-server-amd64:v0.2.1
  1 kubernetesui/dashboard:v2.0.0
  1 kubernetesui/metrics-scraper:v1.0.4
  2 nginx
  2 quay.io/kiali/kiali:v1.9
  1 radial/busyboxplus:curl
</code>```

Unfortunately the size of the docker image is missing. Is there a way to get the container image size? Pretty much like docker image ls. Copy of the output from this example for convenience:

```<code>$ docker image ls
REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
docker.io/ubuntu            latest              3556258649b2        7 days ago          64.2 MB
docker.io/alpine            latest              b7b28af77ffe        2 weeks ago         5.58 MB
docker.io/centos            latest              9f38484d220f        4 months ago        202 MB
docker.io/hello-world       latest              fce289e99eb9        7 months ago        1.84 kB
</code>```

答:
Kubernetes doesn't provide image size information in its outputs. Even though we able to get a list of images running in a cluster, it is not a straight forward process to get the size of an image in a multi-node cluster. But in such cases where we run a single node cluster, we could achieve this by running a docker or DinD (Docker in Docker) container in Kubernetes cluster. Still, it is a good approach for testing purposes only. I have nothing to say about running this on critical environments. It depends.

Spin up a pod by mounting host's /var/lib/docker.sock file inside and exec as shown below.

```<code>apiVersion: v1
kind: Pod
metadata:
  labels:
    run: dind
  name: dind
spec:
  containers:
  - image: docker:dind
    name: dind
    command: ["cat"]
    tty: true
    resources: {}
    volumeMounts:
    - mountPath: /var/run/docker.sock
      name: docker
      readOnly: true
  volumes:
  - name: docker
    hostPath:
      path: /var/run/docker.sock
      type: File
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}
</code>```

```<code>$ kubectl exec -i dind -n dev sh -- docker images nginx
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              4571e56e27f0        11 hours ago        132MB

$kubectl exec -i dind -n dev sh -- docker image ls
REPOSITORY                                                       TAG                 IMAGE ID            CREATED             SIZE
nginx                                                            latest              4571e56e27f0        21 hours ago        132MB
</code>```

Body:
In the Kubernetes documentation List All Container Images Running in a Cluster we can list all containers by:

kubectl get pods --all-namespaces -o jsonpath="{..image}" |\
tr -s '[[:space:]]' '\n' |\
sort |\
uniq -c

Here is an example of output:

  1 cdkbot/addon-resizer-amd64:1.8.1
  1 cdkbot/hostpath-provisioner-amd64:1.0.0
  1 cdkbot/registry-amd64:2.6
  1 coredns/coredns:1.6.6
  1 docker.io/cdkbot/addon-resizer-amd64:1.8.1
  1 docker.io/cdkbot/hostpath-provisioner-amd64:1.0.0
  1 docker.io/cdkbot/registry-amd64:2.6
  1 docker.io/coredns/coredns:1.6.6
  1 docker.io/grafana/grafana:6.4.3
  2 docker.io/istio/citadel:1.5.1
  2 docker.io/istio/examples-bookinfo-details-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-productpage-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-ratings-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v2:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v3:1.15.0
  2 docker.io/istio/galley:1.5.1
  4 docker.io/istio/kubectl:1.5.1
  4 docker.io/istio/mixer:1.5.1
  2 docker.io/istio/pilot:1.5.1
 34 docker.io/istio/proxyv2:1.5.1
  2 docker.io/istio/sidecar_injector:1.5.1
  2 docker.io/jaegertracing/all-in-one:1.16
  1 docker.io/kubernetesui/dashboard:v2.0.0
  1 docker.io/kubernetesui/metrics-scraper:v1.0.4
  2 docker.io/library/nginx:latest
  2 docker.io/prom/prometheus:v2.12.0
  1 docker.io/radial/busyboxplus:curl
  1 grafana/grafana:6.4.3
  2 k8s.gcr.io/metrics-server-amd64:v0.2.1
  1 kubernetesui/dashboard:v2.0.0
  1 kubernetesui/metrics-scraper:v1.0.4
  2 nginx
  2 quay.io/kiali/kiali:v1.9
  1 radial/busyboxplus:curl

Unfortunately the size of the docker image is missing. Is there a way to get the container image size? Pretty much like docker image ls. Copy of the output from this example for convenience:

$ docker image ls
REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
docker.io/ubuntu            latest              3556258649b2        7 days ago          64.2 MB
docker.io/alpine            latest              b7b28af77ffe        2 weeks ago         5.58 MB
docker.io/centos            latest              9f38484d220f        4 months ago        202 MB
docker.io/hello-world       latest              fce289e99eb9        7 months ago        1.84 kB

Body:
Kubernetes doesn't provide image size information in its outputs. Even though we able to get a list of images running in a cluster, it is not a straight forward process to get the size of an image in a multi-node cluster. But in such cases where we run a single node cluster, we could achieve this by running a docker or DinD (Docker in Docker) container in Kubernetes cluster. Still, it is a good approach for testing purposes only. I have nothing to say about running this on critical environments. It depends.

Spin up a pod by mounting host's /var/lib/docker.sock file inside and exec as shown below.

apiVersion: v1
kind: Pod
metadata:
  labels:
    run: dind
  name: dind
spec:
  containers:
  - image: docker:dind
    name: dind
    command: ["cat"]
    tty: true
    resources: {}
    volumeMounts:
    - mountPath: /var/run/docker.sock
      name: docker
      readOnly: true
  volumes:
  - name: docker
    hostPath:
      path: /var/run/docker.sock
      type: File
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}

$ kubectl exec -i dind -n dev sh -- docker images nginx
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              4571e56e27f0        11 hours ago        132MB

$kubectl exec -i dind -n dev sh -- docker image ls
REPOSITORY                                                       TAG                 IMAGE ID            CREATED             SIZE
nginx                                                            latest              4571e56e27f0        21 hours ago        132MB


问:
Column name starts with numeric handling in Amazon Athena
I loaded json file in s3 location ,in which a key starts with numeric (3party_count).I created table in aws Athena on top of this location by using crawler n aws glue.so column names has be created named 3party_count
But I couldn't do select query using this column ?
Error -invalid request exception

Can anyone help me on this ?

答:
use double quotes

```<code>CREATE OR REPLACE VIEW "123view" AS
SELECT column_name1, column_name2
FROM "234table"
</code>```

Names for Tables, Databases, and Columns AWS Athena

Body:
use double quotes

CREATE OR REPLACE VIEW "123view" AS
SELECT column_name1, column_name2
FROM "234table"

Names for Tables, Databases, and Columns AWS Athena


问:
How to get matched array object based on their values in javascript
I would like to know how to get the array object based on values in javascript.
I have array object obj1, obj2 , how to get the object if name of obj1 matches with obj2 values in javascript

```<code>var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
var result = this.getMatchedObj(obj1, obj2);

function getMatchedObj(obj){
    const newlist = obj1.map((elem) => obj2.find(e=>Object.values(e)===elem.value));
    return newlist;
}

</code>```

Expected Output:

```<code>[
 {name: "country", value: "countries"}
]
</code>```

答:
   var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
let data = obj1.filter(ele=>obj2.findIndex(el=> Object.values(el)[0] ==ele.value)!=-1)
console.log(data);

 ```

Body:
I would like to know how to get the array object based on values in javascript.
I have array object obj1, obj2 , how to get the object if name of obj1 matches with obj2 values in javascript

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
var result = this.getMatchedObj(obj1, obj2);

function getMatchedObj(obj){
    const newlist = obj1.map((elem) => obj2.find(e=>Object.values(e)===elem.value));
    return newlist;
}

Expected Output:

[
 {name: "country", value: "countries"}
]


问:
RotateAnimation without duration
guys. i have this code (asyncTask)

my animation() function :

```<code>public void animation()
        {
        int   currentRotation = 0;
            anim = new RotateAnimation(currentRotation, (360*4),
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
            currentRotation = (currentRotation + 45) % 360;
            anim.setInterpolator(new LinearInterpolator());
            anim.setDuration(4000);// i want rotating without this <------------------
            anim.setFillEnabled(true);
            anim.setFillAfter(true);
            refresh.startAnimation(anim);
        }
</code>```

Can anyone tell me it's possible to do it without anim.setDuration ????
just only start .. and when  i pressed on button(for example) animation stoped.
Please help me.
 Regards, Peter.

final code :

```<code> public void animation()
            {
            int   currentRotation = 0;
                anim = new RotateAnimation(currentRotation, (360*4),
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
                currentRotation = (currentRotation + 45) % 360;
                anim.setInterpolator(new LinearInterpolator());
                anim.setDuration(4000);
               // anim.setRepeatMode(Animation.INFINITE);
                anim.setRepeatCount(Animation.INFINITE);
                anim.setFillEnabled(true);
                anim.setFillAfter(true);
                refresh.startAnimation(anim);
            }
</code>```

and somewhere   refresh.clearAnimation(); for stop animation
it's work perfect for me .. if here some thing wrong - please tell me .. Anyway thanks for the answers :)

答:
I think you should look at repeat mode. The duration is the time for one loop through the animation, if you set it up to repeat after that, then it can go on forever. See this and that.

For instance, you could use:

```<code>anim.setRepeatCount(Animation.INFINITE);
anim.setRepeatMode(Animation.RESTART);
</code>```

Title: RotateAnimation without duration

Body:
guys. i have this code (asyncTask)

my animation() function :

public void animation()
        {
        int   currentRotation = 0;
            anim = new RotateAnimation(currentRotation, (360*4),
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
            currentRotation = (currentRotation + 45) % 360;
            anim.setInterpolator(new LinearInterpolator());
            anim.setDuration(4000);// i want rotating without this <------------------
            anim.setFillEnabled(true);
            anim.setFillAfter(true);
            refresh.startAnimation(anim);
        }

Can anyone tell me it's possible to do it without anim.setDuration ????
just only start .. and when  i pressed on button(for example) animation stoped.
Please help me.
 Regards, Peter.

final code :

 public void animation()
            {
            int   currentRotation = 0;
                anim = new RotateAnimation(currentRotation, (360*4),
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
                currentRotation = (currentRotation + 45) % 360;
                anim.setInterpolator(new LinearInterpolator());
                anim.setDuration(4000);
               // anim.setRepeatMode(Animation.INFINITE);
                anim.setRepeatCount(Animation.INFINITE);
                anim.setFillEnabled(true);
                anim.setFillAfter(true);
                refresh.startAnimation(anim);
            }

and somewhere   refresh.clearAnimation(); for stop animation
it's work perfect for me .. if here some thing wrong - please tell me .. Anyway thanks for the answers :)

Body:
I think you should look at repeat mode. The duration is the time for one loop through the animation, if you set it up to repeat after that, then it can go on forever. See this and that.

For instance, you could use:

anim.setRepeatCount(Animation.INFINITE);
anim.setRepeatMode(Animation.RESTART);


问:
Do I need Thread Synchronization, when reading from a shared resource? (C)
Let's imagine I have a global array in my program, so all threads created can access it. Or let's imagine I pass it as an argument to every thread (same thing, because it's the reference to the array, so every thread will be accessing the very same array).

My question is:

If I create this array in the beggining of the program (when no threads have been created), and send it to every thread, where they'll only need to read from it, do I need Thread Synchronization?

I know there would be a problem with writing on the array, but no thread ever writes in the array. They only read it. It's like a constant.

答: if you read the global array you can access it from more thread at the same time and you don't need any kind of synchronization, this is the kind of event which you need to use the parallelism of architecture.</p>


问:
Sum a field only on specific conditions in Oracle SQL
I'm trying to get the amounts from a table where I want to sum some amounts that satisfies a specific condition while retaining the un-summed amount of others if it did not meet the condition.

I was trying this solution but it still doesn't sum up even if it meets the condition.

```<code>SELECT
  price_type,
  CASE trim(price_type)
    WHEN 'TYPE1' THEN sum(bill_amt)
    ELSE bill_amt
  END bill_amt
FROM (
  SELECT
    price_type,
    bill_amt
  FROM price_val_tbl
)
GROUP BY price_type, bill_amt
</code>```

Expected Output:

```<code>PRICE_TYPE   BILL_AMT
==========   ========
TYPE1        50
TYPE2        100
TYPE2        200
</code>```

Actual Output

```<code>PRICE_TYPE   BILL_AMT
==========   ========
TYPE1        100
TYPE1        -50
TYPE2        100
TYPE2        200
</code>```

答:
You can also use conditional GROUP BY as follows:

```<code>SQL> SELECT A, SUM(B)
  2  FROM YOUR_DATA
  3  GROUP BY A, ( CASE WHEN A = 'T1' THEN A ELSE TO_CHAR(ROWNUM) END);

A      SUM(B)
-- ----------
T2        100
T2        200
T1         50

SQL>
</code>```

Body:
I'm trying to get the amounts from a table where I want to sum some amounts that satisfies a specific condition while retaining the un-summed amount of others if it did not meet the condition.

I was trying this solution but it still doesn't sum up even if it meets the condition.

SELECT
  price_type,
  CASE trim(price_type)
    WHEN 'TYPE1' THEN sum(bill_amt)
    ELSE bill_amt
  END bill_amt
FROM (
  SELECT
    price_type,
    bill_amt
  FROM price_val_tbl
)
GROUP BY price_type, bill_amt

Expected Output:

PRICE_TYPE   BILL_AMT
==========   ========
TYPE1        50
TYPE2        100
TYPE2        200

Actual Output

PRICE_TYPE   BILL_AMT
==========   ========
TYPE1        100
TYPE1        -50
TYPE2        100
TYPE2        200

Body:
You can also use conditional GROUP BY as follows:

SQL> SELECT A, SUM(B)
  2  FROM YOUR_DATA
  3  GROUP BY A, ( CASE WHEN A = 'T1' THEN A ELSE TO_CHAR(ROWNUM) END);

A      SUM(B)
-- ----------
T2        100
T2        200
T1         50

SQL>


问:
Using script() inside input()
I am locating a textbox element inside shadow DOM using script(), and it works properly. Once I find the element, I want to enter a string into that box. I am trying to use input(), but since input() takes a locator and a value I am having issues using script() as a locator. Is this possible? I would appreciate any ideas or feedback on how to make this work.</p>

答:
Just use JavaScript (element.value) itself, it should be the simplest way:</p>

```<code>* script('.parent', "_.shadowRoot.querySelector('input').value = 'somevalue'")
</code>```

Title: Using script() inside input()

Body:
Just use JavaScript (element.value) itself, it should be the simplest way:

* script('.parent', "_.shadowRoot.querySelector('input').value = 'somevalue'")


问:
Angular 2 - Add text to the end of the fourth line of an html element
I currently have a problem with Angular 2, I am learning about technology and I am not an expert.

I am trying to add text to the last line of an Html div element to which I add the text of an object through the [innerHTML] = "object.description" tag. The text comes to me from an API request and when I pick it up it has Html tags which I must keep and for the text to show well.

```

<p>By means of CSS, I get only 4 lines to be displayed but the excess text remains in the div tag although it is not shown.</p>

<pre class="lang-css prettyprint-override"><code>.text {
    height: 104px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
    overflow: hidden;
    margin-bottom: 30px;
    font-style: normal;
    font-weight: normal;
    font-size: 22px;
    line-height: 27px;
    color: #333333;
}
</code>```

I need to know in some way to be able to identify how many lines it has and to be able to add "... Read more" at the end, which will be a link where I can redirect the user.

I want the "... Read more" to be added at the end of the fourth line and to be a link.

I have tried to do it with Html and CSS putting div on top but the responsive one is not going to do well.
I have also tried to get the element using typescript but I have not succeeded.

Thank you all.

答:
Add this pipe to your application :- </p>

```<code>import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({
  name: 'safeHtml'
})
export class SanitizeHtmlPipe implements PipeTransform {

 constructor(private _sanitizer:DomSanitizer) { }

 transform(v:string):SafeHtml {
   return this._sanitizer.bypassSecurityTrustHtml(v);
 }
}
</code>```

<p>You need to use safehtml pipe to keep those intact like i have done below :- </p>

```<code><div class="text" id="descripcion" [innerHTML]=" object.description|safeHtml">
</div>
</code>```

Body:
I currently have a problem with Angular 2, I am learning about technology and I am not an expert.

I am trying to add text to the last line of an Html div element to which I add the text of an object through the [innerHTML] = "object.description" tag. The text comes to me from an API request and when I pick it up it has Html tags which I must keep and for the text to show well.

By means of CSS, I get only 4 lines to be displayed but the excess text remains in the div tag although it is not shown.

.text {
    height: 104px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
    overflow: hidden;
    margin-bottom: 30px;
    font-style: normal;
    font-weight: normal;
    font-size: 22px;
    line-height: 27px;
    color: #333333;
}

I need to know in some way to be able to identify how many lines it has and to be able to add "... Read more" at the end, which will be a link where I can redirect the user.

I want the "... Read more" to be added at the end of the fourth line and to be a link.

I have tried to do it with Html and CSS putting div on top but the responsive one is not going to do well.
I have also tried to get the element using typescript but I have not succeeded.

Thank you all.

Body:
Add this pipe to your application :-

import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({
  name: 'safeHtml'
})
export class SanitizeHtmlPipe implements PipeTransform {

 constructor(private _sanitizer:DomSanitizer) { }

 transform(v:string):SafeHtml {
   return this._sanitizer.bypassSecurityTrustHtml(v);
 }
}

You need to use safehtml pipe to keep those intact like i have done below :-

<div class="text" id="descripcion" [innerHTML]=" object.description|safeHtml">
</div>


问:
Module not found: Can't resolve 'react-dom'
I have tried yarn add react react-dom but still facing these issues.If anyone can help me with this</p>

```<code>index.js:1437 D:/ecodocs-admin/node_modules/rc-align/es/Align.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-align\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-animate/es/AnimateChild.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-animate\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-time-picker/es/Select.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-time-picker\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-trigger/es/index.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-trigger\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-trigger/es/Popup.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-trigger\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-util/es/Portal.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-util\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-util/es/ContainerRender.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-util\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-util/es/Dom/addEventListener.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-util\es\Dom'
</code>```

答:
Use this to install react and react-dom:

```<code>yarn add react react-dom
</code>```

If this not work, you You have to fix the 'externals' configuration in webpack.config :

```<code>externals: {
   'react': 'react',
   'react-dom': 'react-dom'
}
</code>```

Body:
I have tried yarn add react react-dom but still facing these issues.If anyone can help me with this

index.js:1437 D:/ecodocs-admin/node_modules/rc-align/es/Align.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-align\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-animate/es/AnimateChild.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-animate\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-time-picker/es/Select.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-time-picker\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-trigger/es/index.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-trigger\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-trigger/es/Popup.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-trigger\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-util/es/Portal.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-util\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-util/es/ContainerRender.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-util\es'
console.<computed> @ index.js:1437
index.js:1437 D:/ecodocs-admin/node_modules/rc-util/es/Dom/addEventListener.js
Module not found: Can't resolve 'react-dom' in 'D:\ecodocs-admin\node_modules\rc-util\es\Dom'

Body:
Use this to install react and react-dom:

yarn add react react-dom

If this not work, you You have to fix the 'externals' configuration in webpack.config :

externals: {
   'react': 'react',
   'react-dom': 'react-dom'
}


问:
Problem with Git Repository in Xcode 4
In my iPhone app, I am using the in-built Git repository of Xcode 4 so that all the team members can work on the same project.

Now the problem is that even after I commit my changes to the repository, It still shows modified (M) symbol in front of the committed file.

What could be wrong?

I want to ensure that once I commit the changes it should not show "M" for that file.

Is there any setting which I have to do to make it work fine?

What can be done?

答: Did you stage your files before committing (git add)? Otherwise the commit will do nothing.

Title: Problem with Git Repository in Xcode 4


问:
Multiple select form tag for the same name getting the last option always
I have been trying to select the table number according to its location. My form is working and the record is added to the database however at the number section, the number that is inserting is "32" no matter what I choose, Even if I choose in the select "tnum3" a different number. I don't know what has happened.

The form

```<code><label for="tnum">table number
                        <select type="number" id="tnum1" name="num">
                            <?php for ($i = 2; $i <= 9; $i++) : ?>
                                <option id="in" value="<?php echo $i; ?>"><?php echo $i; ?></option>
                            <?php endfor; ?></select>
                        <select type="number" id="tnum2" name="num" style="display: none;">
                                <?php for ($i = 12; $i <= 23; $i++) : ?>
                                <option id="out" value="<?php echo $i; ?>"><?php echo $i; ?></option>
                            <?php endfor; ?></select>
                        <select type="number" id="tnum3" name="num" style="display: none;">
                                <?php for ($i = 32; $i <= 35; $i++) : ?>
                                <option id="tr" value="<?php echo $i; ?>"><?php echo $i; ?></option>
                            <?php endfor; ?>
                        </select></label><br>

                    <label for="loc">location
                        <select id="loc" name="location"  style="width:100%;" onchange="change_tnum(this.value)" required>
                            <option value="inside" >inside</option>
                            <option value="outside" >outside</option>
                            <option value="Porch" >Porch</option>
                    </select></label><br>
</code>```

This is the JS function that just toggles the select tags according to the location I choose:

```<code>function change_tnum(x){

    $('#tnum1').hide();
    $('#tnum2').hide();
    $('#tnum3').hide();// hide any options already shown
    switch (x) { // show whichever option is appropriate
      case 'inside':
        $('#tnum1').show();
        inside();
        break;
      case 'outside':
        $('#tnum2').show();
        outside();
        break;
      case 'porch':
        $('#tnum3').show();
        terrace();
        break;
      default:
        break;
    }
}
</code>```

答:
I don't see any issue with your select, however even if you set the element to display: none, it's value will still be submitted. Since there are multiple elements of the same name the last value overwrites the previous values.

If you want only one element value then you should add disabled attribute to it. The elements marked disabled are not sent to the server. Reference

So, your code changes to -

```<code>function change_tnum(x){

    $('#tnum1').hide();
    $('#tnum1').attr('disabled', true);

    $('#tnum2').hide();
    $('#tnum2').attr('disabled', true);

    $('#tnum3').hide();// hide any options already shown
    $('#tnum3').attr('disabled', true);

    switch (x) { // show whichever option is appropriate

        case 'inside':
            $('#tnum1').show();
            $('#tnum1').attr('disabled', false); // or simply remove disabled attribute
            inside();
            break;

        case 'outside':
            $('#tnum2').show();
            $('#tnum2').attr('disabled', false);
            outside();
            break;

        case 'porch':
            $('#tnum3').show();
            $('#tnum3').attr('disabled', false);
            terrace();
            break;

        default:
            // do something
    }
}
</code>```

Hope it helps you.

Body:
I have been trying to select the table number according to its location. My form is working and the record is added to the database however at the number section, the number that is inserting is "32" no matter what I choose, Even if I choose in the select "tnum3" a different number. I don't know what has happened.

The form

table number
                        <select type="number" id="tnum1" name="num">
                            <?php for ($i = 2; $i <= 9; $i++) : ?>
                                <option id="in" value="<?php echo $i; ?>"><?php echo $i; ?></option>
                            <?php endfor; ?></select>
                        <select type="number" id="tnum2" name="num" style="display: none;">
                                <?php for ($i = 12; $i <= 23; $i++) : ?>
                                <option id="out" value="<?php echo $i; ?>"><?php echo $i; ?></option>
                            <?php endfor; ?></select>
                        <select type="number" id="tnum3" name="num" style="display: none;">
                                <?php for ($i = 32; $i <= 35; $i++) : ?>
                                <option id="tr" value="<?php echo $i; ?>"><?php echo $i; ?></option>
                            <?php endfor; ?>
                        </select>

                    location
                        <select id="loc" name="location"  style="width:100%;" onchange="change_tnum(this.value)" required>
                            <option value="inside" >inside</option>
                            <option value="outside" >outside</option>
                            <option value="Porch" >Porch</option>
                    </select>

This is the JS function that just toggles the select tags according to the location I choose:

function change_tnum(x){

    $('#tnum1').hide();
    $('#tnum2').hide();
    $('#tnum3').hide();// hide any options already shown
    switch (x) { // show whichever option is appropriate
      case 'inside':
        $('#tnum1').show();
        inside();
        break;
      case 'outside':
        $('#tnum2').show();
        outside();
        break;
      case 'porch':
        $('#tnum3').show();
        terrace();
        break;
      default:
        break;
    }
}

Body:
I don't see any issue with your select, however even if you set the element to display: none, it's value will still be submitted. Since there are multiple elements of the same name the last value overwrites the previous values.

If you want only one element value then you should add disabled attribute to it. The elements marked disabled are not sent to the server. Reference

So, your code changes to -

function change_tnum(x){

    $('#tnum1').hide();
    $('#tnum1').attr('disabled', true);

    $('#tnum2').hide();
    $('#tnum2').attr('disabled', true);

    $('#tnum3').hide();// hide any options already shown
    $('#tnum3').attr('disabled', true);

    switch (x) { // show whichever option is appropriate

        case 'inside':
            $('#tnum1').show();
            $('#tnum1').attr('disabled', false); // or simply remove disabled attribute
            inside();
            break;

        case 'outside':
            $('#tnum2').show();
            $('#tnum2').attr('disabled', false);
            outside();
            break;

        case 'porch':
            $('#tnum3').show();
            $('#tnum3').attr('disabled', false);
            terrace();
            break;

        default:
            // do something
    }
}

Hope it helps you.


问:
Connect Excel to PostgreSQL via ODBC
I am trying to connect to a PostgreSQL database table from Excel via the PostgreSQL ODBC 32-bit driver.

In Excel, I go to Data>Get Data> From Other Sources> From ODBC. I navigate to the ODBC data source I set up, enter the credentials, and it clearly connects as the available tables appear. The preview fails and the query fails when I hit "Load" giving the error:

```<code>DataSource.Error: ODBC: ERROR [HY000] Error while executing the query
Details:
    DataSourceKind=Odbc
    DataSourcePath=dsn=PostgreSQL
    OdbcErrors=Table
</code>```

When I test the connection in ODBC admin it is successful. I have tried both the ANSI and Unicode drivers. TIBCO Spotfire connects to the ODBC datasource and pulls the data in just fine.

Any help you can provide would be greatly appreciated.

答:
You can skip this error by removing the navigate step and querying the information you need throw an SQL statement.

For example if you want to retry some information from LineItemExport the default query is something like this:

```<code>let
    Source = Odbc.DataSource("dsn=name", [HierarchicalNavigation=true]),
    quickbase_Database = Source{[Name="quickbase",Kind="Database"]}[Data],
    public_Schema = quickbase_Database{[Name="public",Kind="Schema"]}[Data],
    LineItemExport = public_Schema{[Name="LineItemExport",Kind="View"]}[Data]
in
    LineItemExport
</code>```

You have to change the source step in the query editor or change the code to something like this:

```<code>let
    Source = Odbc.Query("dsn=name", "select * from public.LineItemExport")
in
    Source
</code>```

This is the way you can came over the error, otherwise you should try to change your drivers version.

Title: Connect Excel to PostgreSQL via ODBC

Body:
I am trying to connect to a PostgreSQL database table from Excel via the PostgreSQL ODBC 32-bit driver.

In Excel, I go to Data>Get Data> From Other Sources> From ODBC. I navigate to the ODBC data source I set up, enter the credentials, and it clearly connects as the available tables appear. The preview fails and the query fails when I hit "Load" giving the error:

DataSource.Error: ODBC: ERROR [HY000] Error while executing the query
Details:
    DataSourceKind=Odbc
    DataSourcePath=dsn=PostgreSQL
    OdbcErrors=Table

When I test the connection in ODBC admin it is successful. I have tried both the ANSI and Unicode drivers. TIBCO Spotfire connects to the ODBC datasource and pulls the data in just fine.

Any help you can provide would be greatly appreciated.

Body:
You can skip this error by removing the navigate step and querying the information you need throw an SQL statement.

For example if you want to retry some information from LineItemExport the default query is something like this:

let
    Source = Odbc.DataSource("dsn=name", [HierarchicalNavigation=true]),
    quickbase_Database = Source{[Name="quickbase",Kind="Database"]}[Data],
    public_Schema = quickbase_Database{[Name="public",Kind="Schema"]}[Data],
    LineItemExport = public_Schema{[Name="LineItemExport",Kind="View"]}[Data]
in
    LineItemExport

You have to change the source step in the query editor or change the code to something like this:

let
    Source = Odbc.Query("dsn=name", "select * from public.LineItemExport")
in
    Source

This is the way you can came over the error, otherwise you should try to change your drivers version.


问:
XSL Move one level Element into other while last one is appearing
Given the input XML data:

```<code><Report_Entry>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Full" />
    </Time_Off_Type_Group>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Part" />
    </Time_Off_Type_Group>
    <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
    <Request_or_Correction>Time Off Request</Request_or_Correction>
</Report_Entry>
</code>```

As a result, I expect the output data via the condition: "for-each Time_Off_Type_Group move Time_Off_Entry_ID and Request_or_Correction into the Time_Off_Type_Group"

Output example:

```<code><Report_Entry>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Full" />
        <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
        <Request_or_Correction>Time Off Request</Request_or_Correction>
    </Time_Off_Type_Group>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Part" />
        <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
        <Request_or_Correction>Time Off Request</Request_or_Correction>
    </Time_Off_Type_Group>
</Report_Entry>
</code>```

答:
Think templates not for-each, so write a template for the Time_Off_Type_Group elements copying the siblings as children and make sure the default idendity copying does not apply to those siblings:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

  <xsl:output indent="yes"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Time_Off_Type_Group">
      <xsl:copy>
          <xsl:copy-of select="*, ../(* except Time_Off_Type_Group)"/>
      </xsl:copy>
  </xsl:template>

  <xsl:template match="Report_Entry/*[not(self::Time_Off_Type_Group)]"/>

</xsl:stylesheet>
</code>```

https://xsltfiddle.liberty-development.net/bEzkTcn

Body:
Given the input XML data:

<Report_Entry>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Full" />
    </Time_Off_Type_Group>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Part" />
    </Time_Off_Type_Group>
    <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
    <Request_or_Correction>Time Off Request</Request_or_Correction>
</Report_Entry>

As a result, I expect the output data via the condition: "for-each Time_Off_Type_Group move Time_Off_Entry_ID and Request_or_Correction into the Time_Off_Type_Group"

Output example:

<Report_Entry>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Full" />
        <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
        <Request_or_Correction>Time Off Request</Request_or_Correction>
    </Time_Off_Type_Group>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Part" />
        <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
        <Request_or_Correction>Time Off Request</Request_or_Correction>
    </Time_Off_Type_Group>
</Report_Entry>

Body:
Think templates not for-each, so write a template for the Time_Off_Type_Group elements copying the siblings as children and make sure the default idendity copying does not apply to those siblings:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

  <xsl:output indent="yes"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Time_Off_Type_Group">
      <xsl:copy>
          <xsl:copy-of select="*, ../(* except Time_Off_Type_Group)"/>
      </xsl:copy>
  </xsl:template>

  <xsl:template match="Report_Entry/*[not(self::Time_Off_Type_Group)]"/>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/bEzkTcn


问:
Remove X-Powered-By:express response header from Angular UI navigation URL
While navigating the application not getting the header x-powered-by in response headers and it is working as expected.

The problem is when a user refresh the page then the response header is getting appended with the x-powered-by header if we see in developer tools under network.

I want to remove the x-powered-by header from the response headers while navigating or browsing or refreshing to any url of application.

答:
You can remove it by disabling it: app.disable('x-powered-by');

Or you could use helmet: https://github.com/helmetjs/helmet#helmet


问:
Inside of MatterialApp. MediaQuery.of() called with a context that does not contain a MediaQuery
I'm trying to set a drawer size dynamically.

```<code>import 'package:flutter/material.dart';
import './screens/tab_screen.dart';

//widgets
import './widgets/main_drawer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: TabWidget(),
        endDrawer: Container(
          width: MediaQuery.of(context).size.width * 0.65,
          child: MainDrawer(),
        ),
      ),
      title: "Ali Azad",
      // routes: {
      //   '/': (_) => TabWidget(),
      // },
    );
  }
}
</code>```

but I have got this error = MediaQuery.of() called with a context that does not contain a MediaQuery.;

答: put your Container widget inside a Builder widget or create a separate widget an assign it to MaterialApp home parameter, this way you get the context of MaterialApp widget, the context you are now using doesn't have a MaterialApp.

Body:
I'm trying to set a drawer size dynamically.

import 'package:flutter/material.dart';
import './screens/tab_screen.dart';

//widgets
import './widgets/main_drawer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: TabWidget(),
        endDrawer: Container(
          width: MediaQuery.of(context).size.width * 0.65,
          child: MainDrawer(),
        ),
      ),
      title: "Ali Azad",
      // routes: {
      //   '/': (_) => TabWidget(),
      // },
    );
  }
}

but I have got this error = MediaQuery.of() called with a context that does not contain a MediaQuery.;


问:
C++ - where are the implementations of _List_node_base's member functions in the std::list headers
I'm perusing the source files of C++ STL in Ubuntu 14.04 x86. At the std::list::_M_insert which calls _M_hook of a _List_node_base object, I just can't find _M_hook's definition. I tried to grep the entire /usr/include and g++ -E to process a source file that included <list> but got nothing interesting.

Maybe the implementation has been embedded into some binary thing like a lib file, since struct _List_node_base (defined at /usr/include/c++/4.8/bits/stl_list.h:77) is not a template class. In fact not only _M_hook but also other members like _M_reverse, _M_transfer, I can't dig out their C++ sources either.

Wonder if I had missed something that contains the implementation. Or are they really precompiled into binary?

答:
They're defined in the list.cc file within libstdc++; it's in the src/c++98 subdirectory there.

You can view list.cc at the main github mirror here. The definition for _M_hook is (currently) on line 126 there; you can view it here.