问:
Update an attribute and remove duplicate element in an array from JavaScript
I've got a problem about some code.
Here's my array

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 1,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 2,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 1,
    numberHoursSpent: 3,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 4,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 3,
    numberHoursSpent: 5,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  }
  ]```
</div>
</div>
</p>

<p>The problem is I need to make my array looks like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: (1+2+4)/(1+1+1),
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: (3+5)/(1+3),
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]</code>```

which is equivalent to this

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: 2.33,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: 2,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]```
</div>
</div>
</p>

<p>First I find the same objects in array if they have the same "name" attributes.Then I sum all numberHoursSpent attributes and divide them by sum of numberSoldLodgings attributes from those objects.
Then I remove all the same elements, only keep an unique one.
P/S: The objects are the same if they have the same "name" attributes.
Here's what I've tried.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>handleData = arr => {
  var firstElementIndex =0;
  const final = []
  var filteredArray = []
  arr.map((e,i)=>{
    if(final.includes(e.name)){
      var k = k+arr[i].numberHoursSpent;
      firstElementIndex = final.indexOf(e.name);
      arr[firstElementIndex].numberHoursSpent +=  arr[i].numberHoursSpent
      filteredArray= arr.filter(item => item !== arr[i] )
    }
    else{
      final.push(e.name)
    }
    if(i == arr.length-1){
      arr[firstElementIndex].numberHoursSpent /= k
    }
  })

  return filteredArray;
}</code>```

Please help me, thanks.

答:
Try this one:

const qq = [
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 1,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 2,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 1,
    numberHoursSpent: 3,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 4,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 3,
    numberHoursSpent: 5,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  }
  ];

  let p = new Map();
  for (let q of qq) {
    let s = p.get(q.name)
    if(s) {
      s.numberSoldLodging += q.numberSoldLodging;
      s.numberHoursSpent += q.numberHoursSpent;
      p.set(q.name, s);
    } else {
      p.set(q.name, q);
    }

  }

const result = [];
p.forEach((val, key, map) => {
  val.numberHoursSpent = val.numberHoursSpent / val.numberSoldLodging;
  result.push(val)
});

console.log(result);```

Body:
I've got a problem about some code.
Here's my array

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 1,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 2,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 1,
    numberHoursSpent: 3,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 4,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 3,
    numberHoursSpent: 5,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  }
  ]

The problem is I need to make my array looks like this.

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: (1+2+4)/(1+1+1),
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: (3+5)/(1+3),
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]

which is equivalent to this

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: 2.33,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: 2,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]

First I find the same objects in array if they have the same "name" attributes.Then I sum all numberHoursSpent attributes and divide them by sum of numberSoldLodgings attributes from those objects.
Then I remove all the same elements, only keep an unique one.
P/S: The objects are the same if they have the same "name" attributes.
Here's what I've tried.

handleData = arr => {
  var firstElementIndex =0;
  const final = []
  var filteredArray = []
  arr.map((e,i)=>{
    if(final.includes(e.name)){
      var k = k+arr[i].numberHoursSpent;
      firstElementIndex = final.indexOf(e.name);
      arr[firstElementIndex].numberHoursSpent +=  arr[i].numberHoursSpent
      filteredArray= arr.filter(item => item !== arr[i] )
    }
    else{
      final.push(e.name)
    }
    if(i == arr.length-1){
      arr[firstElementIndex].numberHoursSpent /= k
    }
  })

  return filteredArray;
}

Please help me, thanks.


来源: stackexchange

问:
Offline Reverse Geocoding at Country Level
There seems to be much about this, but everyone seems to want street level data.

I'm writing an iOS app that needs to get the international dial code (outgoing) for the country you are in - so all I need is the country.  As this is mostly going to be used abroad, an online solution isn't really going to work!

Whist searching I discovered the fantastic openstreetmap.org, but their export feature seems only to provide street level - and won't do the whole world in one go!!

Once I have the data I might also need help with algorithms.... but thats for later!! :-)

Thanks

Ben.

答:
The MapKit MKReverseGeocoder class returns MKPlaceMark object(s) that have the following attributes:

```<code>addressDictionary
thoroughfare
subThoroughfare
locality
subLocality
administrativeArea
subAdministrativeArea
postalCode
country
countryCode
</code>```

You should be able to get what you need from that.  You'll need to make your own list of countryCodes with associated dialing codes.

ContentLicense: CC BY-SA 2.5

Body:
The MapKit MKReverseGeocoder class returns MKPlaceMark object(s) that have the following attributes:

addressDictionary
thoroughfare
subThoroughfare
locality
subLocality
administrativeArea
subAdministrativeArea
postalCode
country
countryCode

You should be able to get what you need from that.  You'll need to make your own list of countryCodes with associated dialing codes.

ContentLicense: CC BY-SA 3.0


问:
How to print first 5 rows of all the tables in an oracle database (schema)?
I want to open a database (schema) which holds about 100 tables,
Once it's opened I would like to print the top 5 rows of all the tables along with their column names.

My first step was to try and get the schema and table names in the database.
so this is what I used for that.

```<code>SELECT owner, table_name
  FROM all_tables
</code>```

The expected result will contain the table name, column names and top 5 rows of the table.

I am using Oracle SQL Developer ( Oracle database)

答:
Following is the code which you are looking for. I have used USER_TAB_COLUMNS view so that only tables owned by your schema in which you are executing the code is considered.

Feel free to format the output according to your need.

```<code>SET SERVEROUT ON

DECLARE
    LV_QUERY    VARCHAR2(32767);
    LV_RESULT   VARCHAR2(32767);
BEGIN
    DBMS_OUTPUT.PUT_LINE('---------------------------------------');
    DBMS_OUTPUT.PUT_LINE('---------------------------------------');
    FOR I IN (
        SELECT
            C.TABLE_NAME,
            LISTAGG(C.COLUMN_NAME, ' || ''****'' || ') WITHIN GROUP(
                ORDER BY
                    C.COLUMN_ID
            ) COLS
        FROM
            USER_TAB_COLUMNS C
        GROUP BY
            C.TABLE_NAME
        ORDER BY
            1
    ) LOOP
        LV_QUERY := 'SELECT '
                    || q'#RTRIM(XMLAGG(XMLELEMENT(E,VALS,CHR(10)).EXTRACT('//text()') ORDER BY 1).GetClobVal(),CHR(10)) FROM#'
                    || '(SELECT '
                    || I.COLS
                    || ' AS VALS FROM '
                    || I.TABLE_NAME
                    || ' FETCH FIRST 5 ROWS ONLY)';

        BEGIN
