问:
Add props from parent component in map() function from child component
I have 2 components. Parent and child.
This is my child component:

import React, {useState, useEffect} from 'react';

const Users = (props) => {
    const [users, setUsers] = useState([]);
    let [respo, setA] = useState('name');
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://api.github.com/users/hadley/repos`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        setUsers(data)
        // console.log(res)
    };
    fetchData();
    function mapping() {
        return (
            users.map((i, k) =>
{i.props.details}
)
        )
    }

    return (

                {mapping()}

    );
};

export default Users;```
</div>
</div>
</p>

<p>In my parent component i send a prop to  child:</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> <Tabs type="card">
 <TabPane tab="Tab Title 1" key="1">
 <Users details="name"/>
 </TabPane>
<TabPane tab="Tab Title 2" key="2">
 <Users details="id"/>
 </TabPane>
 <TabPane tab="Tab Title 3" key="3">
</Tabs></code>```

I tried to access the props like here: users.map((i, k) =>
{i.props.details}
) Why i cant access  the props from parent in map() function?

答:
If I understand right, you're trying to access the property given in props.details of each user.

Doing i.props.details will look for a property called props on the user. Instead, you can use a computed property with bracket notation like this:

users.map((i, k) =>
{i[props.details]}
)

// If the prop.details is 'name' it will be equivalent to
users.map((i, k) =>
{i["name"]}
)
```

Body:
I have 2 components. Parent and child.
This is my child component:

import React, {useState, useEffect} from 'react';

const Users = (props) => {
    const [users, setUsers] = useState([]);
    let [respo, setA] = useState('name');
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://api.github.com/users/hadley/repos`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        setUsers(data)
        // console.log(res)
    };
    fetchData();
    function mapping() {
        return (
            users.map((i, k) =>
{i.props.details}
)
        )
    }

    return (

                {mapping()}

    );
};

export default Users;

In my parent component i send a prop to  child:

 <Tabs type="card">
 <TabPane tab="Tab Title 1" key="1">
 <Users details="name"/>
 </TabPane>
<TabPane tab="Tab Title 2" key="2">
 <Users details="id"/>
 </TabPane>
 <TabPane tab="Tab Title 3" key="3">
</Tabs>

I tried to access the props like here: users.map((i, k) =>
{i.props.details}
) Why i cant access  the props from parent in map() function?

Body:
If I understand right, you're trying to access the property given in props.details of each user.

Doing i.props.details will look for a property called props on the user. Instead, you can use a computed property with bracket notation like this:

users.map((i, k) => <li key={k}>{i[props.details]}</li>)

// If the prop.details is 'name' it will be equivalent to
users.map((i, k) => <li key={k}>{i["name"]}</li>)


来源: stackexchange

问:
Lazy Loading results in ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment:
I implement lazy loading and result into this error. I have seen many post and none of them are giving the solution.

How to reproduce:

Go to https://stackblitz.com/edit/angular-sxmpj8

Click on orders tab

Click Test

Expected: It opens Test component
Actual: It results into "Uncaught (in promise): Error: Cannot match any routes. URL Segment:" error

I am trying to lazy load the orders module which has two components orders and test. The orders route is working fine but the test component route throws error.

The application is at https://stackblitz.com/edit/angular-sxmpj8

At orders-routing.module.ts the routes are defined as below:

```<code>    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];
</code>```

The routes at app-routing.module.ts are defined as below.

```<code>const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];
</code>```

In orders.component.ts file I have an entry

```<code><button routerLink="/test">Test</button>
</code>```

Clicking this result into error

ERROR
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'

答:
First the routerLink should be a relative path, otherwise it will go to the root of the app, and there is no /test path defined at the app routes.
A relative path in a routerLink is relative to the current router-outlet the routerLink is defined in.

Second, the orders.component.html also needs a <router-outlet></router-outlet>, otherwise the test component won't be placed anywhere.

Something like this:

```<code><button routerLink="test">Test</button>
<router-outlet></router-outlet>
</code>```

working example

ContentLicense: CC BY-SA 4.0

Body:
I implement lazy loading and result into this error. I have seen many post and none of them are giving the solution.

How to reproduce:

Go to https://stackblitz.com/edit/angular-sxmpj8

Click on orders tab

Click Test

Expected: It opens Test component
Actual: It results into "Uncaught (in promise): Error: Cannot match any routes. URL Segment:" error

I am trying to lazy load the orders module which has two components orders and test. The orders route is working fine but the test component route throws error.

The application is at https://stackblitz.com/edit/angular-sxmpj8

At orders-routing.module.ts the routes are defined as below:

    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];

The routes at app-routing.module.ts are defined as below.

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

In orders.component.ts file I have an entry

<button routerLink="/test">Test</button>

Clicking this result into error

ERROR
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'

Body:
First the routerLink should be a relative path, otherwise it will go to the root of the app, and there is no /test path defined at the app routes.
A relative path in a routerLink is relative to the current router-outlet the routerLink is defined in.

Second, the orders.component.html also needs a <router-outlet></router-outlet>, otherwise the test component won't be placed anywhere.

Something like this:

<button routerLink="test">Test</button>
<router-outlet></router-outlet>

working example


问:
class name and then the tag name contains the distinguish text
I have class name active and then there is unique text called active text in span(which is nested). Class name active is the unique among other class names then nested text is unique. How would i click on that. I have used following methods.

```<code>  FindElement(By.XPath("//li[@class='active']//*[contains(.,'active text')]"));
</code>```

also i tried

```<code>  findelement(BY.xpath(//li[@class='active']//div//div//div//span[contains(.,'active text')]"))
</code>```

also tried this

```<code>  FindElement(By.XPath("//li[contains(@class,'active')] and //span[contains(.,'active text')]")).Text;
</code>```

Every time i get no such element found
ANythoughts
this is the html code

```<code><li class="active">
 <div class="a">
  <div class="b">
   <div class="c">
    <h1></h1>
     <h3 class="d"> some text</h3>
      <div class="e">
       <span class="f">
         Active Text</span>
</div></div></div></div>
</li>
</code>```

答:
```<code>FindElement(By.XPath("//li[@class='active']//span[contains(text(),'Active Text')]"));
</code>```

OR

```<code>FindElement(By.XPath("//li[@class='active']//span[@class='f' and contains(text(),'Active Text')]"));
</code>```

Please try the above code. both will work. also, let me know if clarification is required

Body:
I have class name active and then there is unique text called active text in span(which is nested). Class name active is the unique among other class names then nested text is unique. How would i click on that. I have used following methods.

  FindElement(By.XPath("//li[@class='active']//*[contains(.,'active text')]"));

