问:
Angular material progress bar not loading primary color from theme
I am trying to override the primary color for angular material.
I have a progress bar and button.

on .html

```<code><button mat-flat-button color="primary">Continue</button>
<mat-progress-bar color="primary" mode="determinate" value="100" bufferValue="0"></mat-progress-bar>
</code>```

on main.scss

```<code>@import "~@angular/material/theming";
@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';
@include mat-core();

$mat-blue: (
    50: #e3f2fd,
    100: #bbdefb,
    200: #90caf9,
    300: #64b5f6,
    400: #42a5f5,
    500: #2196f3,
    600: #1e88e5,
    700: #1976d2,
    800: #1565c0,
    900: #0d47a1,
    A100: #82b1ff,
    A200: #448aff,
    A400: #2979ff,
    A700: #2B66C3,
    contrast: (
        50: $black-87-opacity,
        100: $black-87-opacity,
        200: $black-87-opacity,
        300: $black-87-opacity,
        400: $black-87-opacity,
        500: white,
        600: white,
        700: white,
        800: $white-87-opacity,
        900: $white-87-opacity,
        A100: $black-87-opacity,
        A200: white,
        A400: white,
        A700: white,
    )
);
$app-primary: mat-palette($mat-blue, A400, A100, A800);
$app-accent: mat-palette($mat-pink, A200, A100, A400);
$app-warn: mat-palette($mat-red);
$app-theme: mat-light-theme($app-primary, $app-accent, $app-warn);
@include angular-material-theme($app-theme);
</code>```

It displays the override color for the button, not for the progress bar.

there is no error in the console.
I inspected the element and I can see the button css from node_modules/@angular/material/_theming.scss is placed in  and the progress bar is displayed from the node_modules/@angular/material/_theming.scss.

Angular 9.1.4
Angular material 9.2.2

What step am I missing? Any suggestion?

Edit:

I see this in the inspect element, for the button it is rendered in the

答:
Try puting this in main.scss

::ng-deep .mat-progress-bar-fill::after { background-color: #2979ff; }

Body:
I am trying to override the primary color for angular material.
I have a progress bar and button.

on .html

<button mat-flat-button color="primary">Continue</button>
<mat-progress-bar color="primary" mode="determinate" value="100" bufferValue="0"></mat-progress-bar>

on main.scss

@import "~@angular/material/theming";
@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';
@include mat-core();

$mat-blue: (
    50: #e3f2fd,
    100: #bbdefb,
    200: #90caf9,
    300: #64b5f6,
    400: #42a5f5,
    500: #2196f3,
    600: #1e88e5,
    700: #1976d2,
    800: #1565c0,
    900: #0d47a1,
    A100: #82b1ff,
    A200: #448aff,
    A400: #2979ff,
    A700: #2B66C3,
    contrast: (
        50: $black-87-opacity,
        100: $black-87-opacity,
        200: $black-87-opacity,
        300: $black-87-opacity,
        400: $black-87-opacity,
        500: white,
        600: white,
        700: white,
        800: $white-87-opacity,
        900: $white-87-opacity,
        A100: $black-87-opacity,
        A200: white,
        A400: white,
        A700: white,
    )
);
$app-primary: mat-palette($mat-blue, A400, A100, A800);
$app-accent: mat-palette($mat-pink, A200, A100, A400);
$app-warn: mat-palette($mat-red);
$app-theme: mat-light-theme($app-primary, $app-accent, $app-warn);
@include angular-material-theme($app-theme);

It displays the override color for the button, not for the progress bar.

there is no error in the console.
I inspected the element and I can see the button css from node_modules/@angular/material/_theming.scss is placed in  and the progress bar is displayed from the node_modules/@angular/material/_theming.scss.

Angular 9.1.4
Angular material 9.2.2

What step am I missing? Any suggestion?

Edit:

I see this in the inspect element, for the button it is rendered in the


来源: stackexchange

问:
In R how would you replace values in a matrix that have a certain condition with values from another vector?
I have a matrix and a vector like this:

```<code>Matrix<-cbind(c(3,3,5,1),c(2,5,2,1))
Vector<-c(2,3,3,3)
</code>```

I want to replace the Matrix elements that are >= the corresponding Vector value with the values in the Vector so that the Matrix would now look like this:

```<code>MatrixNew<-cbind(c(2,3,3,1),c(2,3,2,1))
</code>```

What logic would achieve this?

答:
I believe the pmin method by @caldwellst is the simplest one so far. Here is another option using ifelse

```<code>> ifelse(Matrix >= Vector, Vector, Matrix)
     [,1] [,2]
[1,]    2    2
[2,]    3    3
[3,]    3    2
[4,]    1    1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a matrix and a vector like this:

Matrix<-cbind(c(3,3,5,1),c(2,5,2,1))
Vector<-c(2,3,3,3)

I want to replace the Matrix elements that are >= the corresponding Vector value with the values in the Vector so that the Matrix would now look like this:

MatrixNew<-cbind(c(2,3,3,1),c(2,3,2,1))

What logic would achieve this?

Body:
I believe the pmin method by @caldwellst is the simplest one so far. Here is another option using ifelse

> ifelse(Matrix >= Vector, Vector, Matrix)
     [,1] [,2]
[1,]    2    2
[2,]    3    3
[3,]    3    2
[4,]    1    1


问:
c++ vector with strict ownership semantics
This is not a question about putting std::auto_ptr into std::vector.

Is there some vector equivalent of std::auto_ptr in std::, std::tr1:: or boost::? I use std::auto_ptr in function parameters and return values to decalre ownership semantics of these functions. But this way I can pass only single objects. As a temporary solution for vectors I have this:

```<code>std::auto_ptr<std::vector<std::tr1::shared_ptr<ClassExample> > > fx(....);
</code>```

which, I suppose, by introducing boost, I will be able to change into this:

```<code>std::auto_ptr<std::vectro<boost::unique_ptr<ClassExample> > >f(...);
</code>```

in order to define strict ownership passing, but it seems to be quite complicated. To simplify it, I can use

```<code>std::vector<boost::unique_ptr<ClassExample> > f(...);
</code>```

as the price for deep copy of the vector is not high, but I am still curious if there is something that I can use like this:

```<code>auto_vector<ClassExample> f(...);
</code>```

meaning that the function is releasing ownership of all the objects and the vector internal data array is not deeply copied.

答:
Without any particular reason as to why you need to maintain a vector of pointers, the first solution would be to ditch all the complexity and go for the simple:

```<code>std::vector<Type> f();
</code>```

Ownership of the objects is unique (the vector owns them), and while the code looks like it is copying the vector on return it will be optimized away in most cases.

If you need the objects inside the vector to be dynamically allocated due to some other requirement (objects must be allocated through a factory, they are pointers to derived types, or they cannot move due to vector growth -- code maintains references/pointers) that you are not showing then I would go for a boost::ptr_vector that will maintain ownership of the contained objects. Again, return by value:

```<code>boost::ptr_vector<Type> f();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is not a question about putting std::auto_ptr into std::vector.

Is there some vector equivalent of std::auto_ptr in std::, std::tr1:: or boost::? I use std::auto_ptr in function parameters and return values to decalre ownership semantics of these functions. But this way I can pass only single objects. As a temporary solution for vectors I have this:

std::auto_ptr<std::vector<std::tr1::shared_ptr<ClassExample> > > fx(....);

which, I suppose, by introducing boost, I will be able to change into this:

std::auto_ptr<std::vectro<boost::unique_ptr<ClassExample> > >f(...);

in order to define strict ownership passing, but it seems to be quite complicated. To simplify it, I can use

std::vector<boost::unique_ptr<ClassExample> > f(...);

as the price for deep copy of the vector is not high, but I am still curious if there is something that I can use like this:

auto_vector<ClassExample> f(...);

meaning that the function is releasing ownership of all the objects and the vector internal data array is not deeply copied.

Body:
Without any particular reason as to why you need to maintain a vector of pointers, the first solution would be to ditch all the complexity and go for the simple:

std::vector<Type> f();

Ownership of the objects is unique (the vector owns them), and while the code looks like it is copying the vector on return it will be optimized away in most cases.

If you need the objects inside the vector to be dynamically allocated due to some other requirement (objects must be allocated through a factory, they are pointers to derived types, or they cannot move due to vector growth -- code maintains references/pointers) that you are not showing then I would go for a boost::ptr_vector that will maintain ownership of the contained objects. Again, return by value:

boost::ptr_vector<Type> f();


问:
Is there a way of conditionally selecting which WHERE-clause to use in an SQL query?
Knowing I have 2 variables declared called @Variable and @Name, I need something like this:

```<code>SELECT * from (myDbTable)
CASE WHEN (@Variable IS NOT NULL AND @Variable <> '')
THEN WHERE myDbTable.variable LIKE @Variable
ELSE WHERE myDbTable.name LIKE @Name
</code>```

Basically, if the user enters a "variable" value, it should do a WHERE-clause on that variable, if not, it should do a WHERE-clause on Name.

Can I do this in SQL?

答:
There are a few options here:

Use boolean logic

SELECT *
FROM dbo.myDbTable
WHERE (@Variable IS NOT NULL AND @variable != '' AND variable LIKE @Variable)
   OR ((@Variable IS NULL OR @Variable = '') AND [Name] LIKE @Name)
OPTION (RECOMPILE);
```
<p>The <code>RECOMPILE</code> is added to the <code>OPTION</code> clause, as very likely the plans for the 2 variables could be very different. This means that a plan relevant to the valueof <code>@variable</code> (if it's <code>NULL</code>/<code>''</code> or not) will be used.</p>
<h3>Use <code>IF...ELSE</code> logic</h3>
<pre class="lang-sql prettyprint-override"><code>IF NULLIF(@Variable,'') IS NOT NULL
    SELECT *
    FROM dbo.myDbTable
    WHERE variable LIKE @Variable;
ELSE
    SELECT *
    FROM dbo.myDbTable
    WHERE [Name] LIKE @Name;
</code>```

Considering the simplicity of your query, this might be the "better" option, as the plans can be cached for the 2 different queries.

Dynamic SQL

DECLARE @SQL nvarchar(MAX),
        @CRLF nchar(2) = NCHAR(13) + NCHAR(10);

SET @SQL = N'SELECT *' + @CRLF +
           N'FROM dbo.myDbTable' + @CRLF +
           N'WHERE ' + CASE WHEN NULLIF(@Variable,'') IS NOT NULL THEN N'variable LIKE @Variable'
                                                                  ELSE N'[Name] LIKE @Name'
                       END + N';';

EXEC sys.sp_executesql @SQL, N'@Variable varchar(50), @Name varchar(50)', @Variable, @Name; --Data types are guessed.
```

This, like the IF...ELSE solution will have cached plans, however, I feel that this is an over complication of what you have. If you don't understand the importance of well written dynamic SQL, and the dangers of poorly written dynamic SQL, you shouldn't be using this.

Body:
Knowing I have 2 variables declared called @Variable and @Name, I need something like this:

SELECT * from (myDbTable)
CASE WHEN (@Variable IS NOT NULL AND @Variable <> '')
THEN WHERE myDbTable.variable LIKE @Variable
ELSE WHERE myDbTable.name LIKE @Name

Basically, if the user enters a "variable" value, it should do a WHERE-clause on that variable, if not, it should do a WHERE-clause on Name.

Can I do this in SQL?

Body:
There are a few options here:

Use boolean logic

SELECT *
FROM dbo.myDbTable
WHERE (@Variable IS NOT NULL AND @variable != '' AND variable LIKE @Variable)
   OR ((@Variable IS NULL OR @Variable = '') AND [Name] LIKE @Name)
OPTION (RECOMPILE);

The RECOMPILE is added to the OPTION clause, as very likely the plans for the 2 variables could be very different. This means that a plan relevant to the valueof @variable (if it's NULL/'' or not) will be used.

Use IF...ELSE logic

IF NULLIF(@Variable,'') IS NOT NULL
    SELECT *
    FROM dbo.myDbTable
    WHERE variable LIKE @Variable;
ELSE
    SELECT *
    FROM dbo.myDbTable
    WHERE [Name] LIKE @Name;

Considering the simplicity of your query, this might be the "better" option, as the plans can be cached for the 2 different queries.

Dynamic SQL

DECLARE @SQL nvarchar(MAX),
        @CRLF nchar(2) = NCHAR(13) + NCHAR(10);

SET @SQL = N'SELECT *' + @CRLF +
           N'FROM dbo.myDbTable' + @CRLF +
           N'WHERE ' + CASE WHEN NULLIF(@Variable,'') IS NOT NULL THEN N'variable LIKE @Variable'
                                                                  ELSE N'[Name] LIKE @Name'
                       END + N';';

EXEC sys.sp_executesql @SQL, N'@Variable varchar(50), @Name varchar(50)', @Variable, @Name; --Data types are guessed.

This, like the IF...ELSE solution will have cached plans, however, I feel that this is an over complication of what you have. If you don't understand the importance of well written dynamic SQL, and the dangers of poorly written dynamic SQL, you shouldn't be using this.


问:
How do I use multiple interfaces for one object in typescript
I have to check an object. That may have different signatures. It should accept type and svc or id. Therefore I have two interfaces:

```<code>interface A {
  type: string;
  svc: string;
}
interface B {
  id: string;
}
</code>```

I saw an example, where they used a type and both interface combined with "or":

```<code>export type AB = A | B;

func(config: AB) {
  if (config.type ) {
    ...
  }
}
</code>```

But this delivers an TS error in IDE:

TS2339: Property 'type' does not exist on type 'AB'. Property 'type'
does not exist on type 'B'.

How is the correct way to implement this?

答:
You can change the check to</p>
```<code>if ('type' in config) {
  //because config contains a type property
  //typescript knows config must be of type A in here
}
</code>```

Body:
I have to check an object. That may have different signatures. It should accept type and svc or id. Therefore I have two interfaces:

interface A {
  type: string;
  svc: string;
}
interface B {
  id: string;
}

I saw an example, where they used a type and both interface combined with "or":

export type AB = A | B;

func(config: AB) {
  if (config.type ) {
    ...
  }
}

But this delivers an TS error in IDE:

TS2339: Property 'type' does not exist on type 'AB'. Property 'type'
does not exist on type 'B'.

How is the correct way to implement this?

Body:
You can change the check to

if ('type' in config) {
  //because config contains a type property
  //typescript knows config must be of type A in here
}


问:
first its coming the result after changes some code then its showing like Expected a value of type 'Map<dynamic, dynamic>', but got one of type Null
9:41 AM
{location: Berlin, flag: germany.png, time: 9:41 AM}
Restarted application in 4,422ms.

════════ Exception caught by widgets library ═══════════════════════════════════
The following TypeErrorImpl was thrown building Home(dirty, dependencies: [_ModalScopeStatus], state: _HomeState#b1e1d):
Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'Null'

The relevant error-causing widget was
Home
lib\main.dart:14
When the exception was thrown, this was the stack
enter image description here

答: Declare your Map optional  Map? data = {}


问:
You are not authenticated! Error code: 0 exception occurred only for UiPath background process
I started a development using the UiPath template called ‘Background Process’ and currently I’m facing an issue when reading orchestrator assets. It throws the error ‘You are not authenticated! Error code: 0’. But when I tried out UiPath RE-Framework based developments, this issue was not emerged. However I’m using the community editions of both studio and the orchestrator where the version is 2021.10.5. I’ve been struggling for whole 1 day trying out different solutions, but failed. No idea whether there is something with background processes or not. I would really appreciate your support ahead in time.

Image 1 - Normal flow without using either RE Framework or Background process

Image 2 - RE Framework process

Image 3 - Background process

Image 4 - The main file of background process

答:
I sorted out the issue by downgrading "UIPath.System.Activities" version into 20.4.0.
Thank you.</p>


问:
React / Next - importing component from external library cause : Element type is invalid: expected a string or a class/function but got: undefined
I'm trying to create a React components library then integrated into a NextJs project.
In the library I have a generic "CmsBlock" component that take a type and the data and generate a component (Paragraph or ZigZag). Here is the code :

src/Block.tsx

```<code>import React from "react";
import Paragraph from "./components/Paragraph/Paragraph";
import ZigZag from "./components/ZigZag/ZigZag";

const CMS_BLOCKS: {
  [key: string]: any;
} = {
  ZigZag: ZigZag,
  Paragraph: Paragraph,
};

const CmsBlock = ({ type, data }: { type: string; data: unknown }) => {
  const CurrentBlock = CMS_BLOCKS[type];

  if (!CurrentBlock) {
    throw new Error("Unknown block type");
  }

  return <CurrentBlock data={data} />;
};

export default CmsBlock;
</code>```

src/components/Paragraph/Paragraph.tsx

```<code>import React, { FC } from "react";
import { CmsProps } from "../props";

export interface ParagraphData {
  text: string;
}
const Paragraph: FC<CmsProps<ParagraphData>> = ({ data }) => {
  return (
    <section className="text-gray-600 dark:text-gray-300">
      <p className="leading-relaxed">{data.text}</p>
    </section>
  );
};

Paragraph.defaultProps = {
  data: {
    text: `Lorem ipsum dolor sit amet. Et ullam quis et repellat nulla sit consequatur praesentium est voluptatem dolorem ut voluptate eveniet At consequatur veniam aut vero pariatur? Et consequatur repudiandae ut illum voluptas est unde dolore et enim blanditiis et asperiores perspiciatis et rerum eveniet ad molestiae pariatur. Aut nostrum itaque a assumenda consequatur ad numquam expedita ex rerum officia? Eum delectus incidunt quo incidunt nemo est itaque similique est tempora iure.`,
  },
};

export default Paragraph;
</code>```

And then my index.ts (input for rollup)

```<code>export { default as CmsBlock } from "./Block";
</code>```

In my NextJS project, I use the CmsBlock like that :

```<code>import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (
    <section className="container mx-auto my-4 space-y-10">
      {data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      ))}
    </section>
  );
}
</code>```

It loads well but I have that modal with error  :

Unhandled Runtime Error

Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file
it's defined in, or you might have mixed up default and named imports.

Check the render method of Bloc.

It look like I messed up with a import/export but I can't handle to find it.

edit : Just discover that when I try a "next build", I have that error :

```<code>./src/pages/[[...slug]].tsx
Attempted import error: 'CmsBlock' is not exported from '@cleverconnect/cms-components' (imported as 'CmsBlock').
</code>```

答:
It's likely that block.data and/or block.type are undefined when you pass them to CmsBlock in the Bloc component. You can check that the data.blocks is not empty before mapping it.

Either approach bellow would do:

import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (

      {data.blocks && data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      ))}

  );
}

```
<p>or :</p>
<pre class="lang-js prettyprint-override"><code>import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (
    <section className="container mx-auto my-4 space-y-10">
      {data.blocks.length ? data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      )) : <> Some custom fallback message here: no data yet, sorry</>}
    </section>
  );
}