--    DBMS_OUTPUT.PUT_LINE(lv_query);
            EXECUTE IMMEDIATE LV_QUERY
            INTO LV_RESULT;
            DBMS_OUTPUT.PUT_LINE(CHR(10));
            DBMS_OUTPUT.PUT_LINE('TABLE NAME : ' || I.TABLE_NAME);
            DBMS_OUTPUT.PUT_LINE('COLUMN NAMES : '
                                 || REPLACE(REPLACE(REPLACE(I.COLS, '*', ''), '||', ''), '''', '**'));

            DBMS_OUTPUT.PUT_LINE(LV_RESULT);
        EXCEPTION
            WHEN NO_DATA_FOUND THEN
                DBMS_OUTPUT.PUT_LINE('NO DATA IN TABLE : ' || I.TABLE_NAME);
        END;

        DBMS_OUTPUT.PUT_LINE(CHR(10));
        DBMS_OUTPUT.PUT_LINE('---------------------------------------');
        DBMS_OUTPUT.PUT_LINE('---------------------------------------');
    END LOOP;

END;
</code>```

Hope this is what you are looking for.

ContentLicense: CC BY-SA 4.0

Body:
I want to open a database (schema) which holds about 100 tables,
Once it's opened I would like to print the top 5 rows of all the tables along with their column names.

My first step was to try and get the schema and table names in the database.
so this is what I used for that.

SELECT owner, table_name
  FROM all_tables

The expected result will contain the table name, column names and top 5 rows of the table.

I am using Oracle SQL Developer ( Oracle database)

Body:
Following is the code which you are looking for. I have used USER_TAB_COLUMNS view so that only tables owned by your schema in which you are executing the code is considered.

Feel free to format the output according to your need.

SET SERVEROUT ON

DECLARE
    LV_QUERY    VARCHAR2(32767);
    LV_RESULT   VARCHAR2(32767);
BEGIN
    DBMS_OUTPUT.PUT_LINE('---------------------------------------');
    DBMS_OUTPUT.PUT_LINE('---------------------------------------');
    FOR I IN (
        SELECT
            C.TABLE_NAME,
            LISTAGG(C.COLUMN_NAME, ' || ''****'' || ') WITHIN GROUP(
                ORDER BY
                    C.COLUMN_ID
            ) COLS
        FROM
            USER_TAB_COLUMNS C
        GROUP BY
            C.TABLE_NAME
        ORDER BY
            1
    ) LOOP
        LV_QUERY := 'SELECT '
                    || q'#RTRIM(XMLAGG(XMLELEMENT(E,VALS,CHR(10)).EXTRACT('//text()') ORDER BY 1).GetClobVal(),CHR(10)) FROM#'
                    || '(SELECT '
                    || I.COLS
                    || ' AS VALS FROM '
                    || I.TABLE_NAME
                    || ' FETCH FIRST 5 ROWS ONLY)';

        BEGIN
--    DBMS_OUTPUT.PUT_LINE(lv_query);
            EXECUTE IMMEDIATE LV_QUERY
            INTO LV_RESULT;
            DBMS_OUTPUT.PUT_LINE(CHR(10));
            DBMS_OUTPUT.PUT_LINE('TABLE NAME : ' || I.TABLE_NAME);
            DBMS_OUTPUT.PUT_LINE('COLUMN NAMES : '
                                 || REPLACE(REPLACE(REPLACE(I.COLS, '*', ''), '||', ''), '''', '**'));

            DBMS_OUTPUT.PUT_LINE(LV_RESULT);
        EXCEPTION
            WHEN NO_DATA_FOUND THEN
                DBMS_OUTPUT.PUT_LINE('NO DATA IN TABLE : ' || I.TABLE_NAME);
        END;

        DBMS_OUTPUT.PUT_LINE(CHR(10));
        DBMS_OUTPUT.PUT_LINE('---------------------------------------');
        DBMS_OUTPUT.PUT_LINE('---------------------------------------');
    END LOOP;

END;

Hope this is what you are looking for.


问:
Puppeteer - the tests do not perform any action
so, I'm using Puppeteer with Jest. After adding

```<code>    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
</code>```

My tests does not perform any actions. It doesn't matter if I'm using headless mode or let's call it "normal" mode. Anybody can help me?

homepage.test.js

```<code>const puppeteer = require('puppeteer');
const HomePage = require('./page_objects/HomePage');

const homePage = new HomePage();
describe('Homepage', () => {
  beforeAll(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto(homePage.path);
    await page.waitForSelector(homePage.loginPanel);
  });
  it('Log into your account', async () => {
    await homePage.fillLoginForm();
    await expect(page).toMatchElement(homePage.productList);
    await page.screenshot({ path: 'example.png' });
  });
</code>```

HomePage.js

```<code>module.exports = class HomePage {
  constructor() {
    this.path = 'https://www.saucedemo.com/index.html';
    this.loginPanel = '#login_button_container';
    this.productList = 'div[class="inventory_container"]';
    this.loginForm = {
      fields: {
        usernameInput: 'input[id="user-name"]',
        passwordInput: 'input[id="password"]',
        logInButton: 'input[class="btn_action"]',
      },
    };
  }

  async fillLoginForm() {
    await page.type(this.loginForm.fields.usernameInput, 'standard_user');
    await page.type(this.loginForm.fields.passwordInput, 'secret_sauce');
    await page.click(this.loginForm.fields.logInButton);
  }
};

</code>```

答:
The answer has two parts, one with normal jest and another with jest-puppeteer. You can skip to the jest-puppeteer if you want.

Problem (with jest):

The browser and page inside beforeAll block has no relation to the it blocks. It also does not have any relation with the page inside HomePage class as well.

You did not mention if you were using jest-puppeteer or not.

Solution:

Create block scoped variables for the describe block, and pass the page object to the modules.

Refining the HomePage class

Consider the following HomePage class.

```<code>// HomePage.js
class HomePage {
  constructor(page) {
    this.page = page;
  }

  async getScreenshot() {
    await this.page.screenshot({ path: "example.png" });
  }

  async getTitle(page) {
    return page.title();
  }
}
</code>```

As you can see, there are two ways to access to the page inside the class. Either pass inside the constructor, or use with the method directly.

The method getScreenshot has a this.page, while getTitle has access to a page.

Refining the test

You cannot use this inside the jest tests due to this issue, but you can declare a variable on top of a block, then access it later.

```<code>describe("Example", () => {
  // define them up here inside the parent block
  let browser;
  let page;
  let homepage;

  beforeAll(async () => {
    // it has access to the browser, page and homepage
    browser = await puppeteer.launch({ headless: true });
    page = await browser.newPage();
    homepage = new HomePage(page); // <-- pass the page to HomePage here

    await page.goto("http://example.com");
    await page.waitForSelector("h1");
    return true;
  });
});
</code>```

Now all other blocks can access to the page. According to our previous example HomePage class, we can do either of following depending on how we defined the methods.

```<code>it("Gets the screenshot", async () => {
    await homepage.getScreenshot(); // <-- will use this.page
  });
it("Gets the title", async () => {
    await homepage.getTitle(page); // <-- will use the page we are passing on
});
</code>```

Finally we cleanup the tests,

```<code>afterAll(async () => {
    await page.close();
    await browser.close();
    return true;
});
</code>```

We probably need to run the jest tests with detectOpenHandles for headfull mode.

```<code>jest . --detectOpenHandles
</code>```

Result:

Problem (with jest-puppeteer):

jest-puppeteer already gives you a global browser and page object. You do not need define anything.

However if you want to use jest-puppeteer and expect-puppeteer, you have to use a custom config file.

Solution:

Create a jest-config.json file and put the contents,

```<code>{
  "preset": "jest-puppeteer",
  "setupFilesAfterEnv": ["expect-puppeteer"]
}
</code>```

Now, get rid of browser and page creation code, as well as any afterAll hooks for page.close as well.

Here is a working test file,

```<code>class HomePage {
  async getTitle() {
    return page.$("h1");
  }
}

describe("Example", () => {
  const homepage = new HomePage();
  beforeAll(async () => {
    // it has access to a global browser, page and scoped homepage

    await page.goto("http://example.com");
    await page.waitForSelector("h1");
  });
  it("Gets the screenshot", async () => {
    const element = await homepage.getTitle();
    await expect(element).toMatch("Example");
  });
});
</code>```

And let's run this,

```<code>jest . --detectOpenHandles --config jest-config.json
</code>```

Result:

Body:
so, I'm using Puppeteer with Jest. After adding

    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();

My tests does not perform any actions. It doesn't matter if I'm using headless mode or let's call it "normal" mode. Anybody can help me?

homepage.test.js

const puppeteer = require('puppeteer');
const HomePage = require('./page_objects/HomePage');

const homePage = new HomePage();
describe('Homepage', () => {
  beforeAll(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto(homePage.path);
    await page.waitForSelector(homePage.loginPanel);
  });
  it('Log into your account', async () => {
    await homePage.fillLoginForm();
    await expect(page).toMatchElement(homePage.productList);
    await page.screenshot({ path: 'example.png' });
  });

HomePage.js

module.exports = class HomePage {
  constructor() {
    this.path = 'https://www.saucedemo.com/index.html';
    this.loginPanel = '#login_button_container';
    this.productList = 'div[class="inventory_container"]';
    this.loginForm = {
      fields: {
        usernameInput: 'input[id="user-name"]',
        passwordInput: 'input[id="password"]',
        logInButton: 'input[class="btn_action"]',
      },
    };
  }

  async fillLoginForm() {
    await page.type(this.loginForm.fields.usernameInput, 'standard_user');
    await page.type(this.loginForm.fields.passwordInput, 'secret_sauce');
    await page.click(this.loginForm.fields.logInButton);
  }
};

Body:
The answer has two parts, one with normal jest and another with jest-puppeteer. You can skip to the jest-puppeteer if you want.

Problem (with jest):

The browser and page inside beforeAll block has no relation to the it blocks. It also does not have any relation with the page inside HomePage class as well.

You did not mention if you were using jest-puppeteer or not.

Solution:

Create block scoped variables for the describe block, and pass the page object to the modules.

Refining the HomePage class

Consider the following HomePage class.

// HomePage.js
class HomePage {
  constructor(page) {
    this.page = page;
  }

  async getScreenshot() {
    await this.page.screenshot({ path: "example.png" });
  }

  async getTitle(page) {
    return page.title();
  }
}

As you can see, there are two ways to access to the page inside the class. Either pass inside the constructor, or use with the method directly.

The method getScreenshot has a this.page, while getTitle has access to a page.

Refining the test

You cannot use this inside the jest tests due to this issue, but you can declare a variable on top of a block, then access it later.

describe("Example", () => {
  // define them up here inside the parent block
  let browser;
  let page;
  let homepage;

  beforeAll(async () => {
    // it has access to the browser, page and homepage
    browser = await puppeteer.launch({ headless: true });
    page = await browser.newPage();
    homepage = new HomePage(page); // <-- pass the page to HomePage here

    await page.goto("http://example.com");
    await page.waitForSelector("h1");
    return true;
  });
});

Now all other blocks can access to the page. According to our previous example HomePage class, we can do either of following depending on how we defined the methods.

it("Gets the screenshot", async () => {
    await homepage.getScreenshot(); // <-- will use this.page
  });
it("Gets the title", async () => {
    await homepage.getTitle(page); // <-- will use the page we are passing on
});

Finally we cleanup the tests,

afterAll(async () => {
    await page.close();
    await browser.close();
    return true;
});

We probably need to run the jest tests with detectOpenHandles for headfull mode.

jest . --detectOpenHandles

Result:

Problem (with jest-puppeteer):

jest-puppeteer already gives you a global browser and page object. You do not need define anything.

However if you want to use jest-puppeteer and expect-puppeteer, you have to use a custom config file.

Solution:

Create a jest-config.json file and put the contents,

{
  "preset": "jest-puppeteer",
  "setupFilesAfterEnv": ["expect-puppeteer"]
}

Now, get rid of browser and page creation code, as well as any afterAll hooks for page.close as well.

Here is a working test file,

class HomePage {
  async getTitle() {
    return page.$("h1");
  }
}

describe("Example", () => {
  const homepage = new HomePage();
  beforeAll(async () => {
    // it has access to a global browser, page and scoped homepage

    await page.goto("http://example.com");
    await page.waitForSelector("h1");
  });
  it("Gets the screenshot", async () => {
    const element = await homepage.getTitle();
    await expect(element).toMatch("Example");
  });
});

And let's run this,

jest . --detectOpenHandles --config jest-config.json

Result:


问:
How to run multiple http requests on single click in IntelliJ http file instead of running them individually
I have 10 http requests in http file and want to run them on single click instead of clicking each request and see the output. Subsequent requests use output from previous requests so I want to run them serially in automated way.</p>

答:
You could use "Run/Debug Configurations", create a few separated files and setup order in window. But you'll get a big task, you cannot wait and setup timeouts for requests.

I guess you should use Jmeter for real work.

You also could try setup simple curl requests in the Linux bases os.


问:
Selenium Button Selector and Click
I want to automate the restart of my router using Selenium on Python. Everything is working fine except for the last step, which is locating the restart button and click it!

I have tried to locate it by (id, css_selector, name, value, xpath), but nothing seemed to work.

Here is my code:

```<code>driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)

resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()
</code>```

And this is the HTML code for the target button:

```<code><input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">
</code>```

When trying anything, I get the error:

```<code>NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)
</code>```

A Screenshot of the HTML Page:

Thank you all for your help in advance.

答:
The desired element is an JavaScript enabled element so to locate and click() on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.ApplyButtoncss.buttonwidth_150px#btnReboot[value='Restart']"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ApplyButtoncss buttonwidth_150px' and @id='btnReboot'][@value='Restart']"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Title: Selenium Button Selector and Click

Body:
I want to automate the restart of my router using Selenium on Python. Everything is working fine except for the last step, which is locating the restart button and click it!

I have tried to locate it by (id, css_selector, name, value, xpath), but nothing seemed to work.

Here is my code:

driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)

resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()

And this is the HTML code for the target button:

<input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">

When trying anything, I get the error:

NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)

A Screenshot of the HTML Page:

Thank you all for your help in advance.

Body:
The desired element is an JavaScript enabled element so to locate and click() on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.ApplyButtoncss.buttonwidth_150px#btnReboot[value='Restart']"))).click()

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ApplyButtoncss buttonwidth_150px' and @id='btnReboot'][@value='Restart']"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
how to determine maximum route cost in a n high numeric pyramid
I've got a numeric pyramid like this

```<code>       7
      4 8
     1 8 9
    2 4 6 7
   4 6 7 4 9
  4 9 7 3 8 8

routes: 32
</code>```

every number indexed by how powerful in its line.

```<code> 0 ( 9 => 1 ) 1 ( 8 => 5 ) 2 ( 8 => 4 ) 3 ( 7 => 2 ) 4 ( 4 => 0 ) 5 ( 3 => 3 )
 0 ( 9 => 4 ) 1 ( 7 => 2 ) 2 ( 6 => 1 ) 3 ( 4 => 3 ) 4 ( 4 => 0 )
 0 ( 7 => 3 ) 1 ( 6 => 2 ) 2 ( 4 => 1 ) 3 ( 2 => 0 )
 0 ( 9 => 2 ) 1 ( 8 => 1 ) 2 ( 1 => 0 )
 0 ( 8 => 1 ) 1 ( 4 => 0 )
 0 ( 7 => 0 )
</code>```

in this pyramid there are 2^(n-1) routes (you can go 2 way form each number)
If the pyramid high this low, it's easy you can calculate all the routes, and compare to eachother. But if you have an 50 high pyramid with 562949953421312 routes, the problem little bit more difficult.

I thoght I start from the bottom beginning from the most powerful numbers, but soon i realized, the max route cost ain't necesserly start or end up in big numbers.

Then I thought maybe secoundary indexes (where can you go futher from a number) will help, but I didin't even implement that becouse I assumed its still uses much resources and not optimal.

And now i'm confused how to restart thinking about this problem... any advice appreciated

答: Simplest way is to go bottom up and you have O(N) compexity. This case you do not need dynamic programming or recursion. Just compose another tree where number at higher level is max of numbers of lower layer.</p>

Body:
I've got a numeric pyramid like this

       7
      4 8
     1 8 9
    2 4 6 7
   4 6 7 4 9
  4 9 7 3 8 8

routes: 32

every number indexed by how powerful in its line.

 0 ( 9 => 1 ) 1 ( 8 => 5 ) 2 ( 8 => 4 ) 3 ( 7 => 2 ) 4 ( 4 => 0 ) 5 ( 3 => 3 )
 0 ( 9 => 4 ) 1 ( 7 => 2 ) 2 ( 6 => 1 ) 3 ( 4 => 3 ) 4 ( 4 => 0 )
 0 ( 7 => 3 ) 1 ( 6 => 2 ) 2 ( 4 => 1 ) 3 ( 2 => 0 )
 0 ( 9 => 2 ) 1 ( 8 => 1 ) 2 ( 1 => 0 )
 0 ( 8 => 1 ) 1 ( 4 => 0 )
 0 ( 7 => 0 )

in this pyramid there are 2^(n-1) routes (you can go 2 way form each number)
If the pyramid high this low, it's easy you can calculate all the routes, and compare to eachother. But if you have an 50 high pyramid with 562949953421312 routes, the problem little bit more difficult.

I thoght I start from the bottom beginning from the most powerful numbers, but soon i realized, the max route cost ain't necesserly start or end up in big numbers.

Then I thought maybe secoundary indexes (where can you go futher from a number) will help, but I didin't even implement that becouse I assumed its still uses much resources and not optimal.

And now i'm confused how to restart thinking about this problem... any advice appreciated


问:
Angular 5 - form validation e-mail
i want to solve this problem:
Angular 5 - template driven form

An input-field has type email. Example:

```<code><input type="email" [(ngModel)]="model.email" #email="ngModel" email />
</code>```

I want to validate this field. But it should not be a required field.
The validation should only start, if it isn't empty.
If the field is empty, everthing is fine. Otherwise an error message should be displayed until the e-mail adress is correct.

This is not realy working:

```<code>*ngIf="email.untouched && email.invalid"
</code>```

So, how can i validate the email field?
I miss a status like "not empty".

Any hint?

答:
I am using it in Angular 6+ and it's worked for me.

Use below pattern in TypeScript file.

```<code>this.validations_form = this.formBuilder.group({
    email: new FormControl('', Validators.compose([
           Validators.required,
           Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
    ]))
});
</code>```

Title: Angular 5 - form validation e-mail

Body:
i want to solve this problem:
Angular 5 - template driven form

An input-field has type email. Example:

<input type="email" [(ngModel)]="model.email" #email="ngModel" email />

I want to validate this field. But it should not be a required field.
The validation should only start, if it isn't empty.
If the field is empty, everthing is fine. Otherwise an error message should be displayed until the e-mail adress is correct.

This is not realy working:

*ngIf="email.untouched && email.invalid"

So, how can i validate the email field?
I miss a status like "not empty".

Any hint?

Body:
I am using it in Angular 6+ and it's worked for me.

Use below pattern in TypeScript file.

this.validations_form = this.formBuilder.group({
    email: new FormControl('', Validators.compose([
           Validators.required,
           Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
    ]))
});


问:
Javascript redirect based on navigator.userAgent
I'm trying to redirect a a user when they visit a web page based on the device that they are using to the relevant app store:

```<code>  //iPhone Version:
     if((navigator.userAgent.match(/iPhone/i)) ||  (navigator.userAgent.match(/iPod/i))) {
        window.location.href = "https://itunes.apple.com/gb/app/APP123";
      }

  //Android Version:
     if(navigator.userAgent.match(/android/i)) {
        window.location.href = "https://play.google.com/store/apps/details?id=com.APP.123";
       }
   //Anything Else
     else {
        window.location.href = "https://example.com";
       }
</code>```

This works perfectly on everything other than iPhone.

I know that the userAgent detects the iPhone part but it then ignores the redirect to the Apple App Store and redirects to example.com

Any suggestions would be greatly appriciated

答:
You need to use else if instead of just if:

```<code>if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
  window.location.href = "https://itunes.apple.com/gb/app/APP123"
} else if (navigator.userAgent.match(/android/i)) {
  window.location.href = "https://play.google.com/store/apps/details?id=com.APP.123"
} else {
  window.location.href = "https://example.com"
}
</code>```

If you don't use an else if block then you'll have 2 if statements:

One that checks if it's an iPhone and otherwise does nothing (since there's no else block)