also i tried

  findelement(BY.xpath(//li[@class='active']//div//div//div//span[contains(.,'active text')]"))

also tried this

  FindElement(By.XPath("//li[contains(@class,'active')] and //span[contains(.,'active text')]")).Text;

Every time i get no such element found
ANythoughts
this is the html code

 some text

         Active Text

Body:
FindElement(By.XPath("//li[@class='active']//span[contains(text(),'Active Text')]"));

OR

FindElement(By.XPath("//li[@class='active']//span[@class='f' and contains(text(),'Active Text')]"));

Please try the above code. both will work. also, let me know if clarification is required


问:
using asp.net mvc for REST based endpoint
I'm looking at using ASP.Net MVC as a platform for a REST based Service. I know WCF has built in support for REST services; however, I'm looking at returning multiple types of data depending on the request.

I would like the client to request the content type. So if they send text/html for example I would render my model into Html, if they request text/xml it would return xml. We could also do JSON.

Does anyone see any issues with this?

Not using WCF could increase the complexity of the client when calling the service since they won't be able to auto-generate a proxy; however, in my case, the clients will be either browser requesting html, or java client libraries processing the xml.

Since were not using WCF we need to secure the service; however, I'm thinking we can do this using forms authentication.

The benefit of this is that no matter what type of data the client is requesting it is all going through the same controllers / models etc...

答:
After reading Haack's post, about using extensions to indicate the content type, I think your better off keying off the Accept Header. Seems more Rest'ish to me, although granted its a little more difficult to fire up a browser and test your url.

I through together a little blog article about doing this and using a ModelBinder to abstract out the HttpContext from your controller: http://jberke.blogspot.com/2009/03/aspnet-mvc-model-binder.html.

Additionally in response to Troy's opt-in comment, I was using the view to render Xml of my model. This allowed me to have different xml formats for the same model. Which makes sense. What if you need to support versioning or different formats for different clients. I don't like the idea of the framework automatically rendering anything.

OwnerDisplayName: Josh

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Fabian Steeg


问:
How to test my app in 1.6 android
I'm trying to test my app in the 1.6 platform, but I can't even choose an emulator from the devices list in Run Configurations. Here's my Manifest:

```<code><uses-sdk android:targetSdkVersion="8"
android:minSdkVersion="4"/>
</code>```

I don't see why I'm unable to choose an emulator which is set up for 1.6. What am I missing here?

答:
It seems like you haven't posted the manifest.

In order to run emulator 1.6, go to Run->Run Configurations->Target and select "Manual" instead of "Automatic".

That way Eclipse will prompt you which emulator you want.

ContentLicense: CC BY-SA 3.0

Title: How to test my app in 1.6 android

Body:
I'm trying to test my app in the 1.6 platform, but I can't even choose an emulator from the devices list in Run Configurations. Here's my Manifest:

<uses-sdk android:targetSdkVersion="8"
android:minSdkVersion="4"/>

I don't see why I'm unable to choose an emulator which is set up for 1.6. What am I missing here?


问:
Is storing project configuration in environment variables a bad practice?
Some background first:
i am currently testing a class that sends a GET request with a configurable url, which is built like this

```<code>url = f"{os.environ["TARGET_URL"]}/api/etc"
</code>```

For normal operation, my TARGET_URL environment variable is set at project startup from a .env file and everything works. When testing locally, everything is still fine, tests passes and everyone is happy. My issue arose when I discovered that my Drone CI server failed to complete the project's build because the TARGET_URL environment variable wasn't found.

After some digging I found out that I had the wrong (dumb) idea that environment variables were reset at every project/test startup, and I basically was using my production environment variable all this time (even during tests) because it was set at first project startup.

From this story comes my question: given that environment variables are kept between executions, would storing configurations in them result in a bad practice? Is there an equally convenient alternative (no global objects and access from everywhere in the code) that can be used instead?

答:
Thanks everyone for the quick responses, here's a bit of what-happened-next:

environment variables stay loaded after the first initialization, so I needed a way to test my code after loading only the variables I needed, with values that were expected. This would allow me to keep using environment variables loaded from a .env file and keep building my project remotely, where no .env files are present.

The solution was to add a pytest plugin called pytest-dotenv, which when properly configured would allow me to overwrite every variable in my .env files with a custom variable from another file (.env.test in my case). I filled the .env.test file with all the variables found in the .env file, and assigned empty values to each of them.
This allowed my tests to run ensuring no weird edge cases are missed because something had the wrong value.

example .env file

```<code>TARGET_URL="http://my.api.dev
</code>```

example .env.test file

```<code>TARGET_URL=
</code>```

pytest.ini configuration

```<code>[pytest]
env_override_existing_values = 1
env_files =
    .env.test
</code>```

Body:
Some background first:
i am currently testing a class that sends a GET request with a configurable url, which is built like this

url = f"{os.environ["TARGET_URL"]}/api/etc"

For normal operation, my TARGET_URL environment variable is set at project startup from a .env file and everything works. When testing locally, everything is still fine, tests passes and everyone is happy. My issue arose when I discovered that my Drone CI server failed to complete the project's build because the TARGET_URL environment variable wasn't found.

After some digging I found out that I had the wrong (dumb) idea that environment variables were reset at every project/test startup, and I basically was using my production environment variable all this time (even during tests) because it was set at first project startup.

From this story comes my question: given that environment variables are kept between executions, would storing configurations in them result in a bad practice? Is there an equally convenient alternative (no global objects and access from everywhere in the code) that can be used instead?

Body:
Thanks everyone for the quick responses, here's a bit of what-happened-next:

environment variables stay loaded after the first initialization, so I needed a way to test my code after loading only the variables I needed, with values that were expected. This would allow me to keep using environment variables loaded from a .env file and keep building my project remotely, where no .env files are present.

The solution was to add a pytest plugin called pytest-dotenv, which when properly configured would allow me to overwrite every variable in my .env files with a custom variable from another file (.env.test in my case). I filled the .env.test file with all the variables found in the .env file, and assigned empty values to each of them.
This allowed my tests to run ensuring no weird edge cases are missed because something had the wrong value.

example .env file

TARGET_URL="http://my.api.dev

example .env.test file

TARGET_URL=

pytest.ini configuration

[pytest]
env_override_existing_values = 1
env_files =
    .env.test


问:
Replace ISO-Date with normal Date in HTML Document via Widget
my problem is the following . Im using Duda widget Builder to build my own Widgets. In one application there is a Date and by default its depicted as ISO .
Now converting that isnt too hard, I tried the following :

if (document.getElementById("date") !== null) {
  let date = document.getElementById("date").toString();
  let dater = date.substring(0, 10);
  document.getElementById("date").innerHTML.replace(date, dater);
  console.log('Test');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Wrapper shadow">
  <h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div></code>```

Now it doesnt throw any errors and it console.logs the "Test". But the date stays in ISO.

The widget works with jQuery I believe it has something to do with that.
The widget interface where you write down the javascript is encapsulated by this: function(element,data,api){ 'my js code from above'}
Please help.

答:
The issue is because you never update the content of the element after working with the content. Also note that you don't need to use replace(). Try this:

let el = document.getElementById("date");
if (el) {
  el.textContent = el.textContent.substring(0, 10);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Wrapper shadow">
  <h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div></code>```

That being said, you're just getting the first 10 characters of the date string, which is not infallible. If the locale changes your code will break. To fix this you can create a Date object from the string and output the format you require explicitly:

let el = document.getElementById("date");
if (el) {
  let date = new Date(el.textContent);
  let year = date.getFullYear();
  let month = ("00" + (date.getMonth() + 1)).slice(-2);
  let day = ("00" + date.getDate()).slice(-2);
  el.textContent = `${year}-${month}-${day}`;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Wrapper shadow">
  <h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div></code>```

Body:
my problem is the following . Im using Duda widget Builder to build my own Widgets. In one application there is a Date and by default its depicted as ISO .
Now converting that isnt too hard, I tried the following :

if (document.getElementById("date") !== null) {
  let date = document.getElementById("date").toString();
  let dater = date.substring(0, 10);
  document.getElementById("date").innerHTML.replace(date, dater);
  console.log('Test');
}

2020-02-20T14:39:40Z

Now it doesnt throw any errors and it console.logs the "Test". But the date stays in ISO.

The widget works with jQuery I believe it has something to do with that.
The widget interface where you write down the javascript is encapsulated by this: function(element,data,api){ 'my js code from above'}
Please help.

Body:
The issue is because you never update the content of the element after working with the content. Also note that you don't need to use replace(). Try this:

let el = document.getElementById("date");
if (el) {
  el.textContent = el.textContent.substring(0, 10);
}

<div class="Wrapper shadow">
  <h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>

That being said, you're just getting the first 10 characters of the date string, which is not infallible. If the locale changes your code will break. To fix this you can create a Date object from the string and output the format you require explicitly:

let el = document.getElementById("date");
if (el) {
  let date = new Date(el.textContent);
  let year = date.getFullYear();
  let month = ("00" + (date.getMonth() + 1)).slice(-2);
  let day = ("00" + date.getDate()).slice(-2);
  el.textContent = `${year}-${month}-${day}`;
}

<div class="Wrapper shadow">
  <h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>


问:
ADFS OrganizationalAccountSuffix wildcard workaround
In our ADFS 3.0 environment, we got a relying party trust with 2 claims provider trust. We activated the Home Realm Discovery. Our need is to redirect users based on their email.

The problem is as follows: the first Claims Provider should accept users from *@domain.com, this works great. The second one is more tricky. We want the second CPT to accept all the others suffixes, but as Microsoft states on their documentation, the 'OrganizationalAccountSuffix' parameter of the 'Set-AdfsClaimsProviderTrust' command does not accept wildcard : https://learn.microsoft.com/en-us/powershell/module/adfs/set-adfsclaimsprovidertrust?view=win10-ps#parameters

The question is: is there a workaround in order to redirect all users that have in their email addresses a suffix different from domain.com to the second CPT?

Thanks.

答: This link provides a great workaround : https://learn.microsoft.com/en-us/archive/blogs/pie/customize-the-home-realm-discovery-page-to-ask-for-upn-right-away</p>


问:
Update with filter on timestamp
After somes years without sql oracle activity...I'm trying to update somes status code by date on oracle SQL.
date is in french format DD/MM/YYYY

The format on date_start column is timestamp with this format " 18/10/2019 23:15:26" and i need filter on date -1 month. And working with sqlplus...

i think like this :

```<code>UPDATE contexte_ihm
SET set status_code =1000 status_name = (select FLUX_STATUS_NAME from flux_status_ref where FLUX_STATUS_CD=1000)
WHERE status_code=9999
AND DATE_START = TO_TIMESTAMP( '31/01/2000 08-00-00', 'DD/MM/YYYY HH24-MI-SS' )
</code>```

i tried this:

```<code>SELECT * FROM contexte_ihm WHERE status_code =1000 AND DATE_START =to_date('19/12/2019','dd/mm/yyyy')
  2  ;

no rows selected
</code>```

With <NOW()-30 NOW is invalid identifier...

I need update 95000 rows from one month ago to older date...

答:
It sounds like you want a range of dates.  I think:

```<code>WHERE status_code = 9999 AND
      date_start < trunc(sysdate, 'MON') - interval '1 month' and
      date_start >= timestamp '2000-01-31 08:00:00';
</code>```

You should test the WHERE clause on a SELECT to be sure it gets the right rows.

Title: Update with filter on timestamp

Body:
After somes years without sql oracle activity...I'm trying to update somes status code by date on oracle SQL.
date is in french format DD/MM/YYYY

The format on date_start column is timestamp with this format " 18/10/2019 23:15:26" and i need filter on date -1 month. And working with sqlplus...

i think like this :

UPDATE contexte_ihm
SET set status_code =1000 status_name = (select FLUX_STATUS_NAME from flux_status_ref where FLUX_STATUS_CD=1000)
WHERE status_code=9999
AND DATE_START = TO_TIMESTAMP( '31/01/2000 08-00-00', 'DD/MM/YYYY HH24-MI-SS' )

i tried this:

SELECT * FROM contexte_ihm WHERE status_code =1000 AND DATE_START =to_date('19/12/2019','dd/mm/yyyy')
  2  ;

no rows selected

With <NOW()-30 NOW is invalid identifier...

I need update 95000 rows from one month ago to older date...

Body:
It sounds like you want a range of dates.  I think:

WHERE status_code = 9999 AND
      date_start < trunc(sysdate, 'MON') - interval '1 month' and
      date_start >= timestamp '2000-01-31 08:00:00';

You should test the WHERE clause on a SELECT to be sure it gets the right rows.


问:
Count function with time condition
I have a database similar to the following. I'm looking to count the appointed, emergency and surveyor job types that occured in working hours. Also counting the No Access and Follow On Event Summary.

The criteria is that the jobs we are looking for are ArrivedDAY NOT IN ('Saturday','Sunday) and if its a monday to friday job that the ArrTime is betweeen 08:00:00 - 16:30:00

I've managed to get the count part down but excluding the data i don't need is proving to be difficult, a point in the right direction would be appreciated.

This is on the SQL Server Studio

Cheers
Matt

答:
I believe you're looking for conditional aggregation.</p>

```<code>SELECT
  Operative,
  SUM(CASE WHEN JobType = 'APPOINTED' THEN 1 ELSE 0 END) AS Appointed,
  SUM(CASE WHEN JobType = 'EMERGENCY' THEN 1 ELSE 0 END) AS Emergency,
  SUM(CASE WHEN JobType = 'SURVEYOR' THEN 1 ELSE 0 END) AS Surveyor,
  COUNT(JobNumber) AS TotalJobs,
  SUM(CASE WHEN EventSummary = 'No Access' THEN 1 ELSE 0 END) AS NoAccess,
  SUM(CASE WHEN EventSummary = 'Follow On' THEN 1 ELSE 0 END) AS FollowOn
FROM
  Tbl
WHERE
  ArrivedDAY <> 'Saturday'
  AND ArrivedDAY <> 'Sunday'
  AND ArrTime >= '08:00:00'
  AND ArrTime <= '16:30:00'
GROUP BY
  Operative;
</code>```

Title: Count function with time condition

Body:
I believe you're looking for conditional aggregation.

SELECT
  Operative,
  SUM(CASE WHEN JobType = 'APPOINTED' THEN 1 ELSE 0 END) AS Appointed,
  SUM(CASE WHEN JobType = 'EMERGENCY' THEN 1 ELSE 0 END) AS Emergency,
  SUM(CASE WHEN JobType = 'SURVEYOR' THEN 1 ELSE 0 END) AS Surveyor,
  COUNT(JobNumber) AS TotalJobs,
  SUM(CASE WHEN EventSummary = 'No Access' THEN 1 ELSE 0 END) AS NoAccess,
  SUM(CASE WHEN EventSummary = 'Follow On' THEN 1 ELSE 0 END) AS FollowOn
FROM
  Tbl
WHERE
  ArrivedDAY <> 'Saturday'
  AND ArrivedDAY <> 'Sunday'
  AND ArrTime >= '08:00:00'
  AND ArrTime <= '16:30:00'
GROUP BY
  Operative;


答:
Give this a go, with a bit of guesswork as to your structure.
You could then pivot the results to get the job type as column names</p>

```<code>select
 operative
,jobtype
,count(*) as [count]

from jobs --replace with your table name

where arrivedday not in ('Saturday','Sunday') --alternatively use where weekday(arriveddate) not in (1,7)

and datepart(hour,arrtime) > 8
and (datepart(hour,arrtime) < 17 and datepart(minute,artime) <= 30)

group by
 operative
,jobtype

</code>```

Title: Count function with time condition

Body:
I have a database similar to the following. I'm looking to count the appointed, emergency and surveyor job types that occured in working hours. Also counting the No Access and Follow On Event Summary.

The criteria is that the jobs we are looking for are ArrivedDAY NOT IN ('Saturday','Sunday) and if its a monday to friday job that the ArrTime is betweeen 08:00:00 - 16:30:00

I've managed to get the count part down but excluding the data i don't need is proving to be difficult, a point in the right direction would be appreciated.

This is on the SQL Server Studio

Cheers
Matt

Body:
Give this a go, with a bit of guesswork as to your structure.
You could then pivot the results to get the job type as column names

select
 operative
,jobtype
,count(*) as [count]

from jobs --replace with your table name

where arrivedday not in ('Saturday','Sunday') --alternatively use where weekday(arriveddate) not in (1,7)

and datepart(hour,arrtime) > 8
and (datepart(hour,arrtime) < 17 and datepart(minute,artime) <= 30)

group by
 operative
,jobtype


问:
How to run WorkManager's work retry every 5 seconds
How to retry work with every 5 seconds?
And if was successful then cancel it?

With the solution below it runs every 10 seconds + Linear growth of time.

```<code>// todo: schedule, and invoke worker every 5 seconds
// todo: if the work is done and there is no more work in queue - cancel worker.

fun scheduleBatchUpload(uniqueWorkName: String) {
    val logBuilder = PeriodicWorkRequest.Builder(StreamLogWorker::class.java, 5, TimeUnit.SECONDS)

    logBuilder.setBackoffCriteria(BackoffPolicy.LINEAR, 5000, TimeUnit.MILLISECONDS) // Custom retry not working

    WorkManager.getInstance().enqueueUniquePeriodicWork(uniqueWorkName, ExistingPeriodicWorkPolicy.REPLACE, logBuilder.build())
}

class StreamLogWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        Log.e("!!!!!!!!!!", "doWork")
        return Result.retry()
    }
}
</code>```

答:
That is not possible with the PeriodicWorkRequest. if you look at documentation of the the PeriodicWorkRequest.Builder constructor that you are using, you will see that it says following about the second parameter

The repeat interval must be greater than or equal to
  PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS.

And the value of PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS is 900000, meaning it is equal to 15 minutes.

Body:
How to retry work with every 5 seconds?
And if was successful then cancel it?

With the solution below it runs every 10 seconds + Linear growth of time.

// todo: schedule, and invoke worker every 5 seconds
// todo: if the work is done and there is no more work in queue - cancel worker.

fun scheduleBatchUpload(uniqueWorkName: String) {
    val logBuilder = PeriodicWorkRequest.Builder(StreamLogWorker::class.java, 5, TimeUnit.SECONDS)

    logBuilder.setBackoffCriteria(BackoffPolicy.LINEAR, 5000, TimeUnit.MILLISECONDS) // Custom retry not working

    WorkManager.getInstance().enqueueUniquePeriodicWork(uniqueWorkName, ExistingPeriodicWorkPolicy.REPLACE, logBuilder.build())
}

class StreamLogWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        Log.e("!!!!!!!!!!", "doWork")
        return Result.retry()
    }
}


问:
Is there any way to display a raw image in python?
I want to display the raw image in RGB565-Big Endian or gray 16 bit Big-Endian. The result of this code is little-Endian</p>

```<code>from cv2 import cv2
import numpy as np
import sys
from struct import *

fd = open('path', 'rb')
rows = 360
cols = 640
f = np.fromfile(fd, dtype=np.int16,count=rows*cols)
im = f.reshape((rows, cols)) #notice row, column format
fd.close()

print(fd)

cv2.imshow('', im)
cv2.waitKey()
cv2.destroyAllWindows()
</code>```

答:
from https://docs.scipy.org/doc/numpy/user/basics.byteswapping.html

replace your dtype in line 11 with:

```<code>dtype='>i2'
</code>```

> stands for big endian

i stands for integer

2 stands for 2 bytes

Body:
I want to display the raw image in RGB565-Big Endian or gray 16 bit Big-Endian. The result of this code is little-Endian

from cv2 import cv2
import numpy as np
import sys
from struct import *

fd = open('path', 'rb')
rows = 360
cols = 640
f = np.fromfile(fd, dtype=np.int16,count=rows*cols)
im = f.reshape((rows, cols)) #notice row, column format
fd.close()

print(fd)

cv2.imshow('', im)
cv2.waitKey()
cv2.destroyAllWindows()

Body:
from https://docs.scipy.org/doc/numpy/user/basics.byteswapping.html

replace your dtype in line 11 with:

dtype='>i2'

> stands for big endian

i stands for integer

2 stands for 2 bytes


问:
Android application crash while trying to write file
I have some data and write them to file. But my application  keeps crashing. I tried so many things but it doesn't fixed.

Here is my code for it.

```<code>private void logInValidator(String userName, SimpleCallback<Boolean> finishedCallback) {

        DatabaseReference rootRef = databaseManager.getReference();
        DatabaseReference usersRef = rootRef.child("user");
        Query queryUsernameFinder = usersRef.orderByKey().equalTo(userName);
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    user = ds.getValue(User.class);
                }
                String passHash = null;
                passHash = Objects.requireNonNull(user).getPasswordHash();

                try {
                    validated = PasswordHandler.validatePassword(password, Objects.requireNonNull(passHash));
                } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                    e.printStackTrace();
                } finally {
                    finishedCallback.run(validated); // send the result to the callback
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
                finishedCallback.run(false);
            }
        };
        queryUsernameFinder.addListenerForSingleValueEvent(valueEventListener);
    }