</code>```

Body:
I'm trying to create a React components library then integrated into a NextJs project.
In the library I have a generic "CmsBlock" component that take a type and the data and generate a component (Paragraph or ZigZag). Here is the code :

src/Block.tsx

import React from "react";
import Paragraph from "./components/Paragraph/Paragraph";
import ZigZag from "./components/ZigZag/ZigZag";

const CMS_BLOCKS: {
  [key: string]: any;
} = {
  ZigZag: ZigZag,
  Paragraph: Paragraph,
};

const CmsBlock = ({ type, data }: { type: string; data: unknown }) => {
  const CurrentBlock = CMS_BLOCKS[type];

  if (!CurrentBlock) {
    throw new Error("Unknown block type");
  }

  return <CurrentBlock data={data} />;
};

export default CmsBlock;

src/components/Paragraph/Paragraph.tsx

import React, { FC } from "react";
import { CmsProps } from "../props";

export interface ParagraphData {
  text: string;
}
const Paragraph: FC<CmsProps<ParagraphData>> = ({ data }) => {
  return (

{data.text}

  );
};

Paragraph.defaultProps = {
  data: {
    text: `Lorem ipsum dolor sit amet. Et ullam quis et repellat nulla sit consequatur praesentium est voluptatem dolorem ut voluptate eveniet At consequatur veniam aut vero pariatur? Et consequatur repudiandae ut illum voluptas est unde dolore et enim blanditiis et asperiores perspiciatis et rerum eveniet ad molestiae pariatur. Aut nostrum itaque a assumenda consequatur ad numquam expedita ex rerum officia? Eum delectus incidunt quo incidunt nemo est itaque similique est tempora iure.`,
  },
};

export default Paragraph;

And then my index.ts (input for rollup)

export { default as CmsBlock } from "./Block";

In my NextJS project, I use the CmsBlock like that :

import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (

      {data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      ))}

  );
}

It loads well but I have that modal with error  :

Unhandled Runtime Error

Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file
it's defined in, or you might have mixed up default and named imports.

Check the render method of Bloc.

It look like I messed up with a import/export but I can't handle to find it.

edit : Just discover that when I try a "next build", I have that error :

./src/pages/[[...slug]].tsx
Attempted import error: 'CmsBlock' is not exported from '@cleverconnect/cms-components' (imported as 'CmsBlock').

Body:
It's likely that block.data and/or block.type are undefined when you pass them to CmsBlock in the Bloc component. You can check that the data.blocks is not empty before mapping it.

Either approach bellow would do:

import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (
    <section className="container mx-auto my-4 space-y-10">
      {data.blocks && data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      ))}
    </section>
  );
}

or :

import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (
    <section className="container mx-auto my-4 space-y-10">
      {data.blocks.length ? data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      )) : <> Some custom fallback message here: no data yet, sorry</>}
    </section>
  );
}


问:
c# splitting and retrieving values from a string
I have a string like this:

```<code>"http://localhost:55164/Images/photos/2/2.jpg"
</code>```

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

答:
use Split function with '/' as separator and take 2 last elements of the array.</p>

```<code>            string s = "";
            string[] arr = s.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string ans = "";
            if (arr.Length > 1)
                ans = arr[arr.Length - 1] + arr[arr.Length - 2];