Another that checks if it's an Android and otherwise redirects to https://example.com

Body:
I'm trying to redirect a a user when they visit a web page based on the device that they are using to the relevant app store:

  //iPhone Version:
     if((navigator.userAgent.match(/iPhone/i)) ||  (navigator.userAgent.match(/iPod/i))) {
        window.location.href = "https://itunes.apple.com/gb/app/APP123";
      }

  //Android Version:
     if(navigator.userAgent.match(/android/i)) {
        window.location.href = "https://play.google.com/store/apps/details?id=com.APP.123";
       }
   //Anything Else
     else {
        window.location.href = "https://example.com";
       }

This works perfectly on everything other than iPhone.

I know that the userAgent detects the iPhone part but it then ignores the redirect to the Apple App Store and redirects to example.com

Any suggestions would be greatly appriciated

Body:
You need to use else if instead of just if:

if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
  window.location.href = "https://itunes.apple.com/gb/app/APP123"
} else if (navigator.userAgent.match(/android/i)) {
  window.location.href = "https://play.google.com/store/apps/details?id=com.APP.123"
} else {
  window.location.href = "https://example.com"
}

If you don't use an else if block then you'll have 2 if statements:

One that checks if it's an iPhone and otherwise does nothing (since there's no else block)

Another that checks if it's an Android and otherwise redirects to https://example.com


问:
Generate setters that return self in Eclipse
I'd like to have my setters so that I can chain them like:

```<code>myPojo.setX(x).setY(y);
</code>```

Usually I generate setters with Eclipse but unfortunately code template for setters allows me to change only the body of the setter, not the signature.

What would be the easiest way to complete the above? Besides search-and-replace + manual editing? :)

答:
One alternative would be to use Lombok's @Setter and @Getter. Lombok enhances your classes at compile time based on some annotations. It works well on the command line and it has Eclipse support.

@Getter @Setter
public class Point {
    int x, y;

    static void test() {
        new Point().setX(1).setY(2);
    }
}
```
<p>And in <code>lombok.config</code> :</p>
```lombok.accessors.chain=true
```

Body:
I'd like to have my setters so that I can chain them like:

myPojo.setX(x).setY(y);

Usually I generate setters with Eclipse but unfortunately code template for setters allows me to change only the body of the setter, not the signature.

What would be the easiest way to complete the above? Besides search-and-replace + manual editing? :)

Body:
One alternative would be to use Lombok's @Setter and @Getter. Lombok enhances your classes at compile time based on some annotations. It works well on the command line and it has Eclipse support.

@Getter @Setter
public class Point {
    int x, y;

    static void test() {
        new Point().setX(1).setY(2);
    }
}

And in lombok.config :

lombok.accessors.chain=true


问:
Oracle PL/SQL Swapping a for loop for dynamic SQL, assistance with syntax changes
I have a for loop, here:

```<code>BEGIN