</code>```

This code finds if username exists in my database.

```<code>private void validateCredentials(){
        if (PermissionChecker.checkInternetPermission(this)) {
            if (!EmptyChecker.isEmpty(usernameTextInputLayout) && !EmptyChecker.isEmpty(passwordTextInputLayout)) {
                password = Objects.requireNonNull(passwordTextInputLayout.getEditText()).getText().toString();
                userName = Objects.requireNonNull(usernameTextInputLayout.getEditText()).getText().toString();
                logInValidator(userName, (success) -> {
                    if (success) {
                        String textToWrite = getTextToWrite();
                        writeToFile.write("UserData.txt",textToWrite);

                        //Intent mainIntent = new Intent(LogInActivity.this, MainActivity.class);
                        //startActivity(mainIntent);
                    } else {
                        showResult.setText(getString(userNotFound));
                    }
                });
            } else {
                showResult.setText(getString(string.emptyField));
            }
        } else
            PermissionChecker.requestInternetPermission(TestActivity.this,ContextGetter.getAppContext());
    }
</code>```

This code checks if username and passwords matches or not.

```<code>public class WriteToFile extends AppCompatActivity {

    public void write(String fileName, String textToWrite) {
        //Checking the availability state of the External Storage.
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            if (PermissionChecker.checkInternetPermission(ContextGetter.getAppContext())) {
                File dir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
                dir.mkdir(); // When application come this line app crashes
                File file = new File(dir, fileName);
                FileOutputStream os;
                try {
                    os = new FileOutputStream(file);
                    os.write(textToWrite.getBytes());
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                PermissionChecker.requestFilePermission(WriteToFile.this,ContextGetter.getAppContext()); // Code for permission
            }
        } else {
            Toast.makeText(ContextGetter.getAppContext(), "Can't write to File", Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

This code handles for file writing operations. I made a debug to solve problem. I find when debugger come to "dir.mkdir()" line applications crashes. I think this can cause because of sync issue. But I couldn't find it or fix it.

And this is the my logcat.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.track.medicine, PID: 6098
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getExternalFilesDir(java.lang.String)' on a null object reference
        at android.content.ContextWrapper.getExternalFilesDir(ContextWrapper.java:249)
        at com.track.medicine.WriteToFile.write(WriteToFile.java:20)
        at com.track.medicine.TestActivity.lambda$validateCredentials$2$TestActivity(TestActivity.java:110)
        at com.track.medicine.-$$Lambda$TestActivity$RQ_IhdpryAE_sEsi6RtMvH3Py8Q.run(Unknown Source:4)
        at com.track.medicine.TestActivity$1.onDataChange(TestActivity.java:90)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.2.1:179)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

答:
public class WriteToFile extends AppCompatActivity {

public void write

And then you call writeToFile.write("UserData.txt",textToWrite);

It looks as if you have created an instance of your activity with new.

That is not allowed for activities. They have to be started using an intent.

And your extended activity class cannot have public members like you do with public void write.

Body:
I have some data and write them to file. But my application  keeps crashing. I tried so many things but it doesn't fixed.

Here is my code for it.

private void logInValidator(String userName, SimpleCallback<Boolean> finishedCallback) {

        DatabaseReference rootRef = databaseManager.getReference();
        DatabaseReference usersRef = rootRef.child("user");
        Query queryUsernameFinder = usersRef.orderByKey().equalTo(userName);
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    user = ds.getValue(User.class);
                }
                String passHash = null;
                passHash = Objects.requireNonNull(user).getPasswordHash();

                try {
                    validated = PasswordHandler.validatePassword(password, Objects.requireNonNull(passHash));
                } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                    e.printStackTrace();
                } finally {
                    finishedCallback.run(validated); // send the result to the callback
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
                finishedCallback.run(false);
            }
        };
        queryUsernameFinder.addListenerForSingleValueEvent(valueEventListener);
    }

This code finds if username exists in my database.

private void validateCredentials(){
        if (PermissionChecker.checkInternetPermission(this)) {
            if (!EmptyChecker.isEmpty(usernameTextInputLayout) && !EmptyChecker.isEmpty(passwordTextInputLayout)) {
                password = Objects.requireNonNull(passwordTextInputLayout.getEditText()).getText().toString();
                userName = Objects.requireNonNull(usernameTextInputLayout.getEditText()).getText().toString();
                logInValidator(userName, (success) -> {
                    if (success) {
                        String textToWrite = getTextToWrite();
                        writeToFile.write("UserData.txt",textToWrite);

                        //Intent mainIntent = new Intent(LogInActivity.this, MainActivity.class);
                        //startActivity(mainIntent);
                    } else {
                        showResult.setText(getString(userNotFound));
                    }
                });
            } else {
                showResult.setText(getString(string.emptyField));
            }
        } else
            PermissionChecker.requestInternetPermission(TestActivity.this,ContextGetter.getAppContext());
    }

This code checks if username and passwords matches or not.

public class WriteToFile extends AppCompatActivity {

    public void write(String fileName, String textToWrite) {
        //Checking the availability state of the External Storage.
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            if (PermissionChecker.checkInternetPermission(ContextGetter.getAppContext())) {
                File dir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
                dir.mkdir(); // When application come this line app crashes
                File file = new File(dir, fileName);
                FileOutputStream os;
                try {
                    os = new FileOutputStream(file);
                    os.write(textToWrite.getBytes());
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                PermissionChecker.requestFilePermission(WriteToFile.this,ContextGetter.getAppContext()); // Code for permission
            }
        } else {
            Toast.makeText(ContextGetter.getAppContext(), "Can't write to File", Toast.LENGTH_SHORT).show();
        }
    }
}

This code handles for file writing operations. I made a debug to solve problem. I find when debugger come to "dir.mkdir()" line applications crashes. I think this can cause because of sync issue. But I couldn't find it or fix it.

And this is the my logcat.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.track.medicine, PID: 6098
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getExternalFilesDir(java.lang.String)' on a null object reference
        at android.content.ContextWrapper.getExternalFilesDir(ContextWrapper.java:249)
        at com.track.medicine.WriteToFile.write(WriteToFile.java:20)
        at com.track.medicine.TestActivity.lambda$validateCredentials$2$TestActivity(TestActivity.java:110)
        at com.track.medicine.-$$Lambda$TestActivity$RQ_IhdpryAE_sEsi6RtMvH3Py8Q.run(Unknown Source:4)
        at com.track.medicine.TestActivity$1.onDataChange(TestActivity.java:90)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.2.1:179)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)