</code>```

Body:
I have a string like this:

"http://localhost:55164/Images/photos/2/2.jpg"

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

Body:
use Split function with '/' as separator and take 2 last elements of the array.

            string s = "";
            string[] arr = s.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string ans = "";
            if (arr.Length > 1)
                ans = arr[arr.Length - 1] + arr[arr.Length - 2];


问:
How open the emulator on Android studio with the old way ? (Before bumblebee)
In bumblebee version of android studio the emulator is display like in the screen. I cannot move it on an other screen of something like that.

In the old way the emulator was detached from the ide.

How can I get the view of the old way with bumblebee version ?

EDIT :
I don't have access to "View Mode" when clicking on three Dots

答:
To run the emulator in a separate window

Windows OS (Answered by Per.J: https://stackoverflow.com/a/70923615/3057112)

File > Settings > Tools > Emulator and deselect Launch in a tool window.

Mac OS

Android Studio > Preferences > Tools > Emulator and deselect Launch in a tool window.

Official Ref : https://developer.android.com/studio/run/emulator#run-emulator-studio


问:
str.contains function AND does not contain
I'm iterating over all values in columns that contain 'Applicant Age' and adding them into a new column.

```<code>for i in range(17):
    rule_col = f'rule{i}_evaluationstring'
    matches = df_merged[rule_col].astype(str).str.contains('Applicant Age', na=False)
    df_merged.loc[matches, 'applicant_age'] = df_merged.loc[matches, rule_col]
</code>```

This works properly, but there are some entries that have an 'Applicant Age = 200' that I would like to omit.

How do I add an additional function that omits all values that contain 200 while keeping the functionality of the above?

答:
Try this:</p>
```<code>matches = (df_merged[rule_col].astype(str).str.contains('Applicant Age', na=False)) & (~df_merged[rule_col].astype(str).str.contains('Applicant Age = 200', na=False))
</code>```

Body:
I'm iterating over all values in columns that contain 'Applicant Age' and adding them into a new column.

for i in range(17):
    rule_col = f'rule{i}_evaluationstring'
    matches = df_merged[rule_col].astype(str).str.contains('Applicant Age', na=False)
    df_merged.loc[matches, 'applicant_age'] = df_merged.loc[matches, rule_col]

This works properly, but there are some entries that have an 'Applicant Age = 200' that I would like to omit.

How do I add an additional function that omits all values that contain 200 while keeping the functionality of the above?

Body:
Try this:

matches = (df_merged[rule_col].astype(str).str.contains('Applicant Age', na=False)) & (~df_merged[rule_col].astype(str).str.contains('Applicant Age = 200', na=False))


问:
slideshow stuck framer motion
I want to make a slide show in framer motion and I found that in framer motion docs they have an example slide show like this https://codesandbox.io/s/framer-motion-image-gallery-pqvx3?from-embed=&file=/src/Example.tsx, but I found a bug when we drag and double click it, it will be stuck like this picture .

import * as React from "react";
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { wrap } from "popmotion";
import { images } from "./image-data";

const variants = {
  enter: (direction: number) => {
    return {
      x: direction > 0 ? 1000 : -1000,
      opacity: 0
    };
  },
  center: {
    zIndex: 1,
    x: 0,
    opacity: 1
  },
  exit: (direction: number) => {
    return {
      zIndex: 0,
      x: direction < 0 ? 1000 : -1000,
      opacity: 0
    };
  }
};
const swipeConfidenceThreshold = 10000;
const swipePower = (offset: number, velocity: number) => {
  return Math.abs(offset) * velocity;
};

export const Example = () => {
  const [[page, direction], setPage] = useState([0, 0]);images.
  const imageIndex = wrap(0, images.length, page);

  const paginate = (newDirection: number) => {
    setPage([page + newDirection, newDirection]);
  };

  return (
    <>
      <AnimatePresence initial={false} custom={direction}>
        <motion.img
          key={page}
          src={images[imageIndex]}
          custom={direction}
          variants={variants}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{
            x: { type: "spring", stiffness: 300, damping: 30 },
            opacity: { duration: 0.2 }
          }}
          drag="x"
          dragConstraints={{ left: 0, right: 0 }}
          dragElastic={1}
          onDragEnd={(e, { offset, velocity }) => {
            const swipe = swipePower(offset.x, velocity.x);

            if (swipe < -swipeConfidenceThreshold) {
              paginate(1);
            } else if (swipe > swipeConfidenceThreshold) {
              paginate(-1);
            }
          }}
        />
      </AnimatePresence>
    </>
  );
};

```

I try to solve this problem but still can't fix it, can someone help me?

答:
This looks like a bug of framer-motion.

Up until v1.6.2, everything works fine. The bug seems to occur in all later versions.

There is also an interesting changelog:

[1.6.3] 2019-08-19
Fixed
Ensuring onDragEnd always fires after if onDragStart fired.

Here is a link to the related issue on GitHub, opened by the author of this question.

Until that bug is fixed, here is a workaround that uses Pan events

export default function Carousel() {
  const animationConfidenceThreshold = 200; // you have to move the element 200px in order to perform an animation

  const [displayed, setDisplayed] = useState(0); // the index of the displayed element
  const xOffset = useMotionValue(0); // this is the motion value that drives the translation

  const lastOffset = useRef(0); // this is the lastValue of the xOffset after the Pan ended
  const elementAnimatingIn = useRef(false); // this will be set to true whilst a new element is performing its animation to the center

  useEffect(() => {
    // this happens after we have dragged the element out and triggered a rerender
    if (elementAnimatingIn.current) {
      const rightPan = xOffset.get() > 0; // check if the user drags it to the right

      // if the element has animated out to the right it animates in from the left
      xOffset.set(
        rightPan ? -1 * window.innerWidth - 200 : window.innerWidth + 200
      );
      // perform the animation to the center
      animate(xOffset, 0, {
        duration: 0.5,
        onComplete: () => {
          xOffset.stop();
        },
        onStop: () => {
          elementAnimatingIn.current = false;
          lastOffset.current = xOffset.get();
        }
      });
    }
  });

  return (

      <motion.div
        className="carouselElement"
        onPan={(e, info) => {
          xOffset.set(lastOffset.current + info.offset.x); // set the xOffset to the current offset of the pan + the prev offset
        }}
        style={{ x: xOffset }}
        onPanStart={() => {
          // check if xOffset is animating, if true stop animation and set lastOffset to current xOffset
          if (xOffset.isAnimating()) {
            xOffset.stop();
            lastOffset.current = xOffset.get();
          }
        }}
        onPanEnd={(e, info) => {
          // there can be a difference between the info.offset.x in onPan and onPanEnd
          // so we will set the xOffset to the info.offset.x when the pan ends
          xOffset.set(lastOffset.current + info.offset.x);
          lastOffset.current = xOffset.get(); // set the lastOffset to the current xOffset
          if (Math.abs(lastOffset.current) < animationConfidenceThreshold) {
            // if its only a small movement, animate back to the initial position
            animate(xOffset, 0, {
              onComplete: () => {
                lastOffset.current = 0;
              }
            });
          } else {
            // perform the animation to the next element
            const rightPan = xOffset.get() > 0; // check if the user drags it to the right
            animate(
              xOffset,
              rightPan ? window.innerWidth + 200 : -1 * window.innerWidth - 200, // animate out of view
              {
                duration: 0.5,
                onComplete: () => {
                  // after the element has animated out
                  // stop animation (it does not do this on its own, only one animation can happen at a time)
                  xOffset.stop();
                  elementAnimatingIn.current = true;
                  // trigger a rerender with the new content - now the useEffect runs
                  setDisplayed(rightPan ? displayed - 1 : displayed + 1);
                }
              }
            );
          }
        }}
      >

          {"I am element #" + displayed}

      </motion.div>

  );
}
```

Check this codesandbox out!

Title: slideshow stuck framer motion

Body:
I want to make a slide show in framer motion and I found that in framer motion docs they have an example slide show like this https://codesandbox.io/s/framer-motion-image-gallery-pqvx3?from-embed=&file=/src/Example.tsx, but I found a bug when we drag and double click it, it will be stuck like this picture .

import * as React from "react";
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { wrap } from "popmotion";
import { images } from "./image-data";

const variants = {
  enter: (direction: number) => {
    return {
      x: direction > 0 ? 1000 : -1000,
      opacity: 0
    };
  },
  center: {
    zIndex: 1,
    x: 0,
    opacity: 1
  },
  exit: (direction: number) => {
    return {
      zIndex: 0,
      x: direction < 0 ? 1000 : -1000,
      opacity: 0
    };
  }
};
const swipeConfidenceThreshold = 10000;
const swipePower = (offset: number, velocity: number) => {
  return Math.abs(offset) * velocity;
};

export const Example = () => {
  const [[page, direction], setPage] = useState([0, 0]);images.
  const imageIndex = wrap(0, images.length, page);

  const paginate = (newDirection: number) => {
    setPage([page + newDirection, newDirection]);
  };

  return (
    <>
      <AnimatePresence initial={false} custom={direction}>
        <motion.img
          key={page}
          src={images[imageIndex]}
          custom={direction}
          variants={variants}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{
            x: { type: "spring", stiffness: 300, damping: 30 },
            opacity: { duration: 0.2 }
          }}
          drag="x"
          dragConstraints={{ left: 0, right: 0 }}
          dragElastic={1}
          onDragEnd={(e, { offset, velocity }) => {
            const swipe = swipePower(offset.x, velocity.x);

            if (swipe < -swipeConfidenceThreshold) {
              paginate(1);
            } else if (swipe > swipeConfidenceThreshold) {
              paginate(-1);
            }
          }}
        />
      </AnimatePresence>
    </>
  );
};

I try to solve this problem but still can't fix it, can someone help me?

Body:
This looks like a bug of framer-motion.

Up until v1.6.2, everything works fine. The bug seems to occur in all later versions.

There is also an interesting changelog:

[1.6.3] 2019-08-19
Fixed
Ensuring onDragEnd always fires after if onDragStart fired.

Here is a link to the related issue on GitHub, opened by the author of this question.

Until that bug is fixed, here is a workaround that uses Pan events

export default function Carousel() {
  const animationConfidenceThreshold = 200; // you have to move the element 200px in order to perform an animation

  const [displayed, setDisplayed] = useState(0); // the index of the displayed element
  const xOffset = useMotionValue(0); // this is the motion value that drives the translation

  const lastOffset = useRef(0); // this is the lastValue of the xOffset after the Pan ended
  const elementAnimatingIn = useRef(false); // this will be set to true whilst a new element is performing its animation to the center

  useEffect(() => {
    // this happens after we have dragged the element out and triggered a rerender
    if (elementAnimatingIn.current) {
      const rightPan = xOffset.get() > 0; // check if the user drags it to the right

      // if the element has animated out to the right it animates in from the left
      xOffset.set(
        rightPan ? -1 * window.innerWidth - 200 : window.innerWidth + 200
      );
      // perform the animation to the center
      animate(xOffset, 0, {
        duration: 0.5,
        onComplete: () => {
          xOffset.stop();
        },
        onStop: () => {
          elementAnimatingIn.current = false;
          lastOffset.current = xOffset.get();
        }
      });
    }
  });

  return (
    <div className="container">
      <motion.div
        className="carouselElement"
        onPan={(e, info) => {
          xOffset.set(lastOffset.current + info.offset.x); // set the xOffset to the current offset of the pan + the prev offset
        }}
        style={{ x: xOffset }}
        onPanStart={() => {
          // check if xOffset is animating, if true stop animation and set lastOffset to current xOffset
          if (xOffset.isAnimating()) {
            xOffset.stop();
            lastOffset.current = xOffset.get();
          }
        }}
        onPanEnd={(e, info) => {
          // there can be a difference between the info.offset.x in onPan and onPanEnd
          // so we will set the xOffset to the info.offset.x when the pan ends
          xOffset.set(lastOffset.current + info.offset.x);
          lastOffset.current = xOffset.get(); // set the lastOffset to the current xOffset
          if (Math.abs(lastOffset.current) < animationConfidenceThreshold) {
            // if its only a small movement, animate back to the initial position
            animate(xOffset, 0, {
              onComplete: () => {
                lastOffset.current = 0;
              }
            });
          } else {
            // perform the animation to the next element
            const rightPan = xOffset.get() > 0; // check if the user drags it to the right
            animate(
              xOffset,
              rightPan ? window.innerWidth + 200 : -1 * window.innerWidth - 200, // animate out of view
              {
                duration: 0.5,
                onComplete: () => {
                  // after the element has animated out
                  // stop animation (it does not do this on its own, only one animation can happen at a time)
                  xOffset.stop();
                  elementAnimatingIn.current = true;
                  // trigger a rerender with the new content - now the useEffect runs
                  setDisplayed(rightPan ? displayed - 1 : displayed + 1);
                }
              }
            );
          }
        }}
      >
        <span style={{ userSelect: "none" }}>
          {"I am element #" + displayed}
        </span>
      </motion.div>
    </div>
  );
}

Check this codesandbox out!


问:
Problem with kv file in visual studio code
I'm trying to setup Visual Studio Code for python and everything is good except Kivy.

I have simple code

```<code>import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget

class MyGrid(Widget):
    pass

class MyApp(App):
    def build(self):
        return MyGrid()

if __name__ == "__main__":
    MyApp().run()
</code>```

and simple kivy file

```<code>    #:kivy
<MyGrid>:
    GridLayout:
        cols:1
        size: root.width, root.height

        GridLayout:
            cols:2

            Label:
                text: "Name: "

            TextInput:
                multinline:False

            Label:
                text: "Email: "

            TextInput:
                multiline:False

        Button:
            text:"Submit"
</code>```

And when I'm trying to run python file I got

kivy.lang.parser.ParserException: Parser: File "c:\Users\Paweł\Documents\projects vscode\WeatherProject\my.kv", line 1:
1:#:kivy
2::
3:GridLayout:
Unknown directive

Google isn't helpful at all. Please tell me what should I do.

答:
remove the indent from
GridLayout:</p>

Body:
I'm trying to setup Visual Studio Code for python and everything is good except Kivy.

I have simple code

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget

class MyGrid(Widget):
    pass

class MyApp(App):
    def build(self):
        return MyGrid()

if __name__ == "__main__":
    MyApp().run()

and simple kivy file

    #:kivy
<MyGrid>:
    GridLayout:
        cols:1
        size: root.width, root.height

        GridLayout:
            cols:2

            Label:
                text: "Name: "

            TextInput:
                multinline:False

            Label:
                text: "Email: "

            TextInput:
                multiline:False

        Button:
            text:"Submit"

And when I'm trying to run python file I got

kivy.lang.parser.ParserException: Parser: File "c:\Users\Paweł\Documents\projects vscode\WeatherProject\my.kv", line 1:
1:#:kivy
2::
3:GridLayout:
Unknown directive

Google isn't helpful at all. Please tell me what should I do.

Body:
remove the indent from
GridLayout:


问:
Good way to make Userdialog.Instance.Progress wait for method to execute C# Xamarin
I'm trying to show a progress dialog showing the percent done with the method to wait everything + an await Task.Delay(20); And an await for the method I want to execute. Now I notice that with that task.delay the execution takes much longer.

What I want to achieve instead is that the progress.dialog calculates how long the method takes instead of putting a delay on it because this works a bit more slowly.

What are my options in this?

This is my code

```<code>    private async Task DownloadAllAlert()
    {
        //alert to download everything
        bool result = await DisplayAlert("Download", "Do you want to download everything?", "Yes", "No"); ;

        //alert is user chose yes
        if (result)
        {
            // loading dialog in percentage till downloading is done
            using (var progress = UserDialogs.Instance.Progress("Loading..."))
            {
                for (var i = 0; i < 100; i++)
                {
                    progress.PercentComplete = i;
                    await Api.DownloadAll();
                    await Task.Delay(20);
                }
            }
        }
    }
</code>```

答:
try using Task in c#.

```<code>using (var progress = UserDialogs.Instance.Progress("Loading..."))
{
    await LoadData(ref progress);
}

</code>```

call this function

```<code>public async Task LoadData(ref IProgressDialog progress);
{
  //await Task.Yield(); //add this line of code if on ios didnt work

 Task task1 = new Task(() =>
    {
        for (int i = 0; i < 50 ; i++) // loop untill 50% then increase sleeping thread time
        {
            progress.PercentComplete = i;
            //sleeping for 1 second
            Thread.Sleep(1000);
        }
        for (int i = 50; i < 100; i++) // loop untill 99% then stop
        {
            progress.PercentComplete = i;
            //sleeping for 2 second
            Thread.Sleep(2000);
        }
        Console.WriteLine("Task 1 complete");
    });

    Task task2 = new Task(() =>
    {
        await Api.DownloadAll();
        Console.WriteLine("Task 2 complete");
    });

    //starting the tasks
    task1.Start();
    task2.Start();
    Task.WaitAny(task2);
    progress.PercentComplete = 100; // when task2 finish put it 100%
}
</code>```

Body:
I'm trying to show a progress dialog showing the percent done with the method to wait everything + an await Task.Delay(20); And an await for the method I want to execute. Now I notice that with that task.delay the execution takes much longer.

What I want to achieve instead is that the progress.dialog calculates how long the method takes instead of putting a delay on it because this works a bit more slowly.

What are my options in this?

This is my code

    private async Task DownloadAllAlert()
    {
        //alert to download everything
        bool result = await DisplayAlert("Download", "Do you want to download everything?", "Yes", "No"); ;

        //alert is user chose yes
        if (result)
        {
            // loading dialog in percentage till downloading is done
            using (var progress = UserDialogs.Instance.Progress("Loading..."))
            {
                for (var i = 0; i < 100; i++)
                {
                    progress.PercentComplete = i;
                    await Api.DownloadAll();
                    await Task.Delay(20);
                }
            }
        }
    }

Body:
try using Task in c#.

using (var progress = UserDialogs.Instance.Progress("Loading..."))
{
    await LoadData(ref progress);
}

call this function

public async Task LoadData(ref IProgressDialog progress);
{
  //await Task.Yield(); //add this line of code if on ios didnt work

 Task task1 = new Task(() =>
    {
        for (int i = 0; i < 50 ; i++) // loop untill 50% then increase sleeping thread time
        {
            progress.PercentComplete = i;
            //sleeping for 1 second
            Thread.Sleep(1000);
        }
        for (int i = 50; i < 100; i++) // loop untill 99% then stop
        {
            progress.PercentComplete = i;
            //sleeping for 2 second
            Thread.Sleep(2000);
        }
        Console.WriteLine("Task 1 complete");
    });

    Task task2 = new Task(() =>
    {
        await Api.DownloadAll();
        Console.WriteLine("Task 2 complete");
    });

    //starting the tasks
    task1.Start();
    task2.Start();
    Task.WaitAny(task2);
    progress.PercentComplete = 100; // when task2 finish put it 100%
}


问:
How would you read S3 as a hierarchical directory structure in Ruby?
Has anyone had any success reading S3 buckets as subfolders?

folder1

-- subfolder2

---- file3

---- file4

-- file1

-- file2

folder2

-- subfolder3

-- file5

-- file6

My task is to read folder1.  I expect to see subfolder2, file1 and file2, but NOT file3 or file4.  Right now, because I restrict the bucket keys to prefix => 'folder1/', you still get file3 and 4 since they technically have the folder1 prefix.

It seems the only way to really do this is suck in all the keys under folder1 and then use string searching to actually exclude file3 and file4 from your results array.

Has anyone had experience doing this?  I know FTP-style S3 clients like Transmit and Cyberduck must be doing this but it's not apparent from the S3 API itself.

Thanks ahead,
Conrad

I've looked into both AWS::S3 and right_aws.

答: comes a little late, but as this is still a very popular search engine result: check out the 'delimiter' request property (https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/ListObjectsV2Request.html#setDelimiter-java.lang.String-). setting it to "/" will retrieve a list of direct subfolders for any given prefix.</p>

ContentLicense: CC BY-SA 2.5


问:
RIGHT JOIN in Oracle query
I have large Oracle query, but I would like to have a RIGHT JOIN on the below line of code, I tried to use (+) but does not work:

```<code>AND SUBSTR(IBT_LINE.USER_1, 0, INSTR(IBT_LINE.USER_1, '-', +1, 3)-1) =
  SUBSTR(WORK_ORDER.USER_1, 0, INSTR(WORK_ORDER.USER_1, '-', +1, 3)-1)