for rws in (

select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@DB1 a, MV_PRD_SEG_DATA b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from MV_PDU_TABLE where driver_table is null)
and a.owner in (select distinct productionschema from MV_PDU_TABLE c)
group by a.owner,a.table_name
order by a.table_name
)
loop
</code>```

Data is pulled out of the loop as follows by referencing rws. :

```<code>execute immediate' select /*+parallel (4)*/ count(*) from ' ||rws.owner||'.'||rws.table_name || '@' || dblink into TOTAL_ROW_COUNT;
</code>```

I now have to change some of the hard coded table references in the select statement to variables. (I will be declaring these earlier in the code.)

As I understand it, I must now switch to dynamic SQL.

In doing so, you can see here how the hard coded tables are now referred to as variables:

```<code>BEGIN

v_sql1 := 'select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@NAB1 a, '|| v_Mv_name ||' b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from '|| v_Mv_name ||' where driver_table is null)
and a.owner in (select distinct productionschema from '|| v_Mv_name ||' c)
group by a.owner,a.table_name
order by a.table_name';
</code>```

The issue is... how do I now manage getting the data out of the loop? I think I would loop, just using the variable containing the SQL?:

```<code>for rws in (v_sql1)

loop
</code>```

If so, what would now go here?

```<code>execute immediate' select /*+parallel (4)*/ count(*) from ' <NO_IDEA_HOW_TO_REFERENCE_THE_DATA_IN_THE_LOOP_NOW> ' into TOTAL_ROW_COUNT;
</code>```

答:
You can also use a RefCursor:

```<code>declare
   cur SYS_REFCURSOR;
   owner varchar2(30);
   table_namevarchar2(30);
   TOT_OBJECT_SIZE_MB number;
   EST_ONE_ROW_MB number;
   TOTAL_ROW_COUNT integer;
   v_sql1 varchar2(10000);

begin

v_sql1 := 'select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@NAB1 a, '|| v_Mv_name ||' b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from '|| v_Mv_name ||' where driver_table is null)
and a.owner in (select distinct productionschema from '|| v_Mv_name ||' c)
group by a.owner,a.table_name
order by a.table_name';

   open cur for v_sql1;
   loop
      fetch cur into owner, table_name, TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB;
      exit when cur%NOTFOUND;
      execute immediate' select /*+parallel (4)*/ count(*) from '||table_name into TOTAL_ROW_COUNT;
   end loop;