问:
Intelij IDEA ssh-key git repository connection denied
I couldn't find issue like mine with a solve so I need your help.

In Git Bash I can get access with ssh git@specifiedip

I added public key to GitHub and I can get answer with ssh -T git@github.com
Hi username! You've successfully authenticated ...

I get my SSH-Key generated with PuTTy Gen.
My .ssh folder contains id-rsa and id-rsa.pub files.
I added IdentityFile ~/.ssh/id_dsa to my ssh-config file.

I can clone repository with Git Bash, but I cant clone it with simple git command ie. in intelij IDEA console.

But I can't clone my repository in IntelliJ.
It shows SSH Keyboard Interactive with a Password field. I really don't know what can cause it, and how to make IntelliJ read my ssh-keys...

Password field

After test error field

答:
Configure the SSH executable as "Native"

https://intellij-support.jetbrains.com/hc/user_images/0U1soQH33wre6Fs7piKLaQ.png

If that doesnt work then you can try this also

In the "C:\ Program Files\Git\ cmd" folder you will find the file "start-ssh-pageant.cmd"

Before launching it is necessary to create an environment variable:
Name: SSH_AUTH_SOCK
Value: C: \ Users \ username \ .ssh \ .ssh-pageant-username


问:
Reorder array of objects based on array of strings?
I have the following data structures:

```<code>const fieldOrder = [
  'title',
  'first_name',
  'last_name',
  'address_1',
  'address_2',
  'city',
  'state',
  'zipcode',
  'country',
]

const fields = [
  {
    name: 'first_name',
    value: 'John'
  },
  {
    name: 'title',
    value: 'Mr'
  }
  ...etc
]
</code>```

And I'd like to reorder the fields array of objects based on the position of the name key in the fieldOrder array. How is this possible? Perhaps with the Array.sort method somehow?

And, generally speaking, is this the best way to represent order?

答:
You could create object from the field order array and then use sort method to sort based on the values from that object that will be index of current element in the order array.

const fieldOrder = [
  'title',
  'first_name',
  'last_name',
  'address_1',
  'address_2',
  'city',
  'state',
  'zipcode',
  'country',
].reduce((r, e, i) => {
  r[e] = i;
  return r
}, {})

const fields = [{
    name: 'first_name',
    value: 'John'
  },
  {
    name: 'title',
    value: 'Mr'
  }
].sort((a, b) => fieldOrder[a.name] - fieldOrder[b.name])

console.log(fields)```

Body:
I have the following data structures:

const fieldOrder = [
  'title',
  'first_name',
  'last_name',
  'address_1',
  'address_2',
  'city',
  'state',
  'zipcode',
  'country',
]

const fields = [
  {
    name: 'first_name',
    value: 'John'
  },
  {
    name: 'title',
    value: 'Mr'
  }
  ...etc
]

And I'd like to reorder the fields array of objects based on the position of the name key in the fieldOrder array. How is this possible? Perhaps with the Array.sort method somehow?

And, generally speaking, is this the best way to represent order?


答:
try this:

```<code><button routerLink="/orders">Test</button>
</code>```

and after modify this in order-routing module:

```<code>const routes: Routes = [
  {
    path: '',
    component: OrdersComponent
  }
]
  }
];
</code>```

Title: Lazy Loading results in ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment:

Body:
I implement lazy loading and result into this error. I have seen many post and none of them are giving the solution.

How to reproduce:

Go to https://stackblitz.com/edit/angular-sxmpj8

Click on orders tab

Click Test

Expected: It opens Test component
Actual: It results into "Uncaught (in promise): Error: Cannot match any routes. URL Segment:" error

I am trying to lazy load the orders module which has two components orders and test. The orders route is working fine but the test component route throws error.

The application is at https://stackblitz.com/edit/angular-sxmpj8

At orders-routing.module.ts the routes are defined as below:

    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];

The routes at app-routing.module.ts are defined as below.

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

In orders.component.ts file I have an entry

<button routerLink="/test">Test</button>

Clicking this result into error

ERROR
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'

Body:
try this:

<button routerLink="/orders">Test</button>

and after modify this in order-routing module:

const routes: Routes = [
  {
    path: '',
    component: OrdersComponent
  }
]
  }
];


问:
Use Darcula LAF in JFrame
I have the Darcula LAF installed in Netbeans, and it is functional. It modifies the way the IDE looks as well as the way applications look in the 'Preview Design' popup and the GUI Builder.

Here is an example.

However, the look and feel doesn't stay when running the application.

Here is an example.

The installed look and feels are listed using this code

```<code>for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            System.out.println(info.getName());
        }
</code>```

Clearly, the Darcula LaF is installed. However, it isn't showing up as installed to the compiler. Is there a way for me to get the LaF for the compiler while maintaining the Netbeans module?

I have looked on the download page, the GitHub page, and even Geertjan's blog for information on the subject, have found nothing related to this.

I'm sure that I'm missing something painfully obvious. Not setting the look and feel has it default to metal, and using the OS default look and feel doesn't resolve the issue, either.

All help is appreciated, I apologize if this is incorrectly formatted.

EDIT: It is only set to Nimbus in the code for clarity. Have some screenshots of how it reacts when it isn't set to Nimbus. It defaults to metal.
I have removed the code that sets it to Nimbus before, and it uses Metal. http://prntscr.com/bte2xg
I have set it to use "Darcula" rather than Nimbus in the past, and yet it still uses Metal. http://prntscr.com/bte2b5

I have set it to use "darcula-1.0.0" rather than Nimbus in the past, and yet it still uses Metal. http://prntscr.com/bte3nh

I have set it to use "darcula-1.0.0.jar" rather than Nimbus in the past, and yet it still uses Metal.  http://prntscr.com/bte42m

I have set it to use "com.bulenkov.darcula" in the past, and yet it still uses Metal. http://prntscr.com/bte3du

I merely left Nimbus in there for the sake of it appearing in something presentable.

答:
add darcula.jar in your Library;
then import com.bulenkov.darcula.DarculaLaf in your source file
after that

```<code>for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    System.out.println(info.getName());
    if ("Nimbus".equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(new DarculaLaf());
        break;
    }
}
</code>```

make sure your ticked "Copy Dependented Libraries" in your Project Properties-> Packaging Tab.

Title: Use Darcula LAF in JFrame

Body:
I have the Darcula LAF installed in Netbeans, and it is functional. It modifies the way the IDE looks as well as the way applications look in the 'Preview Design' popup and the GUI Builder.

Here is an example.

However, the look and feel doesn't stay when running the application.

Here is an example.

The installed look and feels are listed using this code

for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            System.out.println(info.getName());
        }

Clearly, the Darcula LaF is installed. However, it isn't showing up as installed to the compiler. Is there a way for me to get the LaF for the compiler while maintaining the Netbeans module?

I have looked on the download page, the GitHub page, and even Geertjan's blog for information on the subject, have found nothing related to this.

I'm sure that I'm missing something painfully obvious. Not setting the look and feel has it default to metal, and using the OS default look and feel doesn't resolve the issue, either.

All help is appreciated, I apologize if this is incorrectly formatted.

EDIT: It is only set to Nimbus in the code for clarity. Have some screenshots of how it reacts when it isn't set to Nimbus. It defaults to metal.
I have removed the code that sets it to Nimbus before, and it uses Metal. http://prntscr.com/bte2xg
I have set it to use "Darcula" rather than Nimbus in the past, and yet it still uses Metal. http://prntscr.com/bte2b5

I have set it to use "darcula-1.0.0" rather than Nimbus in the past, and yet it still uses Metal. http://prntscr.com/bte3nh

I have set it to use "darcula-1.0.0.jar" rather than Nimbus in the past, and yet it still uses Metal.  http://prntscr.com/bte42m

I have set it to use "com.bulenkov.darcula" in the past, and yet it still uses Metal. http://prntscr.com/bte3du

I merely left Nimbus in there for the sake of it appearing in something presentable.

Body:
add darcula.jar in your Library;
then import com.bulenkov.darcula.DarculaLaf in your source file
after that

for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    System.out.println(info.getName());
    if ("Nimbus".equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(new DarculaLaf());
        break;
    }
}

make sure your ticked "Copy Dependented Libraries" in your Project Properties-> Packaging Tab.


问:
How To Execute Python REST API test suite on AWS Lambda
Basically I have written  API tests using Python REST API test suite, below tests runs fine on my local environment ,here are the tests

```<code>import requests
import json