</code>```

The total query:

```<code>FROM
    CUSTOMER_ORDER, IBT, IBT_LINE,PART, WORK_ORDER
WHERE
    CUSTOMER_ORDER.ID = REPLACE(IBT.ID,'X','C')
    AND IBT.ID = IBT_LINE.IBT_ID
    AND IBT_LINE.PART_ID=PART.ID
    AND SUBSTR(IBT_LINE.USER_1, 0, INSTR(IBT_LINE.USER_1, '-', +1, 3)-1) = SUBSTR(WORK_ORDER.USER_1, 0, INSTR(WORK_ORDER.USER_1, '-', +1, 3)-1)
    AND WORK_ORDER.WAREHOUSE_ID ='MEX-04' AND WORK_ORDER.STATUS  ='R'
</code>```

答:
It's impossible to do a right/left join with two tables, and have a mandatory value on a field of that table in the same select.
Your problem is not with sintax (+ or JOIN), yout problem is with your select.

You're trying to get an outer join in WORK_ORDER and IBT_LINE, but you are telling oracle to do a full join with this sentence:

....
   AND WORK_ORDER.WAREHOUSE_ID ='MEX-04' AND WORK_ORDER.STATUS  ='R'

You can try a subselect in your FROM,

```<code>....
FROM
    CUSTOMER_ORDER, IBT, IBT_LINE,PART,
     (SELECT SUBSTR(WORK_ORDER.USER_1, 0, INSTR(WORK_ORDER.USER_1, '-', +1, 3)-1) user_1_formatted
              from WORK_ORDER
              where WORK_ORDER.WAREHOUSE_ID ='MEX-04'
              AND WORK_ORDER.STATUS  ='R') sub_work_order
WHERE
CUSTOMER_ORDER.ID = REPLACE(IBT.ID,'X','C')
    AND IBT.ID = IBT_LINE.IBT_ID
    AND IBT_LINE.PART_ID=PART.ID
    AND SUBSTR(IBT_LINE.USER_1, 0, INSTR(IBT_LINE.USER_1, '-', +1, 3)-1) = sub_work_order.user_1_formatted(+)
</code>```

or a subselect and then filter your results, as you wish.

```<code>select *
from (select ... from
    CUSTOMER_ORDER, IBT, IBT_LINE,PART, WORK_ORDER
WHERE
    CUSTOMER_ORDER.ID = REPLACE(IBT.ID,'X','C')
    AND IBT.ID = IBT_LINE.IBT_ID
    AND IBT_LINE.PART_ID=PART.ID
    AND SUBSTR(IBT_LINE.USER_1, 0, INSTR(IBT_LINE.USER_1, '-', +1, 3)-1) = SUBSTR(WORK_ORDER.USER_1, 0, INSTR(WORK_ORDER.USER_1, '-', +1, 3)-1) (+))
  where (work_order is null or (WORK_ORDER.WAREHOUSE_ID ='MEX-04' AND WORK_ORDER.STATUS  ='R'))
</code>```

Title: RIGHT JOIN in Oracle query

Body:
I have large Oracle query, but I would like to have a RIGHT JOIN on the below line of code, I tried to use (+) but does not work:

AND SUBSTR(IBT_LINE.USER_1, 0, INSTR(IBT_LINE.USER_1, '-', +1, 3)-1) =
  SUBSTR(WORK_ORDER.USER_1, 0, INSTR(WORK_ORDER.USER_1, '-', +1, 3)-1)

The total query:

FROM
    CUSTOMER_ORDER, IBT, IBT_LINE,PART, WORK_ORDER
WHERE
    CUSTOMER_ORDER.ID = REPLACE(IBT.ID,'X','C')
    AND IBT.ID = IBT_LINE.IBT_ID
    AND IBT_LINE.PART_ID=PART.ID
    AND SUBSTR(IBT_LINE.USER_1, 0, INSTR(IBT_LINE.USER_1, '-', +1, 3)-1) = SUBSTR(WORK_ORDER.USER_1, 0, INSTR(WORK_ORDER.USER_1, '-', +1, 3)-1)
    AND WORK_ORDER.WAREHOUSE_ID ='MEX-04' AND WORK_ORDER.STATUS  ='R'

Body:
It's impossible to do a right/left join with two tables, and have a mandatory value on a field of that table in the same select.
Your problem is not with sintax (+ or JOIN), yout problem is with your select.

You're trying to get an outer join in WORK_ORDER and IBT_LINE, but you are telling oracle to do a full join with this sentence:

....
   AND WORK_ORDER.WAREHOUSE_ID ='MEX-04' AND WORK_ORDER.STATUS  ='R'

You can try a subselect in your FROM,

....
FROM
    CUSTOMER_ORDER, IBT, IBT_LINE,PART,
     (SELECT SUBSTR(WORK_ORDER.USER_1, 0, INSTR(WORK_ORDER.USER_1, '-', +1, 3)-1) user_1_formatted
              from WORK_ORDER
              where WORK_ORDER.WAREHOUSE_ID ='MEX-04'
              AND WORK_ORDER.STATUS  ='R') sub_work_order
WHERE
CUSTOMER_ORDER.ID = REPLACE(IBT.ID,'X','C')
    AND IBT.ID = IBT_LINE.IBT_ID
    AND IBT_LINE.PART_ID=PART.ID
    AND SUBSTR(IBT_LINE.USER_1, 0, INSTR(IBT_LINE.USER_1, '-', +1, 3)-1) = sub_work_order.user_1_formatted(+)

or a subselect and then filter your results, as you wish.

select *
from (select ... from
    CUSTOMER_ORDER, IBT, IBT_LINE,PART, WORK_ORDER
WHERE
    CUSTOMER_ORDER.ID = REPLACE(IBT.ID,'X','C')
    AND IBT.ID = IBT_LINE.IBT_ID
    AND IBT_LINE.PART_ID=PART.ID
    AND SUBSTR(IBT_LINE.USER_1, 0, INSTR(IBT_LINE.USER_1, '-', +1, 3)-1) = SUBSTR(WORK_ORDER.USER_1, 0, INSTR(WORK_ORDER.USER_1, '-', +1, 3)-1) (+))
  where (work_order is null or (WORK_ORDER.WAREHOUSE_ID ='MEX-04' AND WORK_ORDER.STATUS  ='R'))


问:
Are "How to delete an item from state array?" answers wrong cuz setState is async?
In this SO question, all the answers use this form of setState:

```<code>this.setState( { items: this.state.items.filter() } )
</code>```

Which means this is a case of "new state is derived from the current state".

However, in this React Doc about async behavior of setState, in this case, this callback form MUST be used instead:

this.setState( currState => ( { items: currState.items.filter() } ) )
```

My question is, are those answer all wrong, and if so, what are the consequences? Or is it somehow still acceptable?

答:
The issue only occurs if your code design is (what I think) "bad". Normally, you expect to update the value that is used in the current render. So for example, if the currently displayed num is 5, and you want to increase it, you would want the number to be 6. But if you now set the num to 10 before doing setNum(num + 1), the output won't be 11, but 6, because it used the currently rendered value (5) + 1 (Which is what I would expect). If you wanted it to use "the current state", so the 10 from the previous setNum, you would need to use the callback version.

That was sort of complicated, so here an example:

```<code>import React, { useState } from 'react';

export default ({ name }) => {
  const [num, setNum] = useState(5);

  return (
    <React.Fragment>
      <h1>{num}</h1>
      <button onClick={changed}>Change!</button>
      <button onClick={changedWithCallback}>Change with callback!</button>
      <button onClick={resetted}>Reset!</button>
    </React.Fragment>
  );

  function changed() {
    setNum(10);
    setNum(num + 1);
  }

  function changedWithCallback() {
    setNum(10);
    setNum((state) => state + 1);
  }

  function resetted() {
    setNum(5);
  }
};
</code>```

Working example

Body:
In this SO question, all the answers use this form of setState:

this.setState( { items: this.state.items.filter() } )

Which means this is a case of "new state is derived from the current state".

However, in this React Doc about async behavior of setState, in this case, this callback form MUST be used instead:

this.setState( currState => ( { items: currState.items.filter() } ) )

My question is, are those answer all wrong, and if so, what are the consequences? Or is it somehow still acceptable?

Body:
The issue only occurs if your code design is (what I think) "bad". Normally, you expect to update the value that is used in the current render. So for example, if the currently displayed num is 5, and you want to increase it, you would want the number to be 6. But if you now set the num to 10 before doing setNum(num + 1), the output won't be 11, but 6, because it used the currently rendered value (5) + 1 (Which is what I would expect). If you wanted it to use "the current state", so the 10 from the previous setNum, you would need to use the callback version.

That was sort of complicated, so here an example:

import React, { useState } from 'react';

export default ({ name }) => {
  const [num, setNum] = useState(5);

  return (
    <React.Fragment>
      <h1>{num}</h1>
      <button onClick={changed}>Change!</button>
      <button onClick={changedWithCallback}>Change with callback!</button>
      <button onClick={resetted}>Reset!</button>
    </React.Fragment>
  );

  function changed() {
    setNum(10);
    setNum(num + 1);
  }

  function changedWithCallback() {
    setNum(10);
    setNum((state) => state + 1);
  }

  function resetted() {
    setNum(5);
  }
};

Working example


问:
Azure Operation returned an invalid status 'Conflict'
I am having below error while running powershell</p>
```<code>$thumbprint=$(az webapp config ssl upload --certificate-file $Path --certificate-password $(pwd) --name $env:APP_NAME --resource-group $env:RG_NAME --query thumbprint --output tsv)

{"Code":"Conflict","Message":"Another certificate exists with same thumbprint xxxxxxxxxxxxxxxxxxxxxxxxxxx at location xxxxxx in the Resource Group xxxxxx.","Target":null,"Details":[{"Message":"Another certificate exists with same thumbprint xxxxxxxxxxxxxxxxxxxxxxxxxxx at location xxxxxx in the Resource Group xxxxxx."},{"Code":"Conflict"},{"ErrorEntity":{"ExtendedCode":"53008","MessageTemplate":"Another certificate exists with same thumbprint {0} at location {1} in the Resource Group {2}.","Parameters":["xxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxx","xxxxxx"],"Code":"Conflict","Message":"Another certificate exists with same thumbprint xxxxxxxxxxxxxxxxxxxxxxxxxxx at location xxxxxx in the Resource Group xxxxxx."}}],"Innererror":null}
</code>```