end;
</code>```

Usually a BULK COLLECT provides better performance. However, as you run a dedicated query for each record I don't think you will notice any difference in the performance.

Body:
I have a for loop, here:

BEGIN

for rws in (

select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@DB1 a, MV_PRD_SEG_DATA b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from MV_PDU_TABLE where driver_table is null)
and a.owner in (select distinct productionschema from MV_PDU_TABLE c)
group by a.owner,a.table_name
order by a.table_name
)
loop

Data is pulled out of the loop as follows by referencing rws. :

execute immediate' select /*+parallel (4)*/ count(*) from ' ||rws.owner||'.'||rws.table_name || '@' || dblink into TOTAL_ROW_COUNT;

I now have to change some of the hard coded table references in the select statement to variables. (I will be declaring these earlier in the code.)

As I understand it, I must now switch to dynamic SQL.

In doing so, you can see here how the hard coded tables are now referred to as variables:

BEGIN

v_sql1 := 'select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@NAB1 a, '|| v_Mv_name ||' b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from '|| v_Mv_name ||' where driver_table is null)
and a.owner in (select distinct productionschema from '|| v_Mv_name ||' c)
group by a.owner,a.table_name
order by a.table_name';

The issue is... how do I now manage getting the data out of the loop? I think I would loop, just using the variable containing the SQL?:

for rws in (v_sql1)

loop

If so, what would now go here?

execute immediate' select /*+parallel (4)*/ count(*) from ' <NO_IDEA_HOW_TO_REFERENCE_THE_DATA_IN_THE_LOOP_NOW> ' into TOTAL_ROW_COUNT;

Body:
You can also use a RefCursor:

declare
   cur SYS_REFCURSOR;
   owner varchar2(30);
   table_namevarchar2(30);
   TOT_OBJECT_SIZE_MB number;
   EST_ONE_ROW_MB number;
   TOTAL_ROW_COUNT integer;
   v_sql1 varchar2(10000);

begin

v_sql1 := 'select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2) TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
from dba_tables@NAB1 a, '|| v_Mv_name ||' b
where a.table_name = b.segment_name
and a.table_name in
(select table_name from '|| v_Mv_name ||' where driver_table is null)
and a.owner in (select distinct productionschema from '|| v_Mv_name ||' c)
group by a.owner,a.table_name
order by a.table_name';

   open cur for v_sql1;
   loop
      fetch cur into owner, table_name, TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB;
      exit when cur%NOTFOUND;
      execute immediate' select /*+parallel (4)*/ count(*) from '||table_name into TOTAL_ROW_COUNT;
   end loop;
end;

Usually a BULK COLLECT provides better performance. However, as you run a dedicated query for each record I don't think you will notice any difference in the performance.


问:
How to select drop-down value in Protractor using framework: 'jasmine',
I am trying to select drop down list using protractor. None of this code works.

```<code>it("Select Block from District", function() {

    const selectElement={}
    selectElement.selectElementDropdown =function(element,index,milliseconds){
     console.log("Selecting element by drop down","OK");

     element.all(by.tagName('option')).then(function(options){

         options[2].click();
    //here index 2 is hardcoded, which can be changed to options[index]
     });

     if(typeof milliseconds!=='undefined'){
         browser.sleep(milliseconds);
     }

    }

    module.exports =selectElement;

    const methodDropDown = {} //require('../Src/SelectElement.js');

    var DistrictDetails = function(){

    this.DistrictName = element.all(by.xpath("//label[text()='Select Block']")).get(7).element(by.xpath("//option[contains(text(),'Ambabhona')]"));
    //the selector is clicked to open the drop down
</code>```

I have already gone through pass the value using send keys to text box

```<code><div _ngcontent-c9="" class="col-sm-6">
    <label _ngcontent-c9="" class="col-md-5 control-label">District
        <span _ngcontent-c9="" class="err-msg">*</span>
    </label>
    <div _ngcontent-c9="" class="col-md-7">
        <p-dropdown _ngcontent-c9="" formcontrolname="districtId" placeholder="Select District"
            class="ng-tns-c6-189 ng-pristine ng-invalid ng-touched">
            <div class="ng-tns-c6-189 ui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix"
                style="width: 138px;">
                <!---->
                <div class="ui-helper-hidden-accessible ng-tns-c6-189 ng-star-inserted">
                    <select class="ng-tns-c6-189" aria-hidden="true" tabindex="-1" aria-label=" ">
                        <!---->
                        <option class="ng-tns-c6-189 ng-star-inserted">Select District</option>
                        <!---->
                        <!---->
                        <!---->
                        <!---->
                        <option class="ng-tns-c6-189 ng-star-inserted" value="390" style="">Bargarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="391" style="">Jharsuguda</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="392" style="">Sambalpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="393" style="">Deogarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="394" style="">Sundergarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="395" style="">Keonjhar</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="396" style="">Mayurbhanj</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="397" style="">Balasore</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="398" style="">Bhadrak</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="399" style="">Kendrapara</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="400" style="">Jagatsinghpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="401" style="">Cuttack</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="402" style="">Jajpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="403" style="">Dhenkanal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="404" style="">Angul</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="405" style="">Nayagarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="406" style="">Khordha</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="407" style="">Puri</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="408" style="">Ganjam</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="409" style="">Gajapati</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="410" style="">Kandhamal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="411" style="">Boudh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="412" style="">Sonepur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="413" style="">Bolangir</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="414" style="">Nuapada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="415" style="">Kalahandi</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="416" style="">Rayagada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="417" style="">Nabarangpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="418" style="">Koraput</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="419" style="">Malkangiri</option>
                        <!---->
                    </select>
                </div>
                <div class="ui-helper-hidden-accessible">
                    <input class="ng-tns-c6-189" readonly="" role="listbox" type="text" aria-label=" ">
                </div>
                <!---->
                <!----><label
                    class="ng-tns-c6-189 ui-dropdown-label ui-inputtext ui-corner-all ui-placeholder ng-star-inserted">
                    Select District
                </label>
                <!---->
                <!---->
                <div class="ui-dropdown-trigger ui-state-default ui-corner-right"><span
                        class="ui-dropdown-trigger-icon ui-clickable pi pi-caret-down"></span>
                </div>
                <div class="ng-tns-c6-189 ui-dropdown-panel ui-widget-content ui-corner-all ui-shadow ng-trigger ng-trigger-panelState"
                    style="display: none; z-index: 1181; top: 27px; left: 0px; opacity: 0;">
                    <!---->
                    <div class="ui-dropdown-items-wrapper" style="max-height: 200px;">
                        <!---->
                    </div>
                </div>
            </div>
        </p-dropdown>
        <!---->
    </div>
</div>
</code>```

Want to select value form drop-down list like  Deogarh

答:
Maybe try this:

HTML:
In select tag, add attribute data-targetId:

```<code>[attr.data-targetId]="selectTag"
</code>```

and then use it in your test like this:

```<code>target='[data-targetId="selectTag"] .ng-star-inserted';
$('[role="listbox"]').click(); // click on ddListBtn to open the ddList if it's not open
let value = 'Kalahandi'; // an example
element(by.cssContainingText(target, value)).click();
</code>```

Body:
I am trying to select drop down list using protractor. None of this code works.

it("Select Block from District", function() {

    const selectElement={}
    selectElement.selectElementDropdown =function(element,index,milliseconds){
     console.log("Selecting element by drop down","OK");

     element.all(by.tagName('option')).then(function(options){

         options[2].click();
    //here index 2 is hardcoded, which can be changed to options[index]
     });

     if(typeof milliseconds!=='undefined'){
         browser.sleep(milliseconds);
     }

    }

    module.exports =selectElement;

    const methodDropDown = {} //require('../Src/SelectElement.js');

    var DistrictDetails = function(){

    this.DistrictName = element.all(by.xpath("//label[text()='Select Block']")).get(7).element(by.xpath("//option[contains(text(),'Ambabhona')]"));
    //the selector is clicked to open the drop down

I have already gone through pass the value using send keys to text box

    District
        *

                    <select class="ng-tns-c6-189" aria-hidden="true" tabindex="-1" aria-label=" ">

                        <option class="ng-tns-c6-189 ng-star-inserted">Select District</option>

                        <option class="ng-tns-c6-189 ng-star-inserted" value="390" style="">Bargarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="391" style="">Jharsuguda</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="392" style="">Sambalpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="393" style="">Deogarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="394" style="">Sundergarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="395" style="">Keonjhar</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="396" style="">Mayurbhanj</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="397" style="">Balasore</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="398" style="">Bhadrak</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="399" style="">Kendrapara</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="400" style="">Jagatsinghpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="401" style="">Cuttack</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="402" style="">Jajpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="403" style="">Dhenkanal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="404" style="">Angul</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="405" style="">Nayagarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="406" style="">Khordha</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="407" style="">Puri</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="408" style="">Ganjam</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="409" style="">Gajapati</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="410" style="">Kandhamal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="411" style="">Boudh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="412" style="">Sonepur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="413" style="">Bolangir</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="414" style="">Nuapada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="415" style="">Kalahandi</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="416" style="">Rayagada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="417" style="">Nabarangpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="418" style="">Koraput</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="419" style="">Malkangiri</option>

                    </select>

                    <input class="ng-tns-c6-189" readonly="" role="listbox" type="text" aria-label=" ">

                    Select District

Want to select value form drop-down list like  Deogarh

Body:
Maybe try this:

HTML:
In select tag, add attribute data-targetId:

[attr.data-targetId]="selectTag"

and then use it in your test like this:

target='[data-targetId="selectTag"] .ng-star-inserted';
$('[role="listbox"]').click(); // click on ddListBtn to open the ddList if it's not open
let value = 'Kalahandi'; // an example
element(by.cssContainingText(target, value)).click();


问:
Randomizing balanced experimental designs
I am writing some code to generate balanced experimental designs for market research, specifically for use in conjoint analysis and maximum difference scaling.

The first step is to generate a Partially Balanced Incompleted Block (PBIB) design.  This is straight-forward using the R package AlgDesign.

For most types of research such a design would be sufficient.  However, in market research one wants to control for order effects in each block.  This is where I would appreciate some help.

Create test data

```<code># The following code is not essential in understanding the problem,
# but I provide it in case you are curious about the origin of the data itself.
#library(AlgDesign)
#set.seed(12345)
#choices <- 4
#nAttributes <- 7
#blocksize <- 7
#bsize <- rep(choices, blocksize)
#PBIB <- optBlock(~., withinData=factor(1:nAttributes), blocksizes=bsize)
#df <- data.frame(t(array(PBIB$rows, dim=c(choices, blocksize))))
#colnames(df) <- paste("Item", 1:choices, sep="")
#rownames(df) <- paste("Set", 1:nAttributes, sep="")

df <- structure(list(
  Item1 = c(1, 2, 1, 3, 1, 1, 2),
  Item2 = c(4, 4, 2, 5, 3, 2, 3),
  Item3 = c(5, 6, 5, 6, 4, 3, 4),
  Item4 = c(7, 7, 6, 7, 6, 7, 5)),
  .Names = c("Item1", "Item2", "Item3", "Item4"),
  row.names = c("Set1", "Set2", "Set3", "Set4", "Set5", "Set6", "Set7"),
  class = "data.frame")
</code>```

** Define two helper functions

balanceMatrix calculates the balance of the matrix:

```<code>balanceMatrix <- function(x){
    t(sapply(unique(unlist(x)), function(i)colSums(x==i)))
}
</code>```

balanceScore calculates a metric of 'fit' - lower scores are better, with zero perfect:

```<code>balanceScore <- function(x){
    sum((1-x)^2)
}
</code>```

Define a function that resamples the rows at random

```<code>findBalance <- function(x, nrepeat=100){
    df <- x
    minw <- Inf
    for (n in 1:nrepeat){
        for (i in 1:nrow(x)){df[i,] <- sample(df[i, ])}
        w <- balanceMatrix(df)
        sumw <- balanceScore(w)
        if(sumw < minw){
            dfbest <- df
            minw <- sumw
        }
    }
    dfbest
}
</code>```

Main code

The dataframe df is a balanced design of 7 sets.  Each set will display 4 items to the respondent. The numeric values in df refers to 7 different attributes.  For example, in Set1 respondent will be asked to choose his/her preferred option from attributes 1, 3, 4 and 7.

The ordering of items in each set is conceptually not important.  Thus an ordering of (1,4,5,7) is identical to (7,5,4,1).

However, to get a fully balanced design, each attribute will appear an equal number of times in each column.  This design is there imbalanced, since attribute 1 appears 4 times in column 1:

```<code>df

     Item1 Item2 Item3 Item4
Set1     1     4     5     7
Set2     2     4     6     7
Set3     1     2     5     6
Set4     3     5     6     7
Set5     1     3     4     6
Set6     1     2     3     7
Set7     2     3     4     5
</code>```

To try and find a more balanced design, I wrote the function findBalance.  This conducts a random search for better solutions, by randomly sampling across the rows of df.  With 100 repeats it finds the following best solution:

```<code>set.seed(12345)
dfbest <- findBalance(df, nrepeat=100)
dfbest

     Item1 Item2 Item3 Item4
Set1     7     5     1     4
Set2     6     7     4     2
Set3     2     1     5     6
Set4     5     6     7     3
Set5     3     1     6     4
Set6     7     2     3     1
Set7     4     3     2     5
</code>```

This appears more balanced, and the calculated balance matrix contains lots of ones.  The balance matrix counts the number of times each attribute appears in each column.  For example, the following table indicates (in the top left hand cell) that attribute 1 appears twice not at all in column 1, and twice in column 2:

```<code>balanceMatrix(dfbest)

     Item1 Item2 Item3 Item4
[1,]     0     2     1     1
[2,]     1     1     1     1
[3,]     1     1     1     1
[4,]     1     0     1     2
[5,]     1     1     1     1
[6,]     1     1     1     1
[7,]     2     1     1     0
</code>```

The balance score for this solution is 6, indicating there are at least six cells unequal to 1:

```<code>balanceScore(balanceMatrix(dfbest))
[1] 6
</code>```

My question

Thank you for following this detailed example.  My question is how can I rewrite this search function to be more systematic?  I'd like to tell R to:

Minimize balanceScore(df)

By changing row order of df

Subject to: already fully constrained

答:
OK, I somehow misunderstood your question. So bye bye Fedorov, hello applied Fedorov.

The following algorithm is based on the second iteration of the Fedorov algorithm :

calculate all possible permutation for every set, and store them in the C0 list

draw a first possible solution from the C0 space (one permutation for every set). This can be the original one, but as I need the indices, I rather just start at random.

calculate the score for every new solution, where the first set is replaced by all permutations.

replace the first set with the permutation giving the lowest score

repeat 3-4 for every other set

repeat 3-5 until score reaches 0 or for n iterations.

Optionally, you can restart the procedure after 10 iterations and start from another starting point. In you test case, it turned out that few starting points converged very slowly to 0. The function below found balanced experimental designs with a score of 0 in on average 1.5 seconds on my computer :

```<code>> X <- findOptimalDesign(df)
> balanceScore(balanceMatrix(X))
[1] 0
> mean(replicate(20, system.time(X <- findOptimalDesign(df))[3]))
[1] 1.733
</code>```

So this is the function now (given your original balanceMatrix and balanceScore functions) :

```<code>findOptimalDesign <- function(x,iter=4,restart=T){
    stopifnot(require(combinat))
    # transform rows to list
    sets <- unlist(apply(x,1,list),recursive=F)
    nsets <- NROW(x)
    # C0 contains all possible design points
    C0 <- lapply(sets,permn)
    n <- gamma(NCOL(x)+1)

    # starting point
    id <- sample(1:n,nsets)
    Sol <- sapply(1:nsets,function(i)C0[[i]][id[i]])

    IT <- iter
    # other iterations
    while(IT > 0){
      for(i in 1:nsets){
          nn <- 1:n
          scores <- sapply(nn,function(p){
             tmp <- Sol
             tmp[[i]] <- C0[[i]][[p]]
             w <- balanceMatrix(do.call(rbind,tmp))
             balanceScore(w)
          })
          idnew <- nn[which.min(scores)]
          Sol[[i]] <- C0[[i]][[idnew]]

      }
      #Check if score is 0
      out <- as.data.frame(do.call(rbind,Sol))
      score <- balanceScore(balanceMatrix(out))
      if (score==0) {break}
      IT <- IT - 1

      # If asked, restart
      if(IT==0 & restart){
          id <- sample(1:n,nsets)
          Sol <- sapply(1:nsets,function(i)C0[[i]][id[i]])
          IT <- iter
      }
    }
    out
}
</code>```

HTH

EDIT : fixed small bug (it restarted immediately after every round as I forgot to condition on IT). Doing that, it runs a bit faster still.

Body:
I am writing some code to generate balanced experimental designs for market research, specifically for use in conjoint analysis and maximum difference scaling.

The first step is to generate a Partially Balanced Incompleted Block (PBIB) design.  This is straight-forward using the R package AlgDesign.

For most types of research such a design would be sufficient.  However, in market research one wants to control for order effects in each block.  This is where I would appreciate some help.

Create test data

# The following code is not essential in understanding the problem,
# but I provide it in case you are curious about the origin of the data itself.
#library(AlgDesign)
#set.seed(12345)
#choices <- 4
#nAttributes <- 7
#blocksize <- 7
#bsize <- rep(choices, blocksize)
#PBIB <- optBlock(~., withinData=factor(1:nAttributes), blocksizes=bsize)
#df <- data.frame(t(array(PBIB$rows, dim=c(choices, blocksize))))
#colnames(df) <- paste("Item", 1:choices, sep="")
#rownames(df) <- paste("Set", 1:nAttributes, sep="")

df <- structure(list(
  Item1 = c(1, 2, 1, 3, 1, 1, 2),
  Item2 = c(4, 4, 2, 5, 3, 2, 3),
  Item3 = c(5, 6, 5, 6, 4, 3, 4),
  Item4 = c(7, 7, 6, 7, 6, 7, 5)),
  .Names = c("Item1", "Item2", "Item3", "Item4"),
  row.names = c("Set1", "Set2", "Set3", "Set4", "Set5", "Set6", "Set7"),
  class = "data.frame")

** Define two helper functions

balanceMatrix calculates the balance of the matrix:

balanceMatrix <- function(x){
    t(sapply(unique(unlist(x)), function(i)colSums(x==i)))
}

balanceScore calculates a metric of 'fit' - lower scores are better, with zero perfect:

balanceScore <- function(x){
    sum((1-x)^2)
}

Define a function that resamples the rows at random

findBalance <- function(x, nrepeat=100){
    df <- x
    minw <- Inf
    for (n in 1:nrepeat){
        for (i in 1:nrow(x)){df[i,] <- sample(df[i, ])}
        w <- balanceMatrix(df)
        sumw <- balanceScore(w)
        if(sumw < minw){
            dfbest <- df
            minw <- sumw
        }
    }
    dfbest
}

Main code

The dataframe df is a balanced design of 7 sets.  Each set will display 4 items to the respondent. The numeric values in df refers to 7 different attributes.  For example, in Set1 respondent will be asked to choose his/her preferred option from attributes 1, 3, 4 and 7.

The ordering of items in each set is conceptually not important.  Thus an ordering of (1,4,5,7) is identical to (7,5,4,1).

However, to get a fully balanced design, each attribute will appear an equal number of times in each column.  This design is there imbalanced, since attribute 1 appears 4 times in column 1:

df

     Item1 Item2 Item3 Item4
Set1     1     4     5     7
Set2     2     4     6     7
Set3     1     2     5     6
Set4     3     5     6     7
Set5     1     3     4     6
Set6     1     2     3     7
Set7     2     3     4     5

To try and find a more balanced design, I wrote the function findBalance.  This conducts a random search for better solutions, by randomly sampling across the rows of df.  With 100 repeats it finds the following best solution:

set.seed(12345)
dfbest <- findBalance(df, nrepeat=100)
dfbest

     Item1 Item2 Item3 Item4
Set1     7     5     1     4
Set2     6     7     4     2
Set3     2     1     5     6
Set4     5     6     7     3
Set5     3     1     6     4
Set6     7     2     3     1
Set7     4     3     2     5

This appears more balanced, and the calculated balance matrix contains lots of ones.  The balance matrix counts the number of times each attribute appears in each column.  For example, the following table indicates (in the top left hand cell) that attribute 1 appears twice not at all in column 1, and twice in column 2:

balanceMatrix(dfbest)

     Item1 Item2 Item3 Item4
[1,]     0     2     1     1
[2,]     1     1     1     1
[3,]     1     1     1     1
[4,]     1     0     1     2
[5,]     1     1     1     1
[6,]     1     1     1     1
[7,]     2     1     1     0

The balance score for this solution is 6, indicating there are at least six cells unequal to 1:

balanceScore(balanceMatrix(dfbest))
[1] 6

My question

Thank you for following this detailed example.  My question is how can I rewrite this search function to be more systematic?  I'd like to tell R to:

Minimize balanceScore(df)

By changing row order of df

Subject to: already fully constrained

Body:
OK, I somehow misunderstood your question. So bye bye Fedorov, hello applied Fedorov.

The following algorithm is based on the second iteration of the Fedorov algorithm :

calculate all possible permutation for every set, and store them in the C0 list

draw a first possible solution from the C0 space (one permutation for every set). This can be the original one, but as I need the indices, I rather just start at random.

calculate the score for every new solution, where the first set is replaced by all permutations.

replace the first set with the permutation giving the lowest score

repeat 3-4 for every other set

repeat 3-5 until score reaches 0 or for n iterations.

Optionally, you can restart the procedure after 10 iterations and start from another starting point. In you test case, it turned out that few starting points converged very slowly to 0. The function below found balanced experimental designs with a score of 0 in on average 1.5 seconds on my computer :

> X <- findOptimalDesign(df)
> balanceScore(balanceMatrix(X))
[1] 0
> mean(replicate(20, system.time(X <- findOptimalDesign(df))[3]))
[1] 1.733

So this is the function now (given your original balanceMatrix and balanceScore functions) :

findOptimalDesign <- function(x,iter=4,restart=T){
    stopifnot(require(combinat))
    # transform rows to list
    sets <- unlist(apply(x,1,list),recursive=F)
    nsets <- NROW(x)
    # C0 contains all possible design points
    C0 <- lapply(sets,permn)
    n <- gamma(NCOL(x)+1)

    # starting point
    id <- sample(1:n,nsets)
    Sol <- sapply(1:nsets,function(i)C0[[i]][id[i]])

    IT <- iter
    # other iterations
    while(IT > 0){
      for(i in 1:nsets){
          nn <- 1:n
          scores <- sapply(nn,function(p){
             tmp <- Sol
             tmp[[i]] <- C0[[i]][[p]]
             w <- balanceMatrix(do.call(rbind,tmp))
             balanceScore(w)
          })
          idnew <- nn[which.min(scores)]
          Sol[[i]] <- C0[[i]][[idnew]]

      }
      #Check if score is 0
      out <- as.data.frame(do.call(rbind,Sol))
      score <- balanceScore(balanceMatrix(out))
      if (score==0) {break}
      IT <- IT - 1

      # If asked, restart
      if(IT==0 & restart){
          id <- sample(1:n,nsets)
          Sol <- sapply(1:nsets,function(i)C0[[i]][id[i]])
          IT <- iter
      }
    }
    out
}

HTH

EDIT : fixed small bug (it restarted immediately after every round as I forgot to condition on IT). Doing that, it runs a bit faster still.


问:
Check if record exists in python. If exists then skip else process
I have a function for extracting frames from videos. I have a csv file which has the names of the videos already processed. I want to check if the name of a newly added video file is present in the csv file. If present then exit the code else process the function to extract frames from the new video

```<code>def extractFrames(m):
    global vid_name

    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        print("path of video========>>>>.",vid_files[v_f])

        #latest_file=max(vid_files, key=os.path.getctime)

        #print(latest_file)

        v1=os.path.basename(vid_files[v_f])
        try:
            vid_name = os.path.splitext(v1)[0]

            vidcap = cv2.VideoCapture(vid_files[v_f])
        except cv2.error as e:
            print(e)
        except:
                print('error')
        #condition
        fsize=os.stat(vid_files[v_f])
        print('=============size of video ===================:' , fsize.st_size)
        try:

            if (fsize.st_size > 1000):

                fps = vidcap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
                frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
                duration = frameCount/fps
                minutes = int(duration/60)
                print('fps = ' + str(fps))
                print('number of frames = ' + str(frameCount))
                print('duration (S) = ' + str(duration))
                if (duration > 1):
                    success,image = vidcap.read()

                    count=0

                    success=True

                    while success:

                        img_name = vid_name + '_f' + str(count) + ".jpg"

                        success,image = vidcap.read()
                        if count % 10 == 0 or count ==0:
                            target_non_target(img_name, image)

                        count+=1

                    vidcap.release()

                    cv2.destroyAllWindows()
        except:
            print("error")

        print('finished processing video ', vid_files[v_f])
        with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv', 'a') as csv_file:
            fieldnames = ['Video_Name','Process']
            file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv').st_size == 0
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            if file_is_empty:
                writer.writeheader()
            writer.writerow({'Video_Name':vid_name,'Process':'done'})

if __name__ == "__main__":

    x="C:\\Python36\\videos\\*.mp4"

    extractFrames(x)
</code>```

Suppose a folder has 2 videos V1 and V2 from which frames have already been extracted and the names V1 and V2 are added in the csv file. Now when i add video V3 the code should check if V3 exists already in the csv. If it exists then the code should be skipped else frames from V3 should be processed and V3 should be added in the csv file after extraction of the frames

答:
Without the details you have code like this

```<code>def extractFrames(m):
    # do stuff
    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        #find vid_name
        #do stuff
        save_as_done(vid_name)

if __name == '__main__':
    x="C:\\Python36\\videos\\*.mp4"
    extractFrames(x)
</code>```

If you pass in a list of things that have been done, something like

```<code>done = ['first.mp4', 'second.mp4']
</code>```

you can check if a filename has been done like this:

```<code>>>> 'first.mp4' in done
True
</code>```

So, if you save the filenames (fully pathed) of what you've done to a file and load them into a list, like this

def load_done_list():
    with open('video_info.csv') as f: #or full path, maybe pass in the file name?
      return f.readlines()

you can check the list

```<code>def extractFrames(m, done):
    # do stuff
    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        #find vid_name
        if vid_name not in done:  #,--- check if done already
            #do stuff
            save_as_done(vid_name)

if __name == '__main__':
    x="C:\\Python36\\videos\\*.mp4"
    done = load_done_list() #<--- You need to load this into a list
    extractFrames(x, done)  #<--- and pass it in to your function
</code>```

This need something that just saves the filenames as they are done:

```<code>def save_as_done(vid_name):
    with open('video_info.csv', 'a') as f: #maybe pass in the file name so you only define it once?
        f.write(vid_name + '\n')
</code>```

I haven't filled in all the details, but have shown where you can do loading and saving and checking.
The written file only has the filenames in - there doesn't seem much point in having "done" on the end of each line.
This will keep opening and closing the file as the files are processed. This may slow thing down but might not matter: you could pass in a file handle to write to, to keep it open. You have options.

Body:
I have a function for extracting frames from videos. I have a csv file which has the names of the videos already processed. I want to check if the name of a newly added video file is present in the csv file. If present then exit the code else process the function to extract frames from the new video

def extractFrames(m):
    global vid_name

    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        print("path of video========>>>>.",vid_files[v_f])

        #latest_file=max(vid_files, key=os.path.getctime)

        #print(latest_file)

        v1=os.path.basename(vid_files[v_f])
        try:
            vid_name = os.path.splitext(v1)[0]

            vidcap = cv2.VideoCapture(vid_files[v_f])
        except cv2.error as e:
            print(e)
        except:
                print('error')
        #condition
        fsize=os.stat(vid_files[v_f])
        print('=============size of video ===================:' , fsize.st_size)
        try:

            if (fsize.st_size > 1000):

                fps = vidcap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
                frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
                duration = frameCount/fps
                minutes = int(duration/60)
                print('fps = ' + str(fps))
                print('number of frames = ' + str(frameCount))
                print('duration (S) = ' + str(duration))
                if (duration > 1):
                    success,image = vidcap.read()

                    count=0

                    success=True

                    while success:

                        img_name = vid_name + '_f' + str(count) + ".jpg"

                        success,image = vidcap.read()
                        if count % 10 == 0 or count ==0:
                            target_non_target(img_name, image)

                        count+=1

                    vidcap.release()

                    cv2.destroyAllWindows()
        except:
            print("error")

        print('finished processing video ', vid_files[v_f])
        with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv', 'a') as csv_file:
            fieldnames = ['Video_Name','Process']
            file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv').st_size == 0
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            if file_is_empty:
                writer.writeheader()
            writer.writerow({'Video_Name':vid_name,'Process':'done'})

if __name__ == "__main__":

    x="C:\\Python36\\videos\\*.mp4"

    extractFrames(x)

Suppose a folder has 2 videos V1 and V2 from which frames have already been extracted and the names V1 and V2 are added in the csv file. Now when i add video V3 the code should check if V3 exists already in the csv. If it exists then the code should be skipped else frames from V3 should be processed and V3 should be added in the csv file after extraction of the frames

Body:
Without the details you have code like this

def extractFrames(m):
    # do stuff
    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        #find vid_name
        #do stuff
        save_as_done(vid_name)

if __name == '__main__':
    x="C:\\Python36\\videos\\*.mp4"
    extractFrames(x)

If you pass in a list of things that have been done, something like

done = ['first.mp4', 'second.mp4']

you can check if a filename has been done like this:

>>> 'first.mp4' in done
True

So, if you save the filenames (fully pathed) of what you've done to a file and load them into a list, like this

def load_done_list():
    with open('video_info.csv') as f: #or full path, maybe pass in the file name?
      return f.readlines()

you can check the list

def extractFrames(m, done):
    # do stuff
    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        #find vid_name
        if vid_name not in done:  #,--- check if done already
            #do stuff
            save_as_done(vid_name)

if __name == '__main__':
    x="C:\\Python36\\videos\\*.mp4"
    done = load_done_list() #<--- You need to load this into a list
    extractFrames(x, done)  #<--- and pass it in to your function

This need something that just saves the filenames as they are done:

def save_as_done(vid_name):
    with open('video_info.csv', 'a') as f: #maybe pass in the file name so you only define it once?
        f.write(vid_name + '\n')

I haven't filled in all the details, but have shown where you can do loading and saving and checking.
The written file only has the filenames in - there doesn't seem much point in having "done" on the end of each line.
This will keep opening and closing the file as the files are processed. This may slow thing down but might not matter: you could pass in a file handle to write to, to keep it open. You have options.


问:
Select next column based on label reference to columns of pandas dataframe
```<code>import pandas as pd, numpy as np

df1 = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=['a','qww12','b','hdbh'])
</code>```

If I have to select columns 'a' and 'b' I do the following:

```<code>sublist=['a','b']

df2= df1[df1.columns.intersection(sublist)]
</code>```

Is there a simpler way to select columns next to 'a' and 'b' without having to type out the names? Actually I am fetching the data from excel sheet and the names can change and can have white spaces.

Thanks in advance.

Expected output

```<code>   qww12  hdbh
0     18    86
1     84    67
2     23    45
3     60    15
4     82    60
5     84    75
6     24    23
7     34    79
8      4    45
9      2    82
</code>```

答:
You can use get_indexer() for this to get the index of the sublist and add 1 to get the next column index, then use df.iloc[]:

```<code>df1.iloc[:,df1.columns.get_indexer(sublist)+1]
</code>```

```<code>   qww12  hdbh
0     48    91
1     86    67
2     21    98
3     11    94
4      9    14
5     70    54
6     38    61
7     99    65
8     16    86
9     15    40
</code>```

Body:
import pandas as pd, numpy as np

df1 = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=['a','qww12','b','hdbh'])

If I have to select columns 'a' and 'b' I do the following:

sublist=['a','b']

df2= df1[df1.columns.intersection(sublist)]

Is there a simpler way to select columns next to 'a' and 'b' without having to type out the names? Actually I am fetching the data from excel sheet and the names can change and can have white spaces.

Thanks in advance.

Expected output

   qww12  hdbh
0     18    86
1     84    67
2     23    45
3     60    15
4     82    60
5     84    75
6     24    23
7     34    79
8      4    45
9      2    82

Body:
You can use get_indexer() for this to get the index of the sublist and add 1 to get the next column index, then use df.iloc[]:

df1.iloc[:,df1.columns.get_indexer(sublist)+1]

   qww12  hdbh
0     48    91
1     86    67
2     21    98
3     11    94
4      9    14
5     70    54
6     38    61
7     99    65
8     16    86
9     15    40


问:
How to run multiple ingress gateway for public and private domains
I have multiple public and private applications running in my kubernetes cluster. I want to separate out traffic for each type by running multiple istio-gateway deployments. Is there any straight methods to implement it with istio.

For both type of application I am using custom CA and importing certificates as secret manually. Do I need to anything cert manager part to achieve my use case

答:
The cert-manager is not required to achieve this configuration.

To install custom istio-ingress-gateway (for you private domain) next to the default one (for public domain), you can take as an example 'example-values/values-istio-gateways.yaml' values file (part of official Istio github project), and use it with helm, to generate all necessary manifest files to upgrade/extend your current Istio installation.

To generate manifest files use the following command:

```<code>helm template install/kubernetes/helm/istio --set gateways.custom-gateway.namespace=nepomucen-custom -f install/kubernetes/istio-demo.yaml -f install/kubernetes/helm/istio/example-values/values-istio-gateways.yaml
</code>```

Note: This creates custom gateway in non-default namespace

Body:
The cert-manager is not required to achieve this configuration.

To install custom istio-ingress-gateway (for you private domain) next to the default one (for public domain), you can take as an example 'example-values/values-istio-gateways.yaml' values file (part of official Istio github project), and use it with helm, to generate all necessary manifest files to upgrade/extend your current Istio installation.

To generate manifest files use the following command:

helm template install/kubernetes/helm/istio --set gateways.custom-gateway.namespace=nepomucen-custom -f install/kubernetes/istio-demo.yaml -f install/kubernetes/helm/istio/example-values/values-istio-gateways.yaml

Note: This creates custom gateway in non-default namespace


问:
Why doesn't my use of "protected" work?
I have read that a protected member can be accessed from derived classes, but the following does not work.</p>

```<code>class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}
</code>```

答:
You do not need to create an instance of A if you inherit A.

```<code>class A
{
   protected int Test;
}
class B:A
{
   public B()
   {
     this.Test = 666;
   }
}
</code>```

Title: Why doesn't my use of "protected" work?

Body:
I have read that a protected member can be accessed from derived classes, but the following does not work.

class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}

Body:
You do not need to create an instance of A if you inherit A.

class A
{
   protected int Test;
}
class B:A
{
   public B()
   {
     this.Test = 666;
   }
}


问:
Error writing request body to server - eGit - Eclipse
I am using BitBucket. https://VibhuDadhichi@bitbucket.org/VibhuDadhichi/disrupt.git

I cloned a project using eGit to my local and added a project to it using eclipse "Add Existing project to workspace". Ran the project on the system. Everything worked fine. Now when I want to push the project to the master. It stops at 40% - Error writing request body to server. No change.

I can see the changes on my local git folder.

I tried increasing the size of the buffer. It's not that big file.

https.postBuffer=524288000 in the git/config file.

New to version control. Please help.

答:
In Eclipse, we follow below steps:
Right click on your GIT Project and go to

```<code>Properties>Configuration>Add Entry
</code>```

Set below properties

```<code>Key=https.postBuffer
Value=524288000
</code>```

Restart Eclipse IDE

Body:
In Eclipse, we follow below steps:
Right click on your GIT Project and go to

Properties>Configuration>Add Entry

Set below properties

Key=https.postBuffer
Value=524288000

Restart Eclipse IDE


问:
Simpler way to use array of class
I have a class and then defined an array of class, each time that I want to add a node to array, I have to mention the class name that I don't like it:

```<code>export class ItemModel {
  constructor(
    ID,
    Name
  ) {
    this.ID = ID;
    this.Name = Name;
  }
}

export var ItemsArray = [];

ItemsArray.push(new ItemModel(0, "BreakFast"));
ItemsArray.push(new ItemModel(1, "Lunch"));
ItemsArray.push(new ItemModel(2, "Dinner"));
</code>```

After reading this post:

https://answers.unity.com/questions/637902/how-to-use-javascript-array-with-classes.html

I tried to declare the class at the time that I define the array like this:

```<code>var ItemsArray : ItemModel[];
</code>```

but I get error : "Types Can only be used in .ts files.

I searched google for that but none of them was helpful.

Any recommendation would be appreciated.

答:
The post you've linked to is using TypeScript, which is a different language from JavaScript: It's a superset of JavaScript (which compiles to JavaScript) that adds static typing (and a couple of other features, like automatic property initialization in constructors).

This TypeScript line:

```<code>var ItemsArray : ItemModel[];
</code>```

is equivalent to this JavaScript:

```<code>var ItemsArray;
</code>```

It's just that the TypeScript version declares that the ItemsArray variable has the static type ItemModel[].

If you're using JavaScript itself, you don't define the types of variables. Your export var ItemsArray = []; is just fine (other than that I'd use let or const instead of var).

Side Note: You can write that array more concisely in JavaScript using an array initializer:

```<code>export const ItemsArray = [
    new ItemModel(0, "BreakFast"),
    new ItemModel(1, "Lunch"),
    new ItemModel(2, "Dinner")
];
</code>```

That's also valid TypeScript, even without a type declaration: TypeScript will infer that you want the type of ItemsArray to be ItemModel[] (because TypeScript does type inference and it can see that you're filling ItemsArray with ItemModel objects).

If you wanted to start with an empty array but still give it a static type, you'd do this:

```<code>//                                   /------ Telling TypeScript to use ItemModel[]
//                      vvvvvvvvvvvvv        as the type
export const ItemsArray : ItemModel[] = [];
//                                   ^^^^^-- Initializing ItemsArray with an
//                                           empty array
</code>```

Then your push calls would be typechecked, so this would work:

```<code>ItemsArray.push(new ItemModel(0, "BreakFast"));
</code>```

but this would cause an error (during TypeScript->JavaScript compilation)

```<code>ItemsArray.push("BreakFast");
</code>```

because "Breakfast" is not compatible with ItemModel.

Side Note 2: The overwhelming convention in JavaScript (and TypeScript) is that variables start with a lowercase letter, not an uppercase one. So itemsArray rather than ItemsArray.

Title: Simpler way to use array of class

Body:
I have a class and then defined an array of class, each time that I want to add a node to array, I have to mention the class name that I don't like it:

export class ItemModel {
  constructor(
    ID,
    Name
  ) {
    this.ID = ID;
    this.Name = Name;
  }
}

export var ItemsArray = [];

ItemsArray.push(new ItemModel(0, "BreakFast"));
ItemsArray.push(new ItemModel(1, "Lunch"));
ItemsArray.push(new ItemModel(2, "Dinner"));

After reading this post:

https://answers.unity.com/questions/637902/how-to-use-javascript-array-with-classes.html

I tried to declare the class at the time that I define the array like this:

var ItemsArray : ItemModel[];

but I get error : "Types Can only be used in .ts files.

I searched google for that but none of them was helpful.

Any recommendation would be appreciated.

Body:
The post you've linked to is using TypeScript, which is a different language from JavaScript: It's a superset of JavaScript (which compiles to JavaScript) that adds static typing (and a couple of other features, like automatic property initialization in constructors).

This TypeScript line:

var ItemsArray : ItemModel[];

is equivalent to this JavaScript:

var ItemsArray;

It's just that the TypeScript version declares that the ItemsArray variable has the static type ItemModel[].

If you're using JavaScript itself, you don't define the types of variables. Your export var ItemsArray = []; is just fine (other than that I'd use let or const instead of var).

Side Note: You can write that array more concisely in JavaScript using an array initializer:

export const ItemsArray = [
    new ItemModel(0, "BreakFast"),
    new ItemModel(1, "Lunch"),
    new ItemModel(2, "Dinner")
];

That's also valid TypeScript, even without a type declaration: TypeScript will infer that you want the type of ItemsArray to be ItemModel[] (because TypeScript does type inference and it can see that you're filling ItemsArray with ItemModel objects).

If you wanted to start with an empty array but still give it a static type, you'd do this:

//                                   /------ Telling TypeScript to use ItemModel[]
//                      vvvvvvvvvvvvv        as the type
export const ItemsArray : ItemModel[] = [];
//                                   ^^^^^-- Initializing ItemsArray with an
//                                           empty array

Then your push calls would be typechecked, so this would work:

ItemsArray.push(new ItemModel(0, "BreakFast"));

but this would cause an error (during TypeScript->JavaScript compilation)

ItemsArray.push("BreakFast");

because "Breakfast" is not compatible with ItemModel.

Side Note 2: The overwhelming convention in JavaScript (and TypeScript) is that variables start with a lowercase letter, not an uppercase one. So itemsArray rather than ItemsArray.


问:
Angular Material mat-ripple isn't working
I'm trying to add ripple effect to one button, but it crashes whole webpage.
When I just add matRipple to my button nothing happens. When I try to add color [matRippleColor]="white" I get "Can't bind to 'matRippleColor' since it isn't a known property of 'button'".

That strange because I enabled ripples on other page of website and it works just fine. (So yes, I've imported MatRippleModule):

HTML:

```<code><button  matRipple class="submit-button" color="accent" type="submit" >
  <mat-icon>search</mat-icon><span>Szukaj</span>
</button>
</code>```

答:
When you use [matRippleColor]="white", Angular evaluates "white" to a template expression. Since you have not defined a variable white in your component, this evaluates to undefined. If you want to pass the color white to the [matRippleColor], you need to pass it as a string like below

```<code><button matRipple [matRippleColor]="'white'" type="submit" class="submit-button">
    <mat-icon>search</mat-icon><span>Szukaj</span>
</button>
</code>```

The issue could also be with the version of @angular/material you are using. MatRippleModule works slightly differently for the different versions of @angular/material

MatRippleModule was introduced in Angular Material 6 so it will not work with versions 5 and below.

In Angular Material 6, the ripple overflows outside your element. This can be fixed by adding position: relative to your element CSS like below

```<code>.submit-button {
    position: relative;
}
</code>```

In Angular Material 7, the position: relative CSS property has been added to the .mat-ripple class of the library so it is not required to add position: relative to the element in your CSS. The same goes for Angular Material 8.

Here is a simple example on StackBlitz on Angular 7 where you can dynamically change the color. For a constant color, just change [matRippleColor]="rippleColor" to [matRippleColor]="'white'" or any color of your choice.

Body:
I'm trying to add ripple effect to one button, but it crashes whole webpage.
When I just add matRipple to my button nothing happens. When I try to add color [matRippleColor]="white" I get "Can't bind to 'matRippleColor' since it isn't a known property of 'button'".

That strange because I enabled ripples on other page of website and it works just fine. (So yes, I've imported MatRippleModule):

HTML:

<button  matRipple class="submit-button" color="accent" type="submit" >
  <mat-icon>search</mat-icon>Szukaj
</button>

Body:
When you use [matRippleColor]="white", Angular evaluates "white" to a template expression. Since you have not defined a variable white in your component, this evaluates to undefined. If you want to pass the color white to the [matRippleColor], you need to pass it as a string like below

<button matRipple [matRippleColor]="'white'" type="submit" class="submit-button">
    <mat-icon>search</mat-icon><span>Szukaj</span>
</button>

The issue could also be with the version of @angular/material you are using. MatRippleModule works slightly differently for the different versions of @angular/material

MatRippleModule was introduced in Angular Material 6 so it will not work with versions 5 and below.

In Angular Material 6, the ripple overflows outside your element. This can be fixed by adding position: relative to your element CSS like below

.submit-button {
    position: relative;
}

In Angular Material 7, the position: relative CSS property has been added to the .mat-ripple class of the library so it is not required to add position: relative to the element in your CSS. The same goes for Angular Material 8.

Here is a simple example on StackBlitz on Angular 7 where you can dynamically change the color. For a constant color, just change [matRippleColor]="rippleColor" to [matRippleColor]="'white'" or any color of your choice.


问:
ASP.NET Access Database Error?
I have written some code that uses an Access DB, on my localhost the following - Select, Insert, and Delete queries work just fine and do what I programmed them to do. When I move the application to the staging server, the application throws errors when Inserting and deleting, however the select statements work just fine. I have made sure all permissions are read/write as far as I can tell, does anyone know what I am missing. See the error below. </p>

<p>~~~~~ </p>

```<code>Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information about
the error and where it originated in the code.

Exception Details: System.Data.OleDb.OleDbException: Could not delete from
specified tables.

Source Error:
Line 714: OleDbDataReader objReader;
Line 715: objConn.Open();
Line 716: objReader = objCmd.ExecuteReader();
</code>```

答:
Seems like whatever account is utilizing the .mdb file does not have the necessary rights to the file/folder.

I've found that using an .mdb file for a website just has too many problems. You want to switch to at least SQL Express. You website will appreciate it.

LastEditorDisplayName: CodeSlave

Title: ASP.NET Access Database Error?

Body:
I have written some code that uses an Access DB, on my localhost the following - Select, Insert, and Delete queries work just fine and do what I programmed them to do. When I move the application to the staging server, the application throws errors when Inserting and deleting, however the select statements work just fine. I have made sure all permissions are read/write as far as I can tell, does anyone know what I am missing. See the error below.

~~~~~

Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information about
the error and where it originated in the code.

Exception Details: System.Data.OleDb.OleDbException: Could not delete from
specified tables.

Source Error:
Line 714: OleDbDataReader objReader;
Line 715: objConn.Open();
Line 716: objReader = objCmd.ExecuteReader();

OwnerDisplayName: Guiness