def test_post_headers_body_json():
 url = 'https://httpbin.org/post'

  # Additional headers.
 headers = {'Content-Type': 'application/json' }

  # Body
 payload = {'key1': 1, 'key2': 'value2'}

  # convert dict to json by json.dumps() for body data.
   resp = requests.post(url, data = json.dumps(payload,indent=4))

  # Validate response headers and body contents, e.g. status code.
    assert resp.status_code == 200
    resp_body = resp.json()
 assert resp_body['url'] == url

    # print response full body as text
    print(resp.text)
</code>```

Now to run tests at my local all I need to do is just open a command prompt and type pytest in the script folder, and you will get a test result as follows.

```<code>   pytest
   ================ test session starts =======================
</code>```

But how can i run the same python test suite written above in AWS LAMBDA environment because AWS lambda has below handler code which is different from what i have above ,how can I include my code here in the AWS lambda handler code?

```<code>    import json

    def lambda_handler(event, context):
      # TODO implement
     return {
          'statusCode': 200,
           'body': json.dumps('Hello from Lambda!')
            }
</code>```

答:
In your Lambda function code, replace:

```<code># TODO implement
</code>```

with the following call:

```<code>test_post_headers_body_json()
</code>```

The entire thing would look something like the following:

```<code>import json
import requests

def lambda_handler(event, context):
  test_post_headers_body_json()
  return {
      'statusCode': 200,
       'body': json.dumps('Hello from Lambda!')
        }

def test_post_headers_body_json():
  url = 'https://httpbin.org/post'

  # Additional headers.
  headers = {'Content-Type': 'application/json' }

  # Body
  payload = {'key1': 1, 'key2': 'value2'}

  # convert dict to json by json.dumps() for body data.
  resp = requests.post(url, data = json.dumps(payload,indent=4))

  # Validate response headers and body contents, e.g. status code.
  assert resp.status_code == 200
  resp_body = resp.json()
  assert resp_body['url'] == url

  # print response full body as text
  print(resp.text)
</code>```

Body:
Basically I have written  API tests using Python REST API test suite, below tests runs fine on my local environment ,here are the tests

import requests
import json

def test_post_headers_body_json():
 url = 'https://httpbin.org/post'

  # Additional headers.
 headers = {'Content-Type': 'application/json' }

  # Body
 payload = {'key1': 1, 'key2': 'value2'}

  # convert dict to json by json.dumps() for body data.
   resp = requests.post(url, data = json.dumps(payload,indent=4))

  # Validate response headers and body contents, e.g. status code.
    assert resp.status_code == 200
    resp_body = resp.json()
 assert resp_body['url'] == url

    # print response full body as text
    print(resp.text)

Now to run tests at my local all I need to do is just open a command prompt and type pytest in the script folder, and you will get a test result as follows.

   pytest
   ================ test session starts =======================

But how can i run the same python test suite written above in AWS LAMBDA environment because AWS lambda has below handler code which is different from what i have above ,how can I include my code here in the AWS lambda handler code?

    import json

    def lambda_handler(event, context):
      # TODO implement
     return {
          'statusCode': 200,
           'body': json.dumps('Hello from Lambda!')
            }

Body:
In your Lambda function code, replace:

# TODO implement

with the following call:

test_post_headers_body_json()

The entire thing would look something like the following:

import json
import requests

def lambda_handler(event, context):
  test_post_headers_body_json()
  return {
      'statusCode': 200,
       'body': json.dumps('Hello from Lambda!')
        }

def test_post_headers_body_json():
  url = 'https://httpbin.org/post'

  # Additional headers.
  headers = {'Content-Type': 'application/json' }

  # Body
  payload = {'key1': 1, 'key2': 'value2'}

  # convert dict to json by json.dumps() for body data.
  resp = requests.post(url, data = json.dumps(payload,indent=4))

  # Validate response headers and body contents, e.g. status code.
  assert resp.status_code == 200
  resp_body = resp.json()
  assert resp_body['url'] == url

  # print response full body as text
  print(resp.text)


问:
Error while fetching value from properties file for @Scheduled fixedRate
```<code>private static final String CONSTANT = (p.getProperty("MILLISECONDS_OF_12_HOURS"));

@Scheduled(fixedRateString = CONSTANT)
public void clearCache() throws IOException {

    if(!rrcodeService.cachedAccessGroups.isEmpty()) {
        for (Entry<String, CachedAccessGroups> entry : rrcodeService.cachedAccessGroups.entrySet()) {
            String key = entry.getKey();
            CachedAccessGroups accessGroups = rrcodeService.cachedAccessGroups.get(key);
            if(now.getTime() - accessGroups.getCachedDate().getTime()> Integer.parseInt(p.getProperty("EVICT_CACHE"))) {
                rrcodeService.cachedAccessGroups.remove(key);
            }
        }
    }
}
</code>```

The value for MILLISECONDS_OF_12_HOURS is being set in the external properties file. And I am trying to set that value to FixedRateString. But its throwing error saying "The value for annotation attribute Scheduled.fixedRateString must be a constant expression"
Any help would be appreciated.. Thanks!

答:
You can inject values from the context. Something like

@Scheduled(fixedRate = "${propertykey.myRate}", initialDelay=1000)
public void clearCache() throws IOException {
   .....
}
```

<p>and have the property file (application.properties YAML) defined outside</p>

```propertykey:
    myRate: 5000
```

Keep in mind that fixedRate in the example above takes a long

Body:
private static final String CONSTANT = (p.getProperty("MILLISECONDS_OF_12_HOURS"));

@Scheduled(fixedRateString = CONSTANT)
public void clearCache() throws IOException {

    if(!rrcodeService.cachedAccessGroups.isEmpty()) {
        for (Entry<String, CachedAccessGroups> entry : rrcodeService.cachedAccessGroups.entrySet()) {
            String key = entry.getKey();
            CachedAccessGroups accessGroups = rrcodeService.cachedAccessGroups.get(key);
            if(now.getTime() - accessGroups.getCachedDate().getTime()> Integer.parseInt(p.getProperty("EVICT_CACHE"))) {
                rrcodeService.cachedAccessGroups.remove(key);
            }
        }
    }
}

The value for MILLISECONDS_OF_12_HOURS is being set in the external properties file. And I am trying to set that value to FixedRateString. But its throwing error saying "The value for annotation attribute Scheduled.fixedRateString must be a constant expression"
Any help would be appreciated.. Thanks!

Body:
You can inject values from the context. Something like

@Scheduled(fixedRate = "${propertykey.myRate}", initialDelay=1000)
public void clearCache() throws IOException {
   .....
}

and have the property file (application.properties YAML) defined outside

propertykey:
    myRate: 5000

Keep in mind that fixedRate in the example above takes a long


问:
Optimising python code by not referring the variable which refers to other variable and so on
I have a question of optimization when I refer to a variable which then refers to a variable and so on, does every time I mention the last variable which holds the previous variable all code is being executed again?

For example my code:

```<code>a = 5
b = 6
c = b * 2
d = a + c
e = c + d
f = e + d + c
g = f
h = g
</code>```

And now in my code, I say print(h), does everything has to be calculated again or python holds all values in memory when I reference them? I've came across this when I am working with SQL and pandas in python, when I connect to a database, take what I need, transform the data, then load it to a dataframe, create 3 new dataframes out of the original one and mention one of those 3 dataframes which has 1,000,000 rows and 50 columns, does python keep all those million records in memory?

Thank you for your suggestions, I assume there is a nice article somewhere explaining this but I haven't exactly find what I am looking for.

答:
Well you are supposed to propose a trimed out version of your problem to build a minimal example. Here your code is close to minimal but unfortunately unrelated to the described problem.

What matter when it comes to memory are objects and not variables. In Python a variable is no more that a name that referes to an underlying object. Simply an object ends its lifetime and can be garbage collected to free memory as soon as it is no longer reachable, meaning as soon as no variable can access it directly or indirectly.

Examples:

```<code>a = "foo and bar"  # ok a addresses the string
b = a              # b addresses the same string (one single copy)
a += "s"           # oops...
</code>```

A string is a non mutable type. The last line then creates a new string (addressed with a), while b still addresses the old one. After b = None, the old string will no longer be reachable and will be garbage collected.

```<code>a = [1, 2, 3, 4]   # ok a point to the list
b = a              # b addresses the same list
a.append(5)        # oops...
</code>```

A list is a mutable type. a.append(5) changes the object and both a and b now address the list [1, 2, 3, 4, 5]. Just use print(a,b) to see that...

Now for your exact question:

pandas underlying containers are numpy array which resides in memory. If at a moment, you can access 3 distinct dataframes, then they will be present in memory. But... pandas is highly optimized. That means that if you use sub dataframes, and depending on gory details, you will get either a plain copy (duplication in memory) that you will be able to change independently of the original dataframe, or a view (same memory used).

Let us look at some pandas examples:

Say df is a 1,000,000 rows dataframe with only numeric data. All those rows are loaded in memory.

After:

```<code>for i in range(2, 11):
    dg = df * i
    ...          # process dg
</code>```