答:
When you try to upload an existing certificate with a different certificate name, you get this error.                                                                                Running ARM template as part of CI/CD workflow (after doing the initial setup via portal) is the most common scenario. Uploading the same certificate into two distinct AppServicePlans is another common scenario (which are in the same WebSpace).

You can resolve this by changing the ARM template so that certificate resource name matches with what you have in the Resource Explorer. Alternatively, you can delete the old certificate and run the ARM template.

To obtain the Certificate Resource name, you can try the PowerShell scripts listed below.

```<code>$resourceGroupName = "SixShotRG"
$thumbprint = "78311D191030008F5D7EEDC0FCC295AFEED5DFD7"

$certificates = Get-AzResource `
 -ResourceGroupName $resourceGroupName `

 -ResourceType Microsoft.Web/certificates
Write-Host ("Looking for thumbprint "  + $thumbprint + "..."  )
Write-Host ("`tFound "  + $certificates.Count `
+ " certificates in ResourceGroup : "  `
+ $resourceGroupName `
+ $resourceGroup.Name)
foreach  ($certificate **in**  $certificates) {
 $cert = Get-AzResource `
-ResourceGroupName $resourceGroupName `
-ResourceType Microsoft.Web/certificates `
-ResourceName $certificate.Name
if  ($thumbprint -eq $cert.properties.thumbprint) {
Write-Host ("`tFound our cert in "  `
+ $cert.properties.webSpace `
+ ' webspace')
+ Write-Host ("`tCert name is "  `
+ $cert.Name)
 Exit
}
}
</code>```

Body:
I am having below error while running powershell

$thumbprint=$(az webapp config ssl upload --certificate-file $Path --certificate-password $(pwd) --name $env:APP_NAME --resource-group $env:RG_NAME --query thumbprint --output tsv)

{"Code":"Conflict","Message":"Another certificate exists with same thumbprint xxxxxxxxxxxxxxxxxxxxxxxxxxx at location xxxxxx in the Resource Group xxxxxx.","Target":null,"Details":[{"Message":"Another certificate exists with same thumbprint xxxxxxxxxxxxxxxxxxxxxxxxxxx at location xxxxxx in the Resource Group xxxxxx."},{"Code":"Conflict"},{"ErrorEntity":{"ExtendedCode":"53008","MessageTemplate":"Another certificate exists with same thumbprint {0} at location {1} in the Resource Group {2}.","Parameters":["xxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxx","xxxxxx"],"Code":"Conflict","Message":"Another certificate exists with same thumbprint xxxxxxxxxxxxxxxxxxxxxxxxxxx at location xxxxxx in the Resource Group xxxxxx."}}],"Innererror":null}

Body:
When you try to upload an existing certificate with a different certificate name, you get this error.                                                                                Running ARM template as part of CI/CD workflow (after doing the initial setup via portal) is the most common scenario. Uploading the same certificate into two distinct AppServicePlans is another common scenario (which are in the same WebSpace).

You can resolve this by changing the ARM template so that certificate resource name matches with what you have in the Resource Explorer. Alternatively, you can delete the old certificate and run the ARM template.

To obtain the Certificate Resource name, you can try the PowerShell scripts listed below.

$resourceGroupName = "SixShotRG"
$thumbprint = "78311D191030008F5D7EEDC0FCC295AFEED5DFD7"

$certificates = Get-AzResource `
 -ResourceGroupName $resourceGroupName `

 -ResourceType Microsoft.Web/certificates
Write-Host ("Looking for thumbprint "  + $thumbprint + "..."  )
Write-Host ("`tFound "  + $certificates.Count `
+ " certificates in ResourceGroup : "  `
+ $resourceGroupName `
+ $resourceGroup.Name)
foreach  ($certificate **in**  $certificates) {
 $cert = Get-AzResource `
-ResourceGroupName $resourceGroupName `
-ResourceType Microsoft.Web/certificates `
-ResourceName $certificate.Name
if  ($thumbprint -eq $cert.properties.thumbprint) {
Write-Host ("`tFound our cert in "  `
+ $cert.properties.webSpace `
+ ' webspace')
+ Write-Host ("`tCert name is "  `
+ $cert.Name)
 Exit
}
}


问:
Combining three chart types Apex charts on Angular
I would like to combine 3 chart types. How to get Pulse series to show on chart as scatter? When base chart.type is line it will not show. If it's changed to scatter for example, Pulse will show up but it also effectively disables lines. Desired end result is Pulse will show as scatter dots and other types stay as they are.

        {
          name: "Income",
          type: "column",
          data: [1.4, 2, 0, 1.5, 2.5, 2.8, 3.8, 4.6]
        },
        {
          name: "Cashflow",
          type: "column",
          data: [0, 3, 3.1, 4, 4.1, 4.9, 6.5, 8.5]
        },
        {
          name: "Revenue",
          type: "line",
          data: [0, 0, 37, 36, 44, 45, 50, 58]
        }
        ,
        {
          name: "Pulse",
          type: "scatter",
          data: [10, 15, 37, 36, 44, 90, 50, 20]
        }
      ],
      chart: {
        height: 350,
        type: "line",
        stacked: false
      },
```

Here is the problem: https://codesandbox.io/s/apx-combo-multiple-yaxis-forked-x7okb?file=/src/app/app.component.ts

Maybe it's how Apex charts works under the hood and some chart types cannot be combined.

答:
Scatter chart added with Line chart and Column chart.

code - https://codesandbox.io/s/apex-chart-combine-three-xclhy

Output -

Body:
I would like to combine 3 chart types. How to get Pulse series to show on chart as scatter? When base chart.type is line it will not show. If it's changed to scatter for example, Pulse will show up but it also effectively disables lines. Desired end result is Pulse will show as scatter dots and other types stay as they are.

        {
          name: "Income",
          type: "column",
          data: [1.4, 2, 0, 1.5, 2.5, 2.8, 3.8, 4.6]
        },
        {
          name: "Cashflow",
          type: "column",
          data: [0, 3, 3.1, 4, 4.1, 4.9, 6.5, 8.5]
        },
        {
          name: "Revenue",
          type: "line",
          data: [0, 0, 37, 36, 44, 45, 50, 58]
        }
        ,
        {
          name: "Pulse",
          type: "scatter",
          data: [10, 15, 37, 36, 44, 90, 50, 20]
        }
      ],
      chart: {
        height: 350,
        type: "line",
        stacked: false
      },

Here is the problem: https://codesandbox.io/s/apx-combo-multiple-yaxis-forked-x7okb?file=/src/app/app.component.ts

Maybe it's how Apex charts works under the hood and some chart types cannot be combined.


问:
How to get all dependency files for a program
I make a program in Go and after completing the code, if I want to run this code on other pc or VM, then it does not get all the dependency package files. How can I get all dependency files?</p>

答: If you are using module mode, you can try go mod tidy, as described here.


问:
Java Generics, why is it illegal to use inheritance in generics?
I have this structure:

```<code>///Creep.java///
public interface Creep extends Movable<Position2D> {
  ...
}

///Movable.java///
public interface Movable<T extends Position2D> {
        ...
    void setMovementStrategy(MovementStrategy<Movable<T>> movementStrategy);
    MovementStrategy<Movable<T>> getMovementStrategy();
}

///MovementStrategy.java///
public interface MovementStrategy<T extends Movable<? extends Position2D>> {
  void executeMovement(T movable);
}

///CreepImpl.java///
public class CreepImpl implements Creep {
...

 @Override
 public void setMovementStrategy(MovementStrategy<Creep> movementStrategy) {
    // TODO Auto-generated method stub

 }

 @Override
 public MovementStrategy<Creep> getMovementStrategy() {
    return null;
 }

}
</code>```

My problem is that generics doesn't like MovementStrategy<Creep> but it does accept MovementStrategy<Movable<Position2D>> Which i think is strange as Creep extends Movable<Position2D>. This in the context of the methods public MovementStrategy<Creep> getMovementStrategy() and public MovementStrategy<Creep> getMovementStrategy()

Isn't this possible? or maybe im doing something wrong?

Any help is appreciated!

EDIT

Forgot to include MovementStrategy source.. doh!

答:
Probably you don't even need generics with MovementStrategy. Try not to create that much generics complexity.

Original answer: You can use the extends keyword: MovementStrategy<? extends Movable>

This is needed to preserve compile-time safety.

Imagine the following was possible: Creep extends Movable, Wind extends Movable

```<code>MovementStrategy<Movable> strategy = new MovementStrategy<Wind>();
strategy.setTargetObject(new Creep()); //fails
</code>```

The 2nd like fails at runtime, because it expects Wind, but you give it a Creep

Body:
I have this structure:

///Creep.java///
public interface Creep extends Movable<Position2D> {
  ...
}

///Movable.java///
public interface Movable<T extends Position2D> {
        ...
    void setMovementStrategy(MovementStrategy<Movable<T>> movementStrategy);
    MovementStrategy<Movable<T>> getMovementStrategy();
}

///MovementStrategy.java///
public interface MovementStrategy<T extends Movable<? extends Position2D>> {
  void executeMovement(T movable);
}

///CreepImpl.java///
public class CreepImpl implements Creep {
...

 @Override
 public void setMovementStrategy(MovementStrategy<Creep> movementStrategy) {
    // TODO Auto-generated method stub

 }

 @Override
 public MovementStrategy<Creep> getMovementStrategy() {
    return null;
 }

}

My problem is that generics doesn't like MovementStrategy<Creep> but it does accept MovementStrategy<Movable<Position2D>> Which i think is strange as Creep extends Movable<Position2D>. This in the context of the methods public MovementStrategy<Creep> getMovementStrategy() and public MovementStrategy<Creep> getMovementStrategy()

Isn't this possible? or maybe im doing something wrong?

Any help is appreciated!

EDIT

Forgot to include MovementStrategy source.. doh!

Body:
Probably you don't even need generics with MovementStrategy. Try not to create that much generics complexity.

Original answer: You can use the extends keyword: MovementStrategy<? extends Movable>

This is needed to preserve compile-time safety.

Imagine the following was possible: Creep extends Movable, Wind extends Movable

MovementStrategy<Movable> strategy = new MovementStrategy<Wind>();
strategy.setTargetObject(new Creep()); //fails

The 2nd like fails at runtime, because it expects Wind, but you give it a Creep


问:
Matplotlib histogram label text crowded
I'm making a histogram in matplotlib and the text label for each bin are overlapping on each other like this:

I tried to rotate the labels on the x-axis by following another solution

```<code>cuisine_hist = plt.hist(train.cuisine, bins=100)
cuisine_hist.set_xticklabels(rotation=45)
plt.show()
</code>```

But I get error message 'tuple' object has no attribute 'set_xticklabels'. Why? How do I solve this problem? Alternatively, how can I "transpose" the plot so the labels are on the vertical axis?

答:
just this simple line would do the trick</p>
```<code>plt.xticks(rotation=45)
</code>```

Title: Matplotlib histogram label text crowded

Body:
I'm making a histogram in matplotlib and the text label for each bin are overlapping on each other like this:

I tried to rotate the labels on the x-axis by following another solution

cuisine_hist = plt.hist(train.cuisine, bins=100)
cuisine_hist.set_xticklabels(rotation=45)
plt.show()

But I get error message 'tuple' object has no attribute 'set_xticklabels'. Why? How do I solve this problem? Alternatively, how can I "transpose" the plot so the labels are on the vertical axis?

Body:
just this simple line would do the trick

plt.xticks(rotation=45)


问:
Display all data of all tables
I want to display all data in my Database without writing a select for each table - how can I do this?

I do not want to do this:

```<code>select * from Customer
select * from Employee
select .............
</code>```

I am using TSQL with MSSQL Server.

答: Use database admin tools to dump the database without schema.</p>

Title: Display all data of all tables

Body:
I want to display all data in my Database without writing a select for each table - how can I do this?

I do not want to do this:

select * from Customer
select * from Employee
select .............

I am using TSQL with MSSQL Server.


问:
How to validate the K8s secret is base64 encoded in helm diff command?
In the K8s secret manifest I put the secret at data field as non-base64 encoded secret. The helm diff execution works great and returns exit code 2 for diff. However for helm upgrade it failed exit code 1 because the secret data is not base64 encoded.

I would like to know if there is a way to verify at helm diff stage that the secret is non-base64 encoded.

Thanks

答:
If you want to use secrets with helm you have 2 options. Either declare them with stringData, or use the b64enc function.

1. StringData

StringData does not have to be base64 encoded. In fact, it should not be encoded.

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
stringData:
  password:  {{ .Values.password }}
```
<h3>2. b64enc</h3>
<p>Alternatively, encode the raw string to base64.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
string:
  password: {{ .Values.password | b64enc }}