For each step you build a new copy of the dataframe but it will be destroyed on next step. Long story short, you will use twice the initial dataframe memory

```<code>dfs = [df * i for i in range(2, 11)]
for dg in dfs:
    ...         # process dg
</code>```

Here you build 9 new dataframes that will be accessible through dfs so you end with 10 distinct dataframes and need 10 times the initial memory.

Body:
I have a question of optimization when I refer to a variable which then refers to a variable and so on, does every time I mention the last variable which holds the previous variable all code is being executed again?

For example my code:

a = 5
b = 6
c = b * 2
d = a + c
e = c + d
f = e + d + c
g = f
h = g

And now in my code, I say print(h), does everything has to be calculated again or python holds all values in memory when I reference them? I've came across this when I am working with SQL and pandas in python, when I connect to a database, take what I need, transform the data, then load it to a dataframe, create 3 new dataframes out of the original one and mention one of those 3 dataframes which has 1,000,000 rows and 50 columns, does python keep all those million records in memory?

Thank you for your suggestions, I assume there is a nice article somewhere explaining this but I haven't exactly find what I am looking for.

Body:
Well you are supposed to propose a trimed out version of your problem to build a minimal example. Here your code is close to minimal but unfortunately unrelated to the described problem.

What matter when it comes to memory are objects and not variables. In Python a variable is no more that a name that referes to an underlying object. Simply an object ends its lifetime and can be garbage collected to free memory as soon as it is no longer reachable, meaning as soon as no variable can access it directly or indirectly.

Examples:

a = "foo and bar"  # ok a addresses the string
b = a              # b addresses the same string (one single copy)
a += "s"           # oops...

A string is a non mutable type. The last line then creates a new string (addressed with a), while b still addresses the old one. After b = None, the old string will no longer be reachable and will be garbage collected.

a = [1, 2, 3, 4]   # ok a point to the list
b = a              # b addresses the same list
a.append(5)        # oops...

A list is a mutable type. a.append(5) changes the object and both a and b now address the list [1, 2, 3, 4, 5]. Just use print(a,b) to see that...

Now for your exact question:

pandas underlying containers are numpy array which resides in memory. If at a moment, you can access 3 distinct dataframes, then they will be present in memory. But... pandas is highly optimized. That means that if you use sub dataframes, and depending on gory details, you will get either a plain copy (duplication in memory) that you will be able to change independently of the original dataframe, or a view (same memory used).

Let us look at some pandas examples:

Say df is a 1,000,000 rows dataframe with only numeric data. All those rows are loaded in memory.

After:

for i in range(2, 11):
    dg = df * i
    ...          # process dg

For each step you build a new copy of the dataframe but it will be destroyed on next step. Long story short, you will use twice the initial dataframe memory

dfs = [df * i for i in range(2, 11)]
for dg in dfs:
    ...         # process dg

Here you build 9 new dataframes that will be accessible through dfs so you end with 10 distinct dataframes and need 10 times the initial memory.


问:
PHP mkdir with special character creates wrong symbols directory
I'd like to use special character because it's my procedure how to show galleries-folders on main page https://onlinegallery.online/admin/gallery/ . Folders are created by user input. Propably I don't want to use special characters for url's only for show content by glob.

```<code>$foldername= $_GET['tabl'] ;
$meno= $_GET['meno'] ;
                $gallery = Db::queryAll('
        SELECT * FROM '.$foldername.'
');

foreach ($gallery as $u)
{
        echo'<div class="section active" id=""><h1 class="headingfirst">'. htmlspecialchars($u["jmeno"]).'</h1>';
        $new = htmlspecialchars($u["jmeno"]);

    foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif}", GLOB_BRACE) as $filename) {
        $title = basename("$meno/$new/$filename", ".jpg").PHP_EOL;
    echo '<div class="slide"><img class="" src="https://onlinegallery.online/'.$filename.'" alt="'.$title.'"/><p class="imagetitle">'.$title.'</p></div>';
}
</code>```

I shouldn't use special characters as folder or file name.

Do I have to disallow special characters on user input ?

How could I solve this issue?

Users would like to name their galleries with diacritics.

答:
Have you tried encode it in utf8 in PHP?

utf8_encode($string)

utf8_encode on php.net

Body:
I'd like to use special character because it's my procedure how to show galleries-folders on main page https://onlinegallery.online/admin/gallery/ . Folders are created by user input. Propably I don't want to use special characters for url's only for show content by glob.

$foldername= $_GET['tabl'] ;
$meno= $_GET['meno'] ;
                $gallery = Db::queryAll('
        SELECT * FROM '.$foldername.'
');

foreach ($gallery as $u)
{
        echo'

'. htmlspecialchars($u["jmeno"]).'
';
        $new = htmlspecialchars($u["jmeno"]);

    foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif}", GLOB_BRACE) as $filename) {
        $title = basename("$meno/$new/$filename", ".jpg").PHP_EOL;
    echo '

'.$title.'

';
}

I shouldn't use special characters as folder or file name.

Do I have to disallow special characters on user input ?

How could I solve this issue?

Users would like to name their galleries with diacritics.


问:
How to get img inside a particular div using JQuery
I have to get all the image tags ids inside a particular div. How can I get that using JQuery?</p>

答:
```<code>function textOnly() {
            jQuery('#dvContent img').each(function () {
                jQuery(this).css('display', 'none');
            });
        }
</code>```

OwnerDisplayName: asd


问:
create element with height equal to entire page length with css only (no javascript)
I have a page with a header with nav, a righthand sidebar and a main content area. The height of the header will vary with its width always being 100%.

The desired behavior is for the sidebar to span from the very top of the page to very bottom (or down to the footer at least).

In order to be able to get the sidebar to start at the top of the page, I created it as an absolutely positioned element and placed it in the header (at the end of the nav). To get it to span the entire height of the page, I set its height to 100vh.

This works fine as long as the page does not scroll. Once the content is long enough such that the page has to scroll, the sidebar no longer extends to the bottom of the page.

My issue can be seen in this Codepen and below

CSS

```<code>nav, main {
  width: auto;
  max-width: 800px;
}

header {
  background: yellow;
  padding: 20px;
}

nav {
  position: relative;
}

main {
  padding-right: 225px;
  box-sizing: border-box;
  min-height: 150vh;
}

.sidebar {
  width: 200px;
  background: green;
  position: absolute;
  right: 10px;
  top: -20px;
  height: 100vh;
}
</code>```

HTML

```<code><header>
  <nav>item 1 | item 2 | item 3
  <div class="sidebar">sidebar</div></nav>
</header>
<main>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor urna at eros congue, vel consequat nisi fringilla. Suspendisse tempor consectetur luctus. Fusce eu nisi at tellus rhoncus eleifend. Duis aliquet sollicitudin elementum. Mauris eu elementum libero. Vivamus scelerisque ex eget faucibus aliquet. Morbi enim orci, elementum at ligula sed, sodales tempor elit.
</main>
</code>```

Can anyone think of a way to get that sidebar to display all the way from top to bottom (even when the page scrolls) using CSS only without having to add multiple sidebar elements (one in  and one in )?

答:
You could easily use grid from : header/aside and main tags for the layout:

body {
  min-height: 100vh;
}

body,
header {
  margin: 0;
  display: grid;
  grid-template-columns: 1fr minmax(auto,3fr) 200px 1fr;
  grid-template-rows: auto 1fr;
}

aside {
  grid-row: 1 / span 2;
  grid-column: 3;
  background: green;
  position: relative;
  width:200px;
}

header {
  background: yellow;
  grid-row: 1;
  grid-column: 1/ span 4;
  padding: 1em 0;
}

nav {
  grid-column: 2;
  max-width:800px;
}

main {
  grid-row: 2;
  grid-column: 2;
  max-width:800px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
  item 1 | item 2 | item 3
  </nav>
</header>
<aside class="sidebar">sidebar</aside><!-- removed from header -->
<main>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor urna at eros congue, vel consequat nisi fringilla. Suspendisse tempor consectetur luctus. Fusce eu nisi at tellus rhoncus eleifend. Duis aliquet sollicitudin elementum. Mauris eu
  elementum libero. Vivamus scelerisque ex eget faucibus aliquet. Morbi enim orci, elementum at ligula sed, sodales tempor elit. Phasellus mattis risus lorem, at vehicula nulla rhoncus vitae. Proin at elit ipsum. Mauris maximus sit amet mauris quis venenatis.
  Pellentesque at nisi egestas, pulvinar nibh eget, dictum urna. Vivamus malesuada, nisi cursus tristique venenatis, purus nisl congue tortor, vel tincidunt ante turpis id sapien. Pellentesque vel risus orci. Aliquam dictum massa eros. Nunc efficitur
  libero vitae convallis euismod. Donec ac suscipit arcu. Suspendisse placerat metus justo, eget finibus diam pharetra a. Duis vel erat diam. Mauris a erat vel ex tempor tincidunt eu in erat. Interdum et malesuada fames ac ante ipsum primis in faucibus.
  Quisque rutrum posuere elit, mattis elementum arcu malesuada non. Pellentesque eget porta ipsum, sit amet lobortis nunc. Nullam tempor, felis eu rhoncus tempus, dui massa dictum dolor, sed finibus tellus quam vel eros. Quisque euismod elit sed imperdiet
  tincidunt. Duis in dapibus risus. Duis at neque nisi. In sapien erat, scelerisque eget nulla interdum, scelerisque ullamcorper eros. Suspendisse et accumsan diam. Vivamus commodo erat eu nunc condimentum condimentum. Cras sagittis mi vel tellus suscipit
  convallis. Mauris lobortis magna a fringilla rhoncus. Proin euismod purus quis velit luctus, at volutpat diam lobortis. Nunc pretium felis vel tortor euismod, a auctor magna consequat. Sed et turpis consequat, varius justo vitae, laoreet ex. Quisque
  accumsan condimentum metus, nec suscipit risus vestibulum elementum. Donec condimentum elementum tincidunt. Phasellus vel nulla pulvinar, posuere nisl a, pellentesque risus. Suspendisse lobortis, velit eu ultricies aliquam, lorem nibh tempus lectus,
  et varius tellus ex eu dui. Nam sed ultricies augue, vel porttitor tellus. Donec ex dolor, vestibulum at enim nec, porta pharetra nulla. Praesent molestie eu mauris ut cursus. Duis nec erat erat. Aenean auctor pretium quam, ut blandit libero tempor
  luctus. Integer est nisi, tristique eu viverra eget, sodales vel nunc. Nunc fermentum sollicitudin facilisis. Nam malesuada, nisl vel ultrices egestas, ligula leo euismod ipsum, non posuere libero diam sit amet erat. Etiam dolor turpis, suscipit vel
  maximus et, pharetra eu dolor. Donec a efficitur est. Integer lacinia ligula in ipsum dapibus sagittis. Duis placerat diam sed erat egestas, eget imperdiet massa dignissim. Ut lacinia viverra leo a vestibulum. Quisque lobortis, sapien ac luctus feugiat,
  nunc sem congue odio, at consequat sem lacus at magna. Etiam quis arcu eget odio hendrerit tempus quis a ex. Etiam id aliquet nisi. Praesent luctus, lacus nec aliquam blandit, sapien sapien porta orci, sed feugiat enim velit accumsan velit. Vestibulum
  pellentesque orci et justo elementum congue. Donec ultricies felis dui, quis luctus lectus pretium vitae.
</main></code>```

Body:
I have a page with a header with nav, a righthand sidebar and a main content area. The height of the header will vary with its width always being 100%.

The desired behavior is for the sidebar to span from the very top of the page to very bottom (or down to the footer at least).

In order to be able to get the sidebar to start at the top of the page, I created it as an absolutely positioned element and placed it in the header (at the end of the nav). To get it to span the entire height of the page, I set its height to 100vh.

This works fine as long as the page does not scroll. Once the content is long enough such that the page has to scroll, the sidebar no longer extends to the bottom of the page.

My issue can be seen in this Codepen and below

CSS

nav, main {
  width: auto;
  max-width: 800px;
}

header {
  background: yellow;
  padding: 20px;
}

nav {
  position: relative;
}

main {
  padding-right: 225px;
  box-sizing: border-box;
  min-height: 150vh;
}

.sidebar {
  width: 200px;
  background: green;
  position: absolute;
  right: 10px;
  top: -20px;
  height: 100vh;
}

HTML

  item 1 | item 2 | item 3

sidebar

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor urna at eros congue, vel consequat nisi fringilla. Suspendisse tempor consectetur luctus. Fusce eu nisi at tellus rhoncus eleifend. Duis aliquet sollicitudin elementum. Mauris eu elementum libero. Vivamus scelerisque ex eget faucibus aliquet. Morbi enim orci, elementum at ligula sed, sodales tempor elit.

Can anyone think of a way to get that sidebar to display all the way from top to bottom (even when the page scrolls) using CSS only without having to add multiple sidebar elements (one in  and one in )?

Body:
You could easily use grid from : header/aside and main tags for the layout:

body {
  min-height: 100vh;
}

body,
header {
  margin: 0;
  display: grid;
  grid-template-columns: 1fr minmax(auto,3fr) 200px 1fr;
  grid-template-rows: auto 1fr;
}

aside {
  grid-row: 1 / span 2;
  grid-column: 3;
  background: green;
  position: relative;
  width:200px;
}

header {
  background: yellow;
  grid-row: 1;
  grid-column: 1/ span 4;
  padding: 1em 0;
}

nav {
  grid-column: 2;
  max-width:800px;
}

main {
  grid-row: 2;
  grid-column: 2;
  max-width:800px;

}

<header>
  <nav>
  item 1 | item 2 | item 3
  </nav>
</header>
<aside class="sidebar">sidebar</aside><!-- removed from header -->
<main>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor urna at eros congue, vel consequat nisi fringilla. Suspendisse tempor consectetur luctus. Fusce eu nisi at tellus rhoncus eleifend. Duis aliquet sollicitudin elementum. Mauris eu
  elementum libero. Vivamus scelerisque ex eget faucibus aliquet. Morbi enim orci, elementum at ligula sed, sodales tempor elit. Phasellus mattis risus lorem, at vehicula nulla rhoncus vitae. Proin at elit ipsum. Mauris maximus sit amet mauris quis venenatis.
  Pellentesque at nisi egestas, pulvinar nibh eget, dictum urna. Vivamus malesuada, nisi cursus tristique venenatis, purus nisl congue tortor, vel tincidunt ante turpis id sapien. Pellentesque vel risus orci. Aliquam dictum massa eros. Nunc efficitur
  libero vitae convallis euismod. Donec ac suscipit arcu. Suspendisse placerat metus justo, eget finibus diam pharetra a. Duis vel erat diam. Mauris a erat vel ex tempor tincidunt eu in erat. Interdum et malesuada fames ac ante ipsum primis in faucibus.
  Quisque rutrum posuere elit, mattis elementum arcu malesuada non. Pellentesque eget porta ipsum, sit amet lobortis nunc. Nullam tempor, felis eu rhoncus tempus, dui massa dictum dolor, sed finibus tellus quam vel eros. Quisque euismod elit sed imperdiet
  tincidunt. Duis in dapibus risus. Duis at neque nisi. In sapien erat, scelerisque eget nulla interdum, scelerisque ullamcorper eros. Suspendisse et accumsan diam. Vivamus commodo erat eu nunc condimentum condimentum. Cras sagittis mi vel tellus suscipit
  convallis. Mauris lobortis magna a fringilla rhoncus. Proin euismod purus quis velit luctus, at volutpat diam lobortis. Nunc pretium felis vel tortor euismod, a auctor magna consequat. Sed et turpis consequat, varius justo vitae, laoreet ex. Quisque
  accumsan condimentum metus, nec suscipit risus vestibulum elementum. Donec condimentum elementum tincidunt. Phasellus vel nulla pulvinar, posuere nisl a, pellentesque risus. Suspendisse lobortis, velit eu ultricies aliquam, lorem nibh tempus lectus,
  et varius tellus ex eu dui. Nam sed ultricies augue, vel porttitor tellus. Donec ex dolor, vestibulum at enim nec, porta pharetra nulla. Praesent molestie eu mauris ut cursus. Duis nec erat erat. Aenean auctor pretium quam, ut blandit libero tempor
  luctus. Integer est nisi, tristique eu viverra eget, sodales vel nunc. Nunc fermentum sollicitudin facilisis. Nam malesuada, nisl vel ultrices egestas, ligula leo euismod ipsum, non posuere libero diam sit amet erat. Etiam dolor turpis, suscipit vel
  maximus et, pharetra eu dolor. Donec a efficitur est. Integer lacinia ligula in ipsum dapibus sagittis. Duis placerat diam sed erat egestas, eget imperdiet massa dignissim. Ut lacinia viverra leo a vestibulum. Quisque lobortis, sapien ac luctus feugiat,
  nunc sem congue odio, at consequat sem lacus at magna. Etiam quis arcu eget odio hendrerit tempus quis a ex. Etiam id aliquet nisi. Praesent luctus, lacus nec aliquam blandit, sapien sapien porta orci, sed feugiat enim velit accumsan velit. Vestibulum
  pellentesque orci et justo elementum congue. Donec ultricies felis dui, quis luctus lectus pretium vitae.
</main>


问:
Why does a GraphQL query return null?
I have an graphql/apollo-server/graphql-yoga endpoint. This endpoint exposes data returned from a database (or a REST endpoint or some other service).

I know my data source is returning the correct data -- if I log the result of the call to the data source inside my resolver, I can see the data being returned. However, my GraphQL field(s) always resolve to null.

If I make the field non-null, I see the following error inside the errors array in the response:

Cannot return null for non-nullable field

Why is GraphQL not returning the data?

答:
If none of the above helped, and you have a global interceptor that envelopes all the responses for example inside a "data" field, you must disable this for graphql other wise graphql resolvers convert to null.

This is what I did to the interceptor on my case:

  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    if (context['contextType'] === 'graphql') return next.handle();

    return next
      .handle()
      .pipe(map(data => {
        return {
          data: isObject(data) ? this.transformResponse(data) : data
        };
      }));
  }
```

Title: Why does a GraphQL query return null?


问:
JAVA - Corrupt ZIP file using ZipOutptuStream with FileInputStream
Why might the following code be generating a corrupt zip file when output over a servlet output stream? When writing the ZIP to disk locally using a FileOutputStream, the output stream does not appear to be corrupt.

```<code>// Create zip stream
ZipOutputStream zos = new ZipOutputStream(this.servletOutputStream);

// prepare a new entry
ZipEntry zipEntry = new ZipEntry(forZip.getName());
zipEntry.setSize(forZip.getTotalSpace());
zipEntry.setTime(System.currentTimeMillis());

// write entry
zos.putNextEntry(zipEntry);

// write the file to the entry
FileInputStream toBeZippedInputStream = new FileInputStream(forZip);
IOUtils.copy(toBeZippedInputStream, zos);
zos.flush();

// close entry
zos.closeEntry();

// close the zip
zos.finish();
zos.close();

this.servletOutputStream.flush();

this.servletOutputStream.close();

// close output stream
IOUtils.closeQuietly(toBeZippedInputStream);
</code>```

Is this perhaps an issue with order of flushing/closing streams?

答: A potential problem I see is that the individual entries to be zipped are not unique. If you are looping through in this code, forZip.getName() may have duplicates.

Body:
Why might the following code be generating a corrupt zip file when output over a servlet output stream? When writing the ZIP to disk locally using a FileOutputStream, the output stream does not appear to be corrupt.

// Create zip stream
ZipOutputStream zos = new ZipOutputStream(this.servletOutputStream);

// prepare a new entry
ZipEntry zipEntry = new ZipEntry(forZip.getName());
zipEntry.setSize(forZip.getTotalSpace());
zipEntry.setTime(System.currentTimeMillis());

// write entry
zos.putNextEntry(zipEntry);

// write the file to the entry
FileInputStream toBeZippedInputStream = new FileInputStream(forZip);
IOUtils.copy(toBeZippedInputStream, zos);
zos.flush();

// close entry
zos.closeEntry();

// close the zip
zos.finish();
zos.close();

this.servletOutputStream.flush();

this.servletOutputStream.close();

// close output stream
IOUtils.closeQuietly(toBeZippedInputStream);

Is this perhaps an issue with order of flushing/closing streams?


问:
Deploying an app on Google Cloud Platform - ImportError for pyzbar
I am deploying an app with Flask that uses the library pyzbar (and more specifically the function pyzbar.pyzbar.decode)

It works perfectly on my machine; but when I deploy it, I have the error: ImportError: Unable to find zbar shared library.

This is because pyzbar.pyzbar runs find_library('zbar') (find_library is from ctypes.util) and nothing is returned.

Do you know what I should do?

答:
The lib-zbar-dev OS package is not present in the  App Engine standard environment and cannot be installed, even if pyzbar is installed. I suggest that you try to use an App Engine flexible custom runtime to install all necessary operating system dependencies. App Engine Flex offers a high level of customization, as this solution uses Debian-based docked images to run your applications.

In this link you can find more information on how to create a custom runtime for App Engine Flex, keep in mind that you need to know Docker.

Another alternative is to use a Compute Engine VM to run your application, this is not a serverless solution, but you can install all the necessary software for your application.


问:
gradle - ProjectB missing ProjectA dependencies
I include ProjectA in ProjectB with compile files('../ProjectA/build/libs/ProjectA-1.0-SNAPSHOT.jar').  However, when running ProjectB I get classnotfound errors for dependencies in ProjectA.  Like the selenium webdriver and okhttp.  What must I do to get past those errors?

ProjectA build.gradle

```<code>plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.61'
    id 'application'
}

group 'com.company.projectA'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    main.java.srcDirs = ['src']
//    main.kotlin.srcDirs = ['src/main/java', 'src/main/kotlin']
    main.kotlin.srcDirs = ['src']
    main.resources.srcDirs = ['src/main/resources']
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '2.41.0'
    implementation("com.squareup.okhttp3:okhttp:4.3.1")

}
</code>```

Project B build.gradle

```<code>plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.61'
    id 'application'
}

group 'com.company.projectB'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    main.java.srcDirs = ['src']
    main.kotlin.srcDirs = ['src']
    main.resources.srcDirs = ['src/main/resources']
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    // This pulls in the local project, but leaves out its dependencies.
    compile files('../ProjectA/build/libs/ProjectA-1.0-SNAPSHOT.jar')
}
</code>```

答:
Depending on the generated jar file adds only the compiled classes from ProjectA as the dependency. In this case ProjectB should depend on ProjectA itself - that will add also ProjectA dependencies as transient dependencies.

Put settings.gradle in root directory of both projects:

```<code>settings.gradle
ProjectA/
  build.gradle
ProjectB/
  build.gradle
</code>```

Include both projects in settings.gradle:

```<code>include ':ProjectA', ':ProjectB'
</code>```

Add ProjectA as a dependency in ProjectB/build.gradle:

```<code>dependencies {
  compile project(':ProjectA')
}
</code>```

Or as in the example Project B build.gradle:

```<code>plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.61'
    id 'application'
}

group 'com.company.projectB'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    main.java.srcDirs = ['src']
    main.kotlin.srcDirs = ['src']
    main.resources.srcDirs = ['src/main/resources']
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    // This adds the local project with all its transient dependencies
    implementation project(':ProjectA')
}
</code>```

Body:
I include ProjectA in ProjectB with compile files('../ProjectA/build/libs/ProjectA-1.0-SNAPSHOT.jar').  However, when running ProjectB I get classnotfound errors for dependencies in ProjectA.  Like the selenium webdriver and okhttp.  What must I do to get past those errors?

ProjectA build.gradle

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.61'
    id 'application'
}