</code>```

Body:
If you want to use secrets with helm you have 2 options. Either declare them with stringData, or use the b64enc function.

1. StringData

StringData does not have to be base64 encoded. In fact, it should not be encoded.

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
stringData:
  password:  {{ .Values.password }}

2. b64enc

Alternatively, encode the raw string to base64.

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
string:
  password: {{ .Values.password | b64enc }}


问:
Refactoring a nested loop into Java 8 streams collecting the outer objects
I have a loop which does what I want - it adds objects of type A to the results list:

```<code>ArrayList<A> results = new ArrayList<>();
for (A a: listOfA) {
  for (B b : a.getListOfB()) {
    if ("myString".equals(b.getMyString())) {
      results.add(a);
    }
  }
}
</code>```

Now I'd like to refactor my code using Java 8 streams and I came up with this solution I'm stuck with because it collects objects of type B instead of A - List results = ... is obviously wrong:

```<code>List<A> results = listOfA.stream()
  .flatMap(a -> a.getListOfB().stream())
  .filter(b -> "myString".equals(b.getMyString()))
  .collect(Collectors.toList());
</code>```

How can I collect a list of type A using Java 8 streams?

I found many results here in SO looking for [java]  nested foreach stream but I couldn't find anything that suits my needs.

答:
You don't need flatMap here. Just apply a filter on the Stream.

```<code>List<A> results =
    listOfA.stream()
           .filter(a -> a.getListOfB()
                         .stream()
                         .anyMatch(b -> "myString".equals(b.getMyString())))
           .collect(Collectors.toList());
</code>```

This is assuming you don't want to add an instance of A multiple times to the List if it has multiple B instances that match "myString".

Body:
I have a loop which does what I want - it adds objects of type A to the results list:

ArrayList results = new ArrayList<>();
for (A a: listOfA) {
  for (B b : a.getListOfB()) {
    if ("myString".equals(b.getMyString())) {
      results.add(a);
    }
  }
}

Now I'd like to refactor my code using Java 8 streams and I came up with this solution I'm stuck with because it collects objects of type B instead of A - List results = ... is obviously wrong:

List results = listOfA.stream()
  .flatMap(a -> a.getListOfB().stream())
  .filter(b -> "myString".equals(b.getMyString()))
  .collect(Collectors.toList());

How can I collect a list of type A using Java 8 streams?

I found many results here in SO looking for [java]  nested foreach stream but I couldn't find anything that suits my needs.

Body:
You don't need flatMap here. Just apply a filter on the Stream<A>.

List<A> results =
    listOfA.stream()
           .filter(a -> a.getListOfB()
                         .stream()
                         .anyMatch(b -> "myString".equals(b.getMyString())))
           .collect(Collectors.toList());

This is assuming you don't want to add an instance of A multiple times to the List if it has multiple B instances that match "myString".


问:
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse
I created an application with ionic with the help of this tutorial: http://masteringionic.com/blog/2016-12-15-using-php-and-mysql-with-ionic/ a school programm

But when i want to select all my client, i get this error :

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttp…, text

My PHP script :

```<code>    <?php

   // Define database connection parameters
   $hn      = 'localhost';
   $un      = 'root';
   $pwd     = '';
   $db      = 'equida';
   $cs      = 'utf8';

   // Set up the PDO parameters
   $dsn     = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
   $opt     = array(
                        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                        PDO::ATTR_EMULATE_PREPARES   => false,
                       );
   // Create a PDO instance (connect to the database)
   $pdo     = new PDO($dsn, $un, $pwd, $opt);
   $data    = array();

   // Attempt to query database table and retrieve data
   try {
      $stmt     = $pdo->query('SELECT * FROM client');
      while($row  = $stmt->fetch(PDO::FETCH_OBJ))
      {
         // Assign each row of data to associative array
         $data[] = $row;
      }

      // Return data as JSON
      echo json_encode($data);
   }
   catch(PDOException $e)
   {
      echo $e->getMessage();
   }

?>
</code>```

My javascript :

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'page-lst-client',
  templateUrl: 'lst-client.html'
})
export class LstClientPage {
   /**
    * @name items
    * @type {Array}
    * @public
    * @description     Used to store returned PHP data
    */
   public items : Array<any> = [];

   constructor(public navCtrl: NavController,
               public http   : HttpClient)
   {

   }

   /*
    * Triggered when template view is about to be entered
    * Returns and parses the PHP data through the load() method
    *
    * @public
    * @method ionViewWillEnter
    * @return {None}
    */
   ionViewWillEnter() : void
   {
      this.load();
   }

   /*
    * Retrieve the JSON encoded data from the remote server
    * Using Angular's Http class and an Observable - then
    * assign this to the items array for rendering to the HTML template
    *
    * @public
    * @method load
    * @return {None}
    */
   load() : void
   {
      this.http
      .get('wequida/retrieve-client.php')
      .subscribe((data : any) =>
      {
         console.dir(data);
         this.items = data;
      },
      (error : any) =>
      {
         console.dir(error);
      });
   }

   /*
    * Allow navigation to the AddTechnologyPage for creating a new entry
    *
    * @public
    * @method addEntry
    * @return {None}
    */
   addEntry() : void
   {
      this.navCtrl.push('AddClientPage');
   }

   /*
    * Allow navigation to the AddTechnologyPage for amending an existing entry
    * (We supply the actual record to be amended, as this method's parameter,
    * to the AddTechnologyPage
    *
    * @public
    * @method viewEntry
    * @param param      {any}           Navigation data to send to the next page
    * @return {None}
    */
   viewEntry(param : any) : void
   {
      this.navCtrl.push('AddClientPage', param);
   }
}
</code>```

答:
Your getting an HTML response from your PHP script.

You should include a json header in your PHP script.

```<code>header('Content-type: application/json');
</code>```

The line

```<code>echo $e->getMessage();
</code>```

will not output JSON.  Your javascript does not accommodate sending errors.
In your PHP script you can use use:

```<code>echo json_encode(array('error' => false, 'data' => $data));
...
echo json_encode(array('error' => $e->getMessage(), 'data' => []));
</code>```

Then in your javascript:

```<code>.subscribe((result: any) =>
{
    if (result.error)
    {
        // error handling code
    }
    else
    {
        console.dir(result.data);
        this.items = result.data;
    }
},
</code>```

If there is an error connecting to the database your script will output an HTML message with an 'Uncaught PDOException'.  You can wrap that in try/catch as well.

To know what the problem is you should look at what your PHP script is outputting.

To do that

open the developers console [Option + ⌘ + J (on macOS), or Shift +
CTRL + J (on Windows/Linux)],

go to the 'Network' tab,

reload the page,

look for your php script and click on it,

open the 'Response' tab.

You will see the raw HTML or JSON response from the PHP script.

Edit - after reading comments:

If in the Response tab you see the full unparsed content of the PHP file then the web server you are using is not parsing PHP.  You might be trying to do this without a sever by opening an HTML file with the javascript above through the file system using file:///C:/something/whatever.html

This will not work for obvious reasons.

Body:
I created an application with ionic with the help of this tutorial: http://masteringionic.com/blog/2016-12-15-using-php-and-mysql-with-ionic/ a school programm

But when i want to select all my client, i get this error :

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttp…, text

My PHP script :

    <?php

   // Define database connection parameters
   $hn      = 'localhost';
   $un      = 'root';
   $pwd     = '';
   $db      = 'equida';
   $cs      = 'utf8';

   // Set up the PDO parameters
   $dsn     = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
   $opt     = array(
                        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                        PDO::ATTR_EMULATE_PREPARES   => false,
                       );
   // Create a PDO instance (connect to the database)
   $pdo     = new PDO($dsn, $un, $pwd, $opt);
   $data    = array();

   // Attempt to query database table and retrieve data
   try {
      $stmt     = $pdo->query('SELECT * FROM client');
      while($row  = $stmt->fetch(PDO::FETCH_OBJ))
      {
         // Assign each row of data to associative array
         $data[] = $row;
      }

      // Return data as JSON
      echo json_encode($data);
   }
   catch(PDOException $e)
   {
      echo $e->getMessage();
   }

?>

My javascript :

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'page-lst-client',
  templateUrl: 'lst-client.html'
})
export class LstClientPage {
   /**
    * @name items
    * @type {Array}
    * @public
    * @description     Used to store returned PHP data
    */
   public items : Array<any> = [];

   constructor(public navCtrl: NavController,
               public http   : HttpClient)
   {

   }

   /*
    * Triggered when template view is about to be entered
    * Returns and parses the PHP data through the load() method
    *
    * @public
    * @method ionViewWillEnter
    * @return {None}
    */
   ionViewWillEnter() : void
   {
      this.load();
   }

   /*
    * Retrieve the JSON encoded data from the remote server
    * Using Angular's Http class and an Observable - then
    * assign this to the items array for rendering to the HTML template
    *
    * @public
    * @method load
    * @return {None}
    */
   load() : void
   {
      this.http
      .get('wequida/retrieve-client.php')
      .subscribe((data : any) =>
      {
         console.dir(data);
         this.items = data;
      },
      (error : any) =>
      {
         console.dir(error);
      });
   }

   /*
    * Allow navigation to the AddTechnologyPage for creating a new entry
    *
    * @public
    * @method addEntry
    * @return {None}
    */
   addEntry() : void
   {
      this.navCtrl.push('AddClientPage');
   }

   /*
    * Allow navigation to the AddTechnologyPage for amending an existing entry
    * (We supply the actual record to be amended, as this method's parameter,
    * to the AddTechnologyPage
    *
    * @public
    * @method viewEntry
    * @param param      {any}           Navigation data to send to the next page
    * @return {None}
    */
   viewEntry(param : any) : void
   {
      this.navCtrl.push('AddClientPage', param);
   }
}

Body:
Your getting an HTML response from your PHP script.

You should include a json header in your PHP script.

header('Content-type: application/json');

The line

echo $e->getMessage();

will not output JSON.  Your javascript does not accommodate sending errors.
In your PHP script you can use use:

echo json_encode(array('error' => false, 'data' => $data));
...
echo json_encode(array('error' => $e->getMessage(), 'data' => []));

Then in your javascript:

.subscribe((result: any) =>
{
    if (result.error)
    {
        // error handling code
    }
    else
    {
        console.dir(result.data);
        this.items = result.data;
    }
},

If there is an error connecting to the database your script will output an HTML message with an 'Uncaught PDOException'.  You can wrap that in try/catch as well.

To know what the problem is you should look at what your PHP script is outputting.

To do that

open the developers console [Option + ⌘ + J (on macOS), or Shift +
CTRL + J (on Windows/Linux)],

go to the 'Network' tab,

reload the page,

look for your php script and click on it,

open the 'Response' tab.

You will see the raw HTML or JSON response from the PHP script.

Edit - after reading comments:

If in the Response tab you see the full unparsed content of the PHP file then the web server you are using is not parsing PHP.  You might be trying to do this without a sever by opening an HTML file with the javascript above through the file system using file:///C:/something/whatever.html

This will not work for obvious reasons.


问:
jQuery changing CSS inside of a nested function call
I'm currently trying to create a drag and drop element which allows me to move an element which it is attached to. Everything is being created dynamically. I'm having a re-occurring problem where I can't change the css from inside a nested function call.

jQuery (Not working)

```<code>//Drag begin
var dragX;
var dragY;
var mouseDown = false;
var dragIcon = $('<span>')
.css({
    'z-index' : '11',
    'position' : 'absolute',
    'width' : '300px',
    'height' : '140px',
    'left' : '0px',
    'top' : '20px'
})

.addClass('unselectable')

.mousedown(function(){
    mouseDown = true;
    $(this).mousemove(function(){
        if(mouseDown == true){
            var dragX = getCurrentMouseX();
            var dragY = getCurrentMouseY();

            //Don't allow ideas to be created too close to the border of the page
            if(dragX < 260){
                dragX = 260;
            }else if(dragX > window.innerWidth - 260){
                dragX = window.innerWidth - 260;
            }

            if(dragY < 160){
                dragY = 160;
            } else if(dragY > window.innerHeight - 450){
                dragY = window.innerHeight - 450;
            }

            $(this).css({
                'left' : dragX - 150,
                'top' : dragY - 81
            });
        }
    })
})

.mouseout(function(){
    mouseDown = false;
})
.mouseup(function(){
     mouseDown = false;
});
</code>```

I've written the function in JavaScript which works correctly, however i'm trying to convert it to jQuery. The following is the working JavaScript function:

JavaScript (Working)

```<code>        //Drag begin
    var dragX;
    var dragY;
    var mouseDown = false;

    //TODO: An icon which can be used to drag the cloud around
    var dragIcon = document.createElement('span');
    dragIcon.style.zIndex = "11";
    dragIcon.style.position = "absolute";
    dragIcon.style.width = "300px";
    dragIcon.style.height = "140px";
    dragIcon.setAttribute('class', 'unselectable');
    dragIcon.style.left = "0px";
    dragIcon.style.top = "20px";
    dragIcon.unselectable = "on";
    dragIcon.style.MozUserSelect = "none";

    dragIcon.onselectstart = function() {return false;}
    dragIcon.onmousedown = function(){
        mouseDown = true;
        dragIcon.onmousemove = function(){
            if(mouseDown == true){
                var dragX = getCurrentMouseX();
                var dragY = getCurrentMouseY();

                if(dragX < 260){
                    dragX = 260;
                }else if(dragX > window.innerWidth - 260){
                    dragX = window.innerWidth - 260;
                }

                if(dragY < 160){
                    dragY = 160;
                } else if(dragY > window.innerHeight - 450){
                    dragY = window.innerHeight - 450;
                }
                cloudStyle.left = dragX  - 150 + "px"; //-150 to make up for the position of the drag icon
                sunRay.style.left = dragX - 220 + "px";
                cloudStyle.top = dragY - 81 + "px"; //-85 to make up for the positioning
                sunRay.style.top = dragY - 250 + "px";
            }
        }
    }

    dragIcon.onmouseout = function(){
        mouseDown = false;
    }
    dragIcon.onmouseup = function(){
        mouseDown = false;
    }
</code>```

Can you please point out where i'm going wrong, and whether i'm taking the wrong approach. Thanks.

答:
Ok i've found that to replace the existing style I need to do the following...

```<code>        item.removeAttr("style");
        item.attr("style", "style goes here!");
</code>```

Removing the style attribute and re-applying seems to work well.

Body:
I'm currently trying to create a drag and drop element which allows me to move an element which it is attached to. Everything is being created dynamically. I'm having a re-occurring problem where I can't change the css from inside a nested function call.

jQuery (Not working)

//Drag begin
var dragX;
var dragY;
var mouseDown = false;
var dragIcon = $('')
.css({
    'z-index' : '11',
    'position' : 'absolute',
    'width' : '300px',
    'height' : '140px',
    'left' : '0px',
    'top' : '20px'
})

.addClass('unselectable')

.mousedown(function(){
    mouseDown = true;
    $(this).mousemove(function(){
        if(mouseDown == true){
            var dragX = getCurrentMouseX();
            var dragY = getCurrentMouseY();

            //Don't allow ideas to be created too close to the border of the page
            if(dragX < 260){
                dragX = 260;
            }else if(dragX > window.innerWidth - 260){
                dragX = window.innerWidth - 260;
            }

            if(dragY < 160){
                dragY = 160;
            } else if(dragY > window.innerHeight - 450){
                dragY = window.innerHeight - 450;
            }

            $(this).css({
                'left' : dragX - 150,
                'top' : dragY - 81
            });
        }
    })
})

.mouseout(function(){
    mouseDown = false;
})
.mouseup(function(){
     mouseDown = false;
});

I've written the function in JavaScript which works correctly, however i'm trying to convert it to jQuery. The following is the working JavaScript function:

JavaScript (Working)

        //Drag begin
    var dragX;
    var dragY;
    var mouseDown = false;

    //TODO: An icon which can be used to drag the cloud around
    var dragIcon = document.createElement('span');
    dragIcon.style.zIndex = "11";
    dragIcon.style.position = "absolute";
    dragIcon.style.width = "300px";
    dragIcon.style.height = "140px";
    dragIcon.setAttribute('class', 'unselectable');
    dragIcon.style.left = "0px";
    dragIcon.style.top = "20px";
    dragIcon.unselectable = "on";
    dragIcon.style.MozUserSelect = "none";

    dragIcon.onselectstart = function() {return false;}
    dragIcon.onmousedown = function(){
        mouseDown = true;
        dragIcon.onmousemove = function(){
            if(mouseDown == true){
                var dragX = getCurrentMouseX();
                var dragY = getCurrentMouseY();

                if(dragX < 260){
                    dragX = 260;
                }else if(dragX > window.innerWidth - 260){
                    dragX = window.innerWidth - 260;
                }

                if(dragY < 160){
                    dragY = 160;
                } else if(dragY > window.innerHeight - 450){
                    dragY = window.innerHeight - 450;
                }
                cloudStyle.left = dragX  - 150 + "px"; //-150 to make up for the position of the drag icon
                sunRay.style.left = dragX - 220 + "px";
                cloudStyle.top = dragY - 81 + "px"; //-85 to make up for the positioning
                sunRay.style.top = dragY - 250 + "px";
            }
        }
    }

    dragIcon.onmouseout = function(){
        mouseDown = false;
    }
    dragIcon.onmouseup = function(){
        mouseDown = false;
    }

Can you please point out where i'm going wrong, and whether i'm taking the wrong approach. Thanks.

Body:
Ok i've found that to replace the existing style I need to do the following...

        item.removeAttr("style");
        item.attr("style", "style goes here!");

Removing the style attribute and re-applying seems to work well.


问:
JSON: How to grab value that has key value in an array?
I have a JSON response in python like this:

```<code>{
   "response" : [
      {
         "section1" : [
            {
               "test1" : "324d",
               "test2" : "433",
            },
            {
               "item" : "trousers",
               "color" : "red",
               "apply" : [ "never", "exclude" ]
            },
            {
               "price" : "277",
               "tax" : "29",
               "apply" : [ "all", "single" ]
            }
         ],
         "site_id" : "38477d",
      }
   ]
}
</code>```

How can I get the price from the part that has apply value of all?

I have been able to manually grab it like this..

```<code>result['response']['section1'][2]['price']
</code>```

But it changes position in the section each time, how can I search for it instead so that the position does not matter?

UPDATE
To clarify, the all will only ever appear once and it will always be in section1

答:
sec = result["response"][0]["section1"]
print([x for x in sec if "apply" in x and "all" in x["apply"]][0]["price"])
```

Body:
I have a JSON response in python like this:

{
   "response" : [
      {
         "section1" : [
            {
               "test1" : "324d",
               "test2" : "433",
            },
            {
               "item" : "trousers",
               "color" : "red",
               "apply" : [ "never", "exclude" ]
            },
            {
               "price" : "277",
               "tax" : "29",
               "apply" : [ "all", "single" ]
            }
         ],
         "site_id" : "38477d",
      }
   ]
}

How can I get the price from the part that has apply value of all?

I have been able to manually grab it like this..

result['response']['section1'][2]['price']

But it changes position in the section each time, how can I search for it instead so that the position does not matter?

UPDATE
To clarify, the all will only ever appear once and it will always be in section1