group 'com.company.projectA'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    main.java.srcDirs = ['src']
//    main.kotlin.srcDirs = ['src/main/java', 'src/main/kotlin']
    main.kotlin.srcDirs = ['src']
    main.resources.srcDirs = ['src/main/resources']
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '2.41.0'
    implementation("com.squareup.okhttp3:okhttp:4.3.1")

}

Project B build.gradle

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.61'
    id 'application'
}

group 'com.company.projectB'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    main.java.srcDirs = ['src']
    main.kotlin.srcDirs = ['src']
    main.resources.srcDirs = ['src/main/resources']
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    // This pulls in the local project, but leaves out its dependencies.
    compile files('../ProjectA/build/libs/ProjectA-1.0-SNAPSHOT.jar')
}

Body:
Depending on the generated jar file adds only the compiled classes from ProjectA as the dependency. In this case ProjectB should depend on ProjectA itself - that will add also ProjectA dependencies as transient dependencies.

Put settings.gradle in root directory of both projects:

settings.gradle
ProjectA/
  build.gradle
ProjectB/
  build.gradle

Include both projects in settings.gradle:

include ':ProjectA', ':ProjectB'

Add ProjectA as a dependency in ProjectB/build.gradle:

dependencies {
  compile project(':ProjectA')
}

Or as in the example Project B build.gradle:

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.61'
    id 'application'
}

group 'com.company.projectB'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    main.java.srcDirs = ['src']
    main.kotlin.srcDirs = ['src']
    main.resources.srcDirs = ['src/main/resources']
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    // This adds the local project with all its transient dependencies
    implementation project(':ProjectA')
}


问:
Selecting updated rows between two tables
Good day,

I have to identical table structures. One is base table and second has incremental changes. I wish to have resulting table so that I pick he rows from the update, if present. Otherwise from old table.

Like so

```<code>table a: | Table b: | Result table:
key val  |  key val | key val
1   a    |  2   bb  |  1   a
2   b    |  4   dd  |  2   bb
3   c    |  5   ee  |  3   c
4   d    |          |  4   dd
                       5   ee
</code>```

I tried selecting B table values on inner join and full outer join where a.key is NULL or b.key is NULL and union. (Code not tested to functionality yet.)

```<code>select * from
(
  (select table_B.* from
    TABLE_A
      inner join
    TABLE_B
    on TABLE_A.key = TABLE_B.key
  )
  UNION
  (select * from
    TABLE_A
     full outer join
    TABLE_B
  on TABLE_A.key = TABLE_B.key
  where TABLE_A.key is NULL or TABLE_A.key is NULL
  )
)
</code>```

Is there an easier way to do this? I got the feeling that there has to be a more robust way to do this.

EDIT: I'm currently implementing this in the SPARK SQL context, but have had similar issues in the SQL server environment. Yet, I'm looking for a general idea.

答:
One method is full join:

```<code>select key, coalesce(i.value, m.value) as value
from master m full join
     incremental i
     using (key);
</code>```

Body:
Good day,

I have to identical table structures. One is base table and second has incremental changes. I wish to have resulting table so that I pick he rows from the update, if present. Otherwise from old table.

Like so

table a: | Table b: | Result table:
key val  |  key val | key val
1   a    |  2   bb  |  1   a
2   b    |  4   dd  |  2   bb
3   c    |  5   ee  |  3   c
4   d    |          |  4   dd
                       5   ee

I tried selecting B table values on inner join and full outer join where a.key is NULL or b.key is NULL and union. (Code not tested to functionality yet.)

select * from
(
  (select table_B.* from
    TABLE_A
      inner join
    TABLE_B
    on TABLE_A.key = TABLE_B.key
  )
  UNION
  (select * from
    TABLE_A
     full outer join
    TABLE_B
  on TABLE_A.key = TABLE_B.key
  where TABLE_A.key is NULL or TABLE_A.key is NULL
  )
)

Is there an easier way to do this? I got the feeling that there has to be a more robust way to do this.

EDIT: I'm currently implementing this in the SPARK SQL context, but have had similar issues in the SQL server environment. Yet, I'm looking for a general idea.

Body:
One method is full join:

select key, coalesce(i.value, m.value) as value
from master m full join
     incremental i
     using (key);


问:
What is the reason that CDATA even exists?
I often see people asking XML/XSLT related questions here that root in the inability to grasp how CDATA works (like this one).

I wonder - why does it exist in the first place? It's not that XML could not do without it, everything you can put into a CDATA section can be expressed as "native" (XML-escaped).

I appreciate that CDATA potentially makes the resulting document a bit smaller, but let's face it - XML is verbose anyway. Small XML documents can be achieved more easily through compression, for example.

For me, CDATA breaks the clean separation of markup and data since you can have data that looks like markup to the unaided eye, which I find is a bad thing. (This may even be one of the things that encourages people to inadequately apply string processing or regex to XML.)

So: What good reason is there to use CDATA?

答:
Here's a concrete example of why/when you may want to use CDATA.

Get rid of the CDATAs and this simple SVG will fail to be parsed by browsers:

```<code><?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1"
    baseProfile="full"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xmlns:ev="http://www.w3.org/2001/xml-events"
    >

<title>CDATA</title>

<style type="text/css"><![CDATA[

/**
 * Imagine you mention this element <foo> in a comment… or use the & sign.
 * Then…
 *
 * If this weren't wrapped into CDATA (mind both the starting and closing
 * tags), then the browser would fail to parse the file correctly. For example:
 *
 * Firefox would fail with this:
 * > XML Parsing Error: mismatched tag. Expected: [foo's closing tag].
 *
 * Chrome and Safari would fail with this:
 * > This page contains the following errors:
 * > error on line 22 at column 9: Opening and ending tag mismatch: foo line 0 and style
 */

]]></style>

<text x="20" y="60" font-size="60">Hello</text>

<script><![CDATA[

// <text>
// see comment in the CSS, because it's the same situation here.

]]></script>
</svg>
</code>```

This was with an SVG file, but you should take the same precautions with just any XML file.

Body:
Here's a concrete example of why/when you may want to use CDATA.

Get rid of the CDATAs and this simple SVG will fail to be parsed by browsers:

<?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1"
    baseProfile="full"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xmlns:ev="http://www.w3.org/2001/xml-events"
    >

<title>CDATA</title>

<style type="text/css"><![CDATA[

/**
 * Imagine you mention this element <foo> in a comment… or use the & sign.
 * Then…
 *
 * If this weren't wrapped into CDATA (mind both the starting and closing
 * tags), then the browser would fail to parse the file correctly. For example:
 *
 * Firefox would fail with this:
 * > XML Parsing Error: mismatched tag. Expected: [foo's closing tag].
 *
 * Chrome and Safari would fail with this:
 * > This page contains the following errors:
 * > error on line 22 at column 9: Opening and ending tag mismatch: foo line 0 and style
 */

]]></style>

<text x="20" y="60" font-size="60">Hello</text>

<script><![CDATA[

// <text>
// see comment in the CSS, because it's the same situation here.

]]></script>
</svg>

This was with an SVG file, but you should take the same precautions with just any XML file.