问:
allauth unverified email remains unverified once email expires
I have a custom user model. and I use Django rest auth to handle authentication of users. the problem is that after sign up when the email is sent. if the user doesn't verify the email before it expires, it seems that it remains stuck like that indefinitely. I was expecting the verification email to be sent again since ACCOUNT_EMAIL_VERIFICATION = "mandatory" in my settings, from the documentation, it is supposed to resend the verification message by default, but this isnt happening. I am lost as to what else to do and I can't seem to find any resource that helps.

below is my model

models.py

```<code>class User(AbstractBaseUser, PermissionsMixin):
    username = None
    email = models.EmailField(max_length=254, unique=True)
    name = models.CharField(max_length=250)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(max_length=255, unique=True, blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

</code>```

in my settings.py the user has an expiry date of 2 days

```<code>ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None #or "api/authenticated/"
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1
ACCOUNT_EMAIL_CONFIRMATION_HMAC = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
EMAIL_VERIFICATION = "mandatory"
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 3600
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 180
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
ACCOUNT_LOGIN_ON_PASSWORD_RESET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "api/login/"
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = False
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"
</code>```

答:
Eventually, I was able to solve this differently, I created a view and URL that requests the user email and then send a link to them if they are unverified.

views.py

```<code>from allauth.account.utils import send_email_confirmation
from allauth.account.admin import EmailAddress
from rest_framework.exceptions import APIException

class EmailConfirmation(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        user = get_object_or_404(User, email=request.data['email'])
        emailAddress = EmailAddress.objects.filter(user=user, verified=True).exists()

        if emailAddress:
            return Response({'message': 'This email is already verified'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            try:
                send_email_confirmation(request, user=user)
                return Response({'message': 'Email confirmation sent'}, status=status.HTTP_201_CREATED)
            except APIException:
                return Response({'message': 'This email does not exist, please create a new account'}, status=status.HTTP_403_FORBIDDEN)
</code>```

urls.py

```<code>path('verify-email/again/', qv.EmailConfirmation.as_view(), name='resend-email-confirmation'),
</code>```

Body:
I have a custom user model. and I use Django rest auth to handle authentication of users. the problem is that after sign up when the email is sent. if the user doesn't verify the email before it expires, it seems that it remains stuck like that indefinitely. I was expecting the verification email to be sent again since ACCOUNT_EMAIL_VERIFICATION = "mandatory" in my settings, from the documentation, it is supposed to resend the verification message by default, but this isnt happening. I am lost as to what else to do and I can't seem to find any resource that helps.

below is my model

models.py

class User(AbstractBaseUser, PermissionsMixin):
    username = None
    email = models.EmailField(max_length=254, unique=True)
    name = models.CharField(max_length=250)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(max_length=255, unique=True, blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

in my settings.py the user has an expiry date of 2 days

ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None #or "api/authenticated/"
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1
ACCOUNT_EMAIL_CONFIRMATION_HMAC = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
EMAIL_VERIFICATION = "mandatory"
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 3600
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 180
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
ACCOUNT_LOGIN_ON_PASSWORD_RESET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "api/login/"
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = False
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"

Body:
Eventually, I was able to solve this differently, I created a view and URL that requests the user email and then send a link to them if they are unverified.

views.py

from allauth.account.utils import send_email_confirmation
from allauth.account.admin import EmailAddress
from rest_framework.exceptions import APIException

class EmailConfirmation(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        user = get_object_or_404(User, email=request.data['email'])
        emailAddress = EmailAddress.objects.filter(user=user, verified=True).exists()

        if emailAddress:
            return Response({'message': 'This email is already verified'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            try:
                send_email_confirmation(request, user=user)
                return Response({'message': 'Email confirmation sent'}, status=status.HTTP_201_CREATED)
            except APIException:
                return Response({'message': 'This email does not exist, please create a new account'}, status=status.HTTP_403_FORBIDDEN)

urls.py

path('verify-email/again/', qv.EmailConfirmation.as_view(), name='resend-email-confirmation'),


来源: stackexchange

问:
Sort doubly linked list by next id Ramda.js
I want to sort doubly linked list by next_id value.

My DLL:

```<code>const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]
</code>```

As a result:

```<code>const dll_result = [
  {id: '14', prev_id: null, next_id: '41'}, // next item - 41
  {id: '41', prev_id: '14', next_id: '22'}, // next item - 22
  {id: '22', prev_id: '41', next_id: '45'}, // next item - 45
  {id: '45', prev_id: '22', next_id: null},
]
</code>```

I understand that it may not make sense to sort the DLL, but in my case I need to sequentially visualize the data from the array using next_id.

P.S. It would be nice to know even a native solution, and then I could try to convert to Ramda.js myself

答:
Native approach

You can sort by id and pick the lowest id as the first element of the desired output, then you can push the next elements by finding the next node using the attribute next_id.

const dll = [{id: '22', prev_id: '41', next_id: '45'},{id: '45', prev_id: '22', next_id: null},{id: '41', prev_id: '14', next_id: '22'},{id: '14', prev_id: null, next_id: '41'}],
      result = [[...dll].sort((a, b) => a.id - b.id).shift()];

dll.forEach(() => result.push(dll.find(({id}) => id === result[result.length - 1].next_id)));
console.log(result);```

ContentLicense: CC BY-SA 4.0

Body:
I want to sort doubly linked list by next_id value.

My DLL:

const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]

As a result:

const dll_result = [
  {id: '14', prev_id: null, next_id: '41'}, // next item - 41
  {id: '41', prev_id: '14', next_id: '22'}, // next item - 22
  {id: '22', prev_id: '41', next_id: '45'}, // next item - 45
  {id: '45', prev_id: '22', next_id: null},
]

I understand that it may not make sense to sort the DLL, but in my case I need to sequentially visualize the data from the array using next_id.

P.S. It would be nice to know even a native solution, and then I could try to convert to Ramda.js myself


问:
Strapi custom routes to redirect to public directory
I deployed my react app to /public directory in strapi, everything work's correctly but, when I refreshed page, strapi override my react-router routs.

So... how can I redirect strapi to open public directory when i use specific routs?

e.g redirect /posts to public directory?

答:
I build my Strapi and CRA (create-react-app) at the build time, and says I want to mount my react app under /dashboard path.

and the file structure is:

```<code>yourapp/
└── apps/
    ├── frontend (react app)
    └── backend (strapi)
</code>```

add a homepage property in frontend's package.json if you are using CRA, this will tell Webpack to add a prefix to your static assets, e.g

```<code>// in frontend's package.json
{
  ...
  "homepage": "/dashboard"
}
</code>```

move your built react app to a subfolder /dashboard of backend project, by modifying the yarn build script, I'm doing like this, be careful before copy/paste my code, there is a rm -rf cmd.

```<code>// package.json in root path
{
  ...
  "scripts": {
    "build": "yarn build:front && yarn build:back && rm -rf apps/backend/dashboard && mv apps/frontend/build apps/backend/dashboard",
    ...
  }
}
</code>```

add a custom middleware in Strapi to be your "view router", that will handle all requests to /dashboard/* to serve the react app assets under apps/backend/dashboard

create a file under <strapiapp>/middlewares/viewRouter/index.js

const path = require("path");
const koaStatic = require("koa-static");
const fs = require("fs");

module.exports = strapi => {
  return {
    async initialize() {
      const { maxAge } = strapi.config.middleware.settings.public;

      const basename = "/dashboard";

      const dashboardDir = path.resolve(strapi.dir, "dashboard");

      // Serve dashboard assets.
      strapi.router.get(
        `${basename}/*`,
        async (ctx, next) => {
          ctx.url = ctx.url.replace(/^\/dashboard/, "");
          if (!ctx.url) ctx.url = basename;
          await next();
        },
        koaStatic(dashboardDir, {
          index: "index.html",
          maxage: maxAge,
          defer: false
        })
      );

      const validRoutes = [
        "/dashboard",
        "/subpath1",
        "/subpath2"
      ];

      // server dashboard assets and all routers
      strapi.router.get(`${basename}*`, ctx => {
        const routePath = ctx.url.split("?")[0];
        let fileName = ctx.url;
        if (validRoutes.includes(routePath)) fileName = "index.html";

        ctx.type = "html";
        ctx.body = fs.createReadStream(
          path.join(dashboardDir + `/${fileName}`)
        );
      });
    }
  };
};

```

<ol start="4">
<li>enable the custom middleware in <code><strapiapp>/config/custom.json</code></li>
</ol>

```{
  "myCustomConfiguration": "This configuration is accessible through strapi.config.myCustomConfiguration",
  "viewRouter": { // use the middleware name
    "enabled": true
  }
}
```

and visit http://localhost:1337/dashboard you'll see the react page.

Body:
I build my Strapi and CRA (create-react-app) at the build time, and says I want to mount my react app under /dashboard path.

and the file structure is:

yourapp/
└── apps/
    ├── frontend (react app)
    └── backend (strapi)

add a homepage property in frontend's package.json if you are using CRA, this will tell Webpack to add a prefix to your static assets, e.g

// in frontend's package.json
{
  ...
  "homepage": "/dashboard"
}

move your built react app to a subfolder /dashboard of backend project, by modifying the yarn build script, I'm doing like this, be careful before copy/paste my code, there is a rm -rf cmd.

// package.json in root path
{
  ...
  "scripts": {
    "build": "yarn build:front && yarn build:back && rm -rf apps/backend/dashboard && mv apps/frontend/build apps/backend/dashboard",
    ...
  }
}

add a custom middleware in Strapi to be your "view router", that will handle all requests to /dashboard/* to serve the react app assets under apps/backend/dashboard

create a file under <strapiapp>/middlewares/viewRouter/index.js

const path = require("path");
const koaStatic = require("koa-static");
const fs = require("fs");

module.exports = strapi => {
  return {
    async initialize() {
      const { maxAge } = strapi.config.middleware.settings.public;

      const basename = "/dashboard";

      const dashboardDir = path.resolve(strapi.dir, "dashboard");

      // Serve dashboard assets.
      strapi.router.get(
        `${basename}/*`,
        async (ctx, next) => {
          ctx.url = ctx.url.replace(/^\/dashboard/, "");
          if (!ctx.url) ctx.url = basename;
          await next();
        },
        koaStatic(dashboardDir, {
          index: "index.html",
          maxage: maxAge,
          defer: false
        })
      );

      const validRoutes = [
        "/dashboard",
        "/subpath1",
        "/subpath2"
      ];

      // server dashboard assets and all routers
      strapi.router.get(`${basename}*`, ctx => {
        const routePath = ctx.url.split("?")[0];
        let fileName = ctx.url;
        if (validRoutes.includes(routePath)) fileName = "index.html";

        ctx.type = "html";
        ctx.body = fs.createReadStream(
          path.join(dashboardDir + `/${fileName}`)
        );
      });
    }
  };
};

enable the custom middleware in <strapiapp>/config/custom.json

{
  "myCustomConfiguration": "This configuration is accessible through strapi.config.myCustomConfiguration",
  "viewRouter": { // use the middleware name
    "enabled": true
  }
}

and visit http://localhost:1337/dashboard you'll see the react page.


问:
How to determine unique years within date range?
I'm trying to determine in what years clients make use of healthcare. The data:

```<code>Clientnumber   Date start  Date end
1              01-03-2017  31-10-2017
1              01-02-2018  07-08-2018
1              01-11-2018  01-03-2019
1              25-03-2019  01-07-2020
</code>```

For this one client I want to know in what unique years he/she is registered. Thus, the result should be:
2017, 2018, 2019, 2020 and additonally a count of unique years: 4.

Is there a way to do this in either Excel or R?

Thanks in advance.

答:
In R, we can get the data in long format, convert to Date and extract year. For each client we can create a comma-separated value of unique Year and count number of distinct Year.

```<code>library(dplyr)

df %>%
  tidyr::pivot_longer(cols = -Clientnumber) %>%
  mutate(value = as.Date(value, "%d-%m-%Y"),
         Year = format(value, "%Y")) %>%
  group_by(Clientnumber) %>%
  summarise(Un_year = toString(unique(Year)),
            count = n_distinct(Year))

# Clientnumber  Un_year                count
#         <int> <chr>                  <int>
#1            1 2017, 2018, 2019, 2020     4
</code>```

Body:
I'm trying to determine in what years clients make use of healthcare. The data:

Clientnumber   Date start  Date end
1              01-03-2017  31-10-2017
1              01-02-2018  07-08-2018
1              01-11-2018  01-03-2019
1              25-03-2019  01-07-2020

For this one client I want to know in what unique years he/she is registered. Thus, the result should be:
2017, 2018, 2019, 2020 and additonally a count of unique years: 4.

Is there a way to do this in either Excel or R?

Thanks in advance.

Body:
In R, we can get the data in long format, convert to Date and extract year. For each client we can create a comma-separated value of unique Year and count number of distinct Year.

library(dplyr)

df %>%
  tidyr::pivot_longer(cols = -Clientnumber) %>%
  mutate(value = as.Date(value, "%d-%m-%Y"),
         Year = format(value, "%Y")) %>%
  group_by(Clientnumber) %>%
  summarise(Un_year = toString(unique(Year)),
            count = n_distinct(Year))

# Clientnumber  Un_year                count
#         <int> <chr>                  <int>
#1            1 2017, 2018, 2019, 2020     4


问:
Colored text in command prompt after "cls" but not before "cls"
I have a python program where I am trying to print "Hello" in colored text using ANSI codes in command prompt. When I print in normally, it is not working, it just prints ? and text, but when I print it after clearing the command prompt it works fine. Can some one explain this weird nature.

I searched for this but couldn't find anything about this nature. I am using Windows 10

The below code outputs [0;32mHello[0m

print('\x1b[0;32m' + "Hello" + '\033[0m')
```

<p><img src="https://i.stack.imgur.com/V85M0.png" alt="no color"></p>

<p>whereas the below code outputs Hello in green color.</p>

<pre class="lang-py prettyprint-override"><code>os.system("cls")
print('\x1b[0;32m' + "Hello" + '\033[0m')
</code>```

Right image is the output of the code shown above or in the left image

My expectation was that is gives either ansii or colored text in both the above codes, but actual output is different in both the cases

Body:
I have a python program where I am trying to print "Hello" in colored text using ANSI codes in command prompt. When I print in normally, it is not working, it just prints ? and text, but when I print it after clearing the command prompt it works fine. Can some one explain this weird nature.

I searched for this but couldn't find anything about this nature. I am using Windows 10

The below code outputs [0;32mHello[0m

print('\x1b[0;32m' + "Hello" + '\033[0m')

whereas the below code outputs Hello in green color.

os.system("cls")
print('\x1b[0;32m' + "Hello" + '\033[0m')

Right image is the output of the code shown above or in the left image

My expectation was that is gives either ansii or colored text in both the above codes, but actual output is different in both the cases

Body:
try this:

os.system("")
print('\x1b[0;32m' + "Hello" + '\033[0m')


问:
React, unable to display the data received by an api, after doing a GET in componentDidMount()
I have done a function in my react call which calls an api, and sets a state based on the data received by that api

```<code>getUserList() {
    API.get('/userlist')
        .then(response => {
            this.setState({
                userList: response.data
            }, () => {
                console.log(this.state.userList) //I can see this
            });
        })
}
</code>```

This is how my constructor looks

```<code>constructor(props) {
    super(props)
    this.state = {
        retracted: false,
        userList: []

    }
    this.getUserList = this.getUserList.bind(this);
}
</code>```

I call it in componentDidMount()

```<code>componentDidMount() {
    this.getUserList();
}
</code>```

But then my render crashes, because both console.log return undefined

```<code>render() {
    var users = this.state.userList;
    var user = users[0].email //cannot read email of undefined

    console.log(this.state.userList)
    console.log(users)
    return (
        <div class="maincontainer">
            <div className="content-landing">
                 <p>{user}</p>
            </div>

        </div>
    )
}
</code>```

答:
this is a case of initially undefined data, until there is data in users this line var user = users[0].email will crash because its trying to access non existing data so rewrite that part into:

var user = users && users[0] ? users[0].email : null
```

Body:
I have done a function in my react call which calls an api, and sets a state based on the data received by that api

getUserList() {
    API.get('/userlist')
        .then(response => {
            this.setState({
                userList: response.data
            }, () => {
                console.log(this.state.userList) //I can see this
            });
        })
}

This is how my constructor looks

constructor(props) {
    super(props)
    this.state = {
        retracted: false,
        userList: []

    }
    this.getUserList = this.getUserList.bind(this);
}

I call it in componentDidMount()

componentDidMount() {
    this.getUserList();
}

But then my render crashes, because both console.log return undefined

render() {
    var users = this.state.userList;
    var user = users[0].email //cannot read email of undefined

    console.log(this.state.userList)
    console.log(users)
    return (

{user}

    )
}


问:
ORACLE BIPUBLISHER SQL Query taking too long to execute
Following is the query

```<code>Select
pu.username,
ROLE.ROLE_NAME,
(
CASE
WHEN ((ROLE.ORG_ID IS NOT NULL) AND ROLE.ORG_ID=fabuv.BU_ID) THEN FABUV.BU_NAME
WHEN ((ROLE.LEDGER_ID IS NOT NULL) AND ROLE.LEDGER_ID=gl.LEDGER_ID) THEN GL.NAME
WHEN ((ROLE.BOOK_ID IS NOT NULL) AND ROLE.BOOK_ID=fbc.BOOK_CONTROL_ID) THEN FBC.BOOK_TYPE_NAME
WHEN ((ROLE.SET_ID IS NOT NULL) AND ROLE.SET_ID=fssv.SET_ID) THEN FSSV.SET_NAME
WHEN ((ROLE.INV_ORGANIZATION_ID IS NOT NULL) AND ROLE.INV_ORGANIZATION_ID=iop.ORGANIZATION_ID) THEN IOP.ORGANIZATION_CODE
WHEN ((ROLE.CST_ORGANIZATION_ID IS NOT NULL) AND ROLE.CST_ORGANIZATION_ID=ccov.COST_ORG_ID) THEN CCOV.COST_ORG_CODE
WHEN ((ROLE.ACCESS_SET_ID IS NOT NULL) AND ROLE.ACCESS_SET_ID=gas.ACCESS_SET_ID) THEN GAS.NAME
WHEN ((ROLE.CONTROL_BUDGET_ID IS NOT NULL) AND ROLE.CONTROL_BUDGET_ID=xcb.CONTROL_BUDGET_ID) THEN XCB.NAME
WHEN ((ROLE.INTERCO_ORG_ID IS NOT NULL) AND ROLE.INTERCO_ORG_ID=fio.INTERCO_ORG_ID) THEN FIO.INTERCO_ORG_NAME
ELSE 'NOT_APPLICABLE'
END
) "Security_Context_Value"
from
fusion.per_users pu,
fusion.FA_BOOK_CONTROLS FBC,
fusion.FUN_ALL_BUSINESS_UNITS_V FABUV,
fusion.XCC_CONTROL_BUDGETS XCB,
fusion.CST_COST_ORGS_V CCOV,
fusion.gl_access_sets GAS,
fusion.FUN_INTERCO_ORGANIZATIONS FIO,
fusion.INV_ORG_PARAMETERS iOP,
fusion.GL_LEDGERS GL,
fusion.RCS_MFG_PARAMETERS RMP,
fusion.FUN_USER_ROLE_DATA_ASGNMNTS ROLE,
fusion.FND_SETID_SETS_VL FSSV
where
1=1
and pu.USERNAME=:Username
AND ROLE.ORG_ID != NULL
OR ROLE.LEDGER_ID != NULL
OR ROLE.BOOK_ID != NULL
OR ROLE.SET_ID != NULL
OR ROLE.INV_ORGANIZATION_ID != NULL
OR ROLE.CST_ORGANIZATION_ID != NULL
OR ROLE.ACCESS_SET_ID != NULL
OR ROLE.CONTROL_BUDGET_ID != NULL
OR ROLE.INTERCO_ORG_ID != NULL
And pu.USER_GUID=role.USER_GUID
</code>```

It is the query required to extract roles assigned to users with Security_Context and Value.
I have tried different combinations of using IS NOT NULL in place of '!=' but it also didnt help, again Username is not taken into consideration when if it run.

答:
I think what you're after is something like:

```<code>SELECT pu.username,
     role.role_name,
     CASE WHEN ROLE.ORG_ID IS NOT NULL THEN FABUV.BU_NAME
            WHEN ROLE.LEDGER_ID IS NOT NULL THEN GL.NAME
            WHEN ROLE.BOOK_ID IS NOT NULL THEN FBC.BOOK_TYPE_NAME
            WHEN ROLE.SET_ID IS NOT NULL THEN FSSV.SET_NAME
            WHEN ROLE.INV_ORGANIZATION_ID IS NOT NULL THEN IOP.ORGANIZATION_CODE
            WHEN ROLE.CST_ORGANIZATION_ID IS NOT NULL THEN CCOV.COST_ORG_CODE
            WHEN ROLE.ACCESS_SET_ID IS NOT NULL THEN GAS.NAME
            WHEN ROLE.CONTROL_BUDGET_ID IS NOT NULL THEN XCB.NAME
            WHEN ROLE.INTERCO_ORG_ID IS NOT NULL THEN FIO.INTERCO_ORG_NAME
            ELSE 'NOT_APPLICABLE'
       END "Security_Context_Value"
FROM   fusion.per_users pu
       INNER JOIN fusion.fun_user_role_data_asgnmnts role ON pu.user_guid = role.user_guid
       LEFT OUTER JOIN fusion.fun_all_business_units_v fabuv ON role.org_id = fabuv.bu_id
       LEFT OUTER JOIN fusion.gl_ledgers gl ON role.ledger_id = gl.ledger_id
       LEFT OUTER JOIN fusion.fa_book_controls fbc ON role.book_id=fbc.book_control_id
       LEFT OUTER JOIN fusion.fnd_setid_sets_vl fssv ON role.SET_ID=fssv.SET_ID
       LEFT OUTER JOIN fusion.inv_org_parameters iop ON role.inv_organization_id=iop.organization_id
       LEFT OUTER JOIN fusion.cst_cost_orgs_v ccov ON role.cst_organization_id=ccov.cost_org_id
       LEFT OUTER JOIN fusion.gl_access_sets gas ON role.access_set_id=gas.access_set_id
       LEFT OUTER JOIN fusion.xcc_control_budgets xcb ON role.control_budget_id=xcb.control_budget_id
       LEFT OUTER JOIN fusion.fun_interco_organizations fio ON role.interco_org_id=fio.interco_org_id
WHERE  pu.username = :username
AND    COALESCE(role.org_id,
                role.ledger_id,
                role.book_id,
                role.set_id,
                role.inv_organization_id,
                role.cst_organization_id,
                role.access_set_id,
                role.control_budget_id,
                role.interco_org_id) IS NOT NULL;
</code>```

Note the use of the ANSI join syntax, which forces you to add in join conditions (unless you explicitly request a cross join).

Your original query was doing a cross join between your fabuv, gl, fbc, etc tables, meaning each row in fabuv was being joined to all rows in gl, and each of the resultant rows was being joined to every row in the fbc table and so on... that's a lot of rows - e.g. if there are 100 rows in each of the fabuv, gl, fbc, etc tables, you're going to end up with 100 x 100 x 100 x ... which ends up being way too many rows.

I've take a guess as to what the join conditions should be, based on your case statement - n.b. the rmp table wasn't being referenced at all, so I've excluded it from the from clause.

I also used the COALESCE function to simplify your where clause - this function returns the first not-null value.

Body:
Following is the query

Select
pu.username,
ROLE.ROLE_NAME,
(
CASE
WHEN ((ROLE.ORG_ID IS NOT NULL) AND ROLE.ORG_ID=fabuv.BU_ID) THEN FABUV.BU_NAME
WHEN ((ROLE.LEDGER_ID IS NOT NULL) AND ROLE.LEDGER_ID=gl.LEDGER_ID) THEN GL.NAME
WHEN ((ROLE.BOOK_ID IS NOT NULL) AND ROLE.BOOK_ID=fbc.BOOK_CONTROL_ID) THEN FBC.BOOK_TYPE_NAME
WHEN ((ROLE.SET_ID IS NOT NULL) AND ROLE.SET_ID=fssv.SET_ID) THEN FSSV.SET_NAME
WHEN ((ROLE.INV_ORGANIZATION_ID IS NOT NULL) AND ROLE.INV_ORGANIZATION_ID=iop.ORGANIZATION_ID) THEN IOP.ORGANIZATION_CODE
WHEN ((ROLE.CST_ORGANIZATION_ID IS NOT NULL) AND ROLE.CST_ORGANIZATION_ID=ccov.COST_ORG_ID) THEN CCOV.COST_ORG_CODE
WHEN ((ROLE.ACCESS_SET_ID IS NOT NULL) AND ROLE.ACCESS_SET_ID=gas.ACCESS_SET_ID) THEN GAS.NAME
WHEN ((ROLE.CONTROL_BUDGET_ID IS NOT NULL) AND ROLE.CONTROL_BUDGET_ID=xcb.CONTROL_BUDGET_ID) THEN XCB.NAME
WHEN ((ROLE.INTERCO_ORG_ID IS NOT NULL) AND ROLE.INTERCO_ORG_ID=fio.INTERCO_ORG_ID) THEN FIO.INTERCO_ORG_NAME
ELSE 'NOT_APPLICABLE'
END
) "Security_Context_Value"
from
fusion.per_users pu,
fusion.FA_BOOK_CONTROLS FBC,
fusion.FUN_ALL_BUSINESS_UNITS_V FABUV,
fusion.XCC_CONTROL_BUDGETS XCB,
fusion.CST_COST_ORGS_V CCOV,
fusion.gl_access_sets GAS,
fusion.FUN_INTERCO_ORGANIZATIONS FIO,
fusion.INV_ORG_PARAMETERS iOP,
fusion.GL_LEDGERS GL,
fusion.RCS_MFG_PARAMETERS RMP,
fusion.FUN_USER_ROLE_DATA_ASGNMNTS ROLE,
fusion.FND_SETID_SETS_VL FSSV
where
1=1
and pu.USERNAME=:Username
AND ROLE.ORG_ID != NULL
OR ROLE.LEDGER_ID != NULL
OR ROLE.BOOK_ID != NULL
OR ROLE.SET_ID != NULL
OR ROLE.INV_ORGANIZATION_ID != NULL
OR ROLE.CST_ORGANIZATION_ID != NULL
OR ROLE.ACCESS_SET_ID != NULL
OR ROLE.CONTROL_BUDGET_ID != NULL
OR ROLE.INTERCO_ORG_ID != NULL
And pu.USER_GUID=role.USER_GUID

It is the query required to extract roles assigned to users with Security_Context and Value.
I have tried different combinations of using IS NOT NULL in place of '!=' but it also didnt help, again Username is not taken into consideration when if it run.

Body:
I think what you're after is something like:

SELECT pu.username,
     role.role_name,
     CASE WHEN ROLE.ORG_ID IS NOT NULL THEN FABUV.BU_NAME
            WHEN ROLE.LEDGER_ID IS NOT NULL THEN GL.NAME
            WHEN ROLE.BOOK_ID IS NOT NULL THEN FBC.BOOK_TYPE_NAME
            WHEN ROLE.SET_ID IS NOT NULL THEN FSSV.SET_NAME
            WHEN ROLE.INV_ORGANIZATION_ID IS NOT NULL THEN IOP.ORGANIZATION_CODE
            WHEN ROLE.CST_ORGANIZATION_ID IS NOT NULL THEN CCOV.COST_ORG_CODE
            WHEN ROLE.ACCESS_SET_ID IS NOT NULL THEN GAS.NAME
            WHEN ROLE.CONTROL_BUDGET_ID IS NOT NULL THEN XCB.NAME
            WHEN ROLE.INTERCO_ORG_ID IS NOT NULL THEN FIO.INTERCO_ORG_NAME
            ELSE 'NOT_APPLICABLE'
       END "Security_Context_Value"
FROM   fusion.per_users pu
       INNER JOIN fusion.fun_user_role_data_asgnmnts role ON pu.user_guid = role.user_guid
       LEFT OUTER JOIN fusion.fun_all_business_units_v fabuv ON role.org_id = fabuv.bu_id
       LEFT OUTER JOIN fusion.gl_ledgers gl ON role.ledger_id = gl.ledger_id
       LEFT OUTER JOIN fusion.fa_book_controls fbc ON role.book_id=fbc.book_control_id
       LEFT OUTER JOIN fusion.fnd_setid_sets_vl fssv ON role.SET_ID=fssv.SET_ID
       LEFT OUTER JOIN fusion.inv_org_parameters iop ON role.inv_organization_id=iop.organization_id
       LEFT OUTER JOIN fusion.cst_cost_orgs_v ccov ON role.cst_organization_id=ccov.cost_org_id
       LEFT OUTER JOIN fusion.gl_access_sets gas ON role.access_set_id=gas.access_set_id
       LEFT OUTER JOIN fusion.xcc_control_budgets xcb ON role.control_budget_id=xcb.control_budget_id
       LEFT OUTER JOIN fusion.fun_interco_organizations fio ON role.interco_org_id=fio.interco_org_id
WHERE  pu.username = :username
AND    COALESCE(role.org_id,
                role.ledger_id,
                role.book_id,
                role.set_id,
                role.inv_organization_id,
                role.cst_organization_id,
                role.access_set_id,
                role.control_budget_id,
                role.interco_org_id) IS NOT NULL;

Note the use of the ANSI join syntax, which forces you to add in join conditions (unless you explicitly request a cross join).

Your original query was doing a cross join between your fabuv, gl, fbc, etc tables, meaning each row in fabuv was being joined to all rows in gl, and each of the resultant rows was being joined to every row in the fbc table and so on... that's a lot of rows - e.g. if there are 100 rows in each of the fabuv, gl, fbc, etc tables, you're going to end up with 100 x 100 x 100 x ... which ends up being way too many rows.

I've take a guess as to what the join conditions should be, based on your case statement - n.b. the rmp table wasn't being referenced at all, so I've excluded it from the from clause.

I also used the COALESCE function to simplify your where clause - this function returns the first not-null value.


问:
return RedirectToAction not Functioning

I already simple checking the name and pass(=true)

When return RedirectToAction("Index", "Home"); ---> not function

I don't know what wrongs! No error show

Please help.. Thx a lot.

答:
Try This Way:

LoginController.cs

```<code>
using System.Data.Odbc;
using System.Web.Configuration;

        public ActionResult LoginReadData()
        {
            string query = "Select * from login where name=@name and password=@password";

            //using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString))
                OR
            using (OdbcConnection connection = new OdbcConnection("Your Connection String")) //here you need to add connection
            {
                OdbcCommand command = new OdbcCommand(query, connection);

                connection.Open();

                OdbcDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    string name = reader[0].ToString();
                    string password = reader[1].ToString();

                    if (name != null && password != null)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        return View("Create", "Registration");
                    }
                }
                reader.Close();
            }
            return View();
        }

</code>```

Title: return RedirectToAction not Functioning

Body:
Try This Way:

LoginController.cs

using System.Data.Odbc;
using System.Web.Configuration;

        public ActionResult LoginReadData()
        {
            string query = "Select * from login where name=@name and password=@password";

            //using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString))
                OR
            using (OdbcConnection connection = new OdbcConnection("Your Connection String")) //here you need to add connection
            {
                OdbcCommand command = new OdbcCommand(query, connection);

                connection.Open();

                OdbcDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    string name = reader[0].ToString();
                    string password = reader[1].ToString();

                    if (name != null && password != null)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        return View("Create", "Registration");
                    }
                }
                reader.Close();
            }
            return View();
        }


问:
Regex for at least 8 + upper and lower+numbers or other non-alphabetic

Contains at least 8 characters.

Contains upper and lower case letters.

Contains numbers or other non-alphabetic characters.

What could be the reg ex for the above criteria?

I am creating a check for stronger password :)

c# i am using

答:
Don't try to use one regexp for all rules -- it's hard, and more importantly it will be hard to read and modify by future programmers. Instead, write one function for each rule. Use a string length function for the first rule, then use separate regular expressions (or a simple scan of the string)for uppercase letters, lowercase letters and numbers.

Your test then becomes something like:

```<code>if (len(password) >= 8 &&
    contains_lower(password) &&
    contains_upper(password) &&
    contains_number(password)) {
    ...
}
</code>```

Your code becomes absolutely clear in its intent, and if you have to change just one piece of the algorithm you don't have to reinvent a complex regular expression. Plus, you'll be able to unit test each rule independently.

Compare that to an example someone wrote in another answer to this question:

```<code>(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]).{8,}
</code>```

Which of these two answers looks easier to understand, easier to modify and easier to test? You can't even guess what the regex is doing until you spend a few (or many) moments studying it. And what if the requirement changes to ".. and has at least one underscore"? How do you change the pattern, especially when you weren't the one who came up with the pattern to begin with?

ContentLicense: CC BY-SA 3.0

Body:
Don't try to use one regexp for all rules -- it's hard, and more importantly it will be hard to read and modify by future programmers. Instead, write one function for each rule. Use a string length function for the first rule, then use separate regular expressions (or a simple scan of the string)for uppercase letters, lowercase letters and numbers.

Your test then becomes something like:

if (len(password) >= 8 &&
    contains_lower(password) &&
    contains_upper(password) &&
    contains_number(password)) {
    ...
}

Your code becomes absolutely clear in its intent, and if you have to change just one piece of the algorithm you don't have to reinvent a complex regular expression. Plus, you'll be able to unit test each rule independently.

Compare that to an example someone wrote in another answer to this question:

(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]).{8,}

Which of these two answers looks easier to understand, easier to modify and easier to test? You can't even guess what the regex is doing until you spend a few (or many) moments studying it. And what if the requirement changes to ".. and has at least one underscore"? How do you change the pattern, especially when you weren't the one who came up with the pattern to begin with?


问:
Stripe and React, react-stripe-element custom card element without zip field
I am newbie in stripe and react.

I am trying to create a stripe checkout screen which has already been designed.

Now when I add CardElement component it create a new row which looks like this

I would like it use my own custom styled elements, is there any way to pass these as props style them custom

Regards

答:
On the topic of styling Stripe Card Elements. I would recommend checking out the following parts of the Stripe.js docs:

https://stripe.com/docs/js/element/the_element_container

https://stripe.com/docs/js/appendix/style

https://stripe.com/docs/js/elements_object/create_element?type=card

Ultimately, there are both classes and style parameters that you can work with to change the style of your Card Element.

Hope this helps!


问:
Problem with animating letters in jQuery + CSS
I'm trying to animate a string if a use hovers over it.
(turning it into an array and pulling different animations on every letter)
The animations work perfectly but I have one problem.

once I hover over the element (mouseenter) for a second time the code shows the user all of the tags within the hovered upon element like so:

Code Below.
if you hover over the name twice you will see the problem.
any suggestions on how to fix this?

JSfiddle:

$(function() {

    var $win = $(window),
        w = 0,
        h = 0,
        rgb = [],
        getWidth = function() {
            w = $win.width();
            h = $win.height();
        };

    $win.resize(getWidth).mousemove(function(e) {

        rgb = [
            Math.round(e.pageX / w * 255),
            Math.round(e.pageY / h * 255),
            150
        ];

        $(document.body).css('background', 'rgb(' + rgb.join(',') + ')');

    }).resize();

    $('.firstName').on('mouseenter', function () {
        let firstNameArray = $('.firstName').html().split(' ')[0].split('');
        let lastNameArray = $('.firstName').html().split(' ')[1].split('');
        $('.firstName').html('');
        for (letter of firstNameArray) {
            let radomizer = Math.floor(Math.random() * 3);
            $('.firstName').append(`<span class='animation${radomizer}'>${letter}</span>`);
        }
        $('.firstName').append(' ')
        for (letter of lastNameArray) {
            let radomizer = Math.floor(Math.random() * 3);
            $('.firstName').append(`<span class='animation${radomizer}'>${letter}</span>`);
        }

    });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.firstBox {
    margin-top: 10rem;
}

.firstBox>div {
    margin-top: 3rem;
}

div>h1 {
    color: white;
    font-size: 55px;
    text-shadow: 2px black solid;
}

.animation0 {
    animation: letterrotate 1.5s forwards;
    display: inline-block;
}

.animation1 {
    animation: lettermovedown 1.5s forwards;
    display: inline-block;
}

.animation2 {
    animation: lettermoveup 1.5s forwards;
    display: inline-block;
}

@keyframes letterrotate {
    0% {
        transform: rotate(100deg);
    }
    50% {
        transform: rotate(250deg);
    }
    100% {
        transform: rotate(0deg);
    }
}

@keyframes lettermovedown {
    0% {
        transform: translateY(0px);
    }
    50% {
        transform: translateY(20px);
    }
    100% {
        transform: translateY(0px);
    }
}

@keyframes lettermoveup {
    0% {
        transform: translateY(0px);
    }
    50% {
        transform: translateY(-20px);
    }
    100% {
        transform: translateY(0px);
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">

    <link rel="stylesheet" href="styles.css">
    <title>Eden Hazani</title>

Eden Hazani

Not Your Avarage

Web Developer

```

答:
This is happening because you have changed the html inside the class firstName on mouse enter. My advice is just change the html after mouseout event  i.e</p>

```<code>        $('.firstName').on('mouseout', function () {
             $(this).html('Eden Hazani');
        });
</code>```

Body:
I'm trying to animate a string if a use hovers over it.
(turning it into an array and pulling different animations on every letter)
The animations work perfectly but I have one problem.

once I hover over the element (mouseenter) for a second time the code shows the user all of the tags within the hovered upon element like so:

Code Below.
if you hover over the name twice you will see the problem.
any suggestions on how to fix this?

JSfiddle:

$(function() {

    var $win = $(window),
        w = 0,
        h = 0,
        rgb = [],
        getWidth = function() {
            w = $win.width();
            h = $win.height();
        };

    $win.resize(getWidth).mousemove(function(e) {

        rgb = [
            Math.round(e.pageX / w * 255),
            Math.round(e.pageY / h * 255),
            150
        ];

        $(document.body).css('background', 'rgb(' + rgb.join(',') + ')');

    }).resize();

    $('.firstName').on('mouseenter', function () {
        let firstNameArray = $('.firstName').html().split(' ')[0].split('');
        let lastNameArray = $('.firstName').html().split(' ')[1].split('');
        $('.firstName').html('');
        for (letter of firstNameArray) {
            let radomizer = Math.floor(Math.random() * 3);
            $('.firstName').append(`<span class='animation${radomizer}'>${letter}</span>`);
        }
        $('.firstName').append(' ')
        for (letter of lastNameArray) {
            let radomizer = Math.floor(Math.random() * 3);
            $('.firstName').append(`<span class='animation${radomizer}'>${letter}</span>`);
        }

    });

});

.firstBox {
    margin-top: 10rem;
}

.firstBox>div {
    margin-top: 3rem;
}

div>h1 {
    color: white;
    font-size: 55px;
    text-shadow: 2px black solid;
}

.animation0 {
    animation: letterrotate 1.5s forwards;
    display: inline-block;
}

.animation1 {
    animation: lettermovedown 1.5s forwards;
    display: inline-block;
}

.animation2 {
    animation: lettermoveup 1.5s forwards;
    display: inline-block;
}

@keyframes letterrotate {
    0% {
        transform: rotate(100deg);
    }
    50% {
        transform: rotate(250deg);
    }
    100% {
        transform: rotate(0deg);
    }
}

@keyframes lettermovedown {
    0% {
        transform: translateY(0px);
    }
    50% {
        transform: translateY(20px);
    }
    100% {
        transform: translateY(0px);
    }
}

@keyframes lettermoveup {
    0% {
        transform: translateY(0px);
    }
    50% {
        transform: translateY(-20px);
    }
    100% {
        transform: translateY(0px);
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">

    <link rel="stylesheet" href="styles.css">
    <title>Eden Hazani</title>

Eden Hazani

Not Your Avarage

Web Developer

Body:
This is happening because you have changed the html inside the class firstName on mouse enter. My advice is just change the html after mouseout event  i.e

        $('.firstName').on('mouseout', function () {
             $(this).html('Eden Hazani');
        });


问:
How to fetch odd columns in oracle
How to fetch odd columns in Oracle using a query when number of columns and name of columns are not known?
E.g.:
I need to get output in below format

Column1  column3  column5  column7
And so on....

答:
You need to use the dynamic queries in the procedure as follows:

```<code>SQL> CREATE OR REPLACE PROCEDURE ODD_COLUMNS (
  2      TABLE_NAME_P   IN             VARCHAR2,
  3      DATAA          OUT            SYS_REFCURSOR
  4  ) AS
  5      V_SQL   VARCHAR2(4000);
  6  BEGIN
  7      SELECT
  8          'SELECT '
  9          ||
 10              LISTAGG(COLUMN_NAME, ',') WITHIN GROUP(
 11                  ORDER BY
 12                      COLUMN_ID
 13              )
 14          || ' FROM "'
 15          || TABLE_NAME_P
 16          || '"'
 17      INTO V_SQL
 18      FROM
 19          USER_TAB_COLS
 20      WHERE
 21          TABLE_NAME = TABLE_NAME_P
 22          AND MOD(COLUMN_ID, 2) = 1;
 23
 24      OPEN DATAA FOR V_SQL;
 25
 26  END ODD_COLUMNS;
 27  /

Procedure created.

SQL>
</code>```

Now, Let's test it:

```<code>SQL> variable rc refcursor;
SQL> exec ODD_COLUMNS('EMP',:rc);

PL/SQL procedure successfully completed.

SQL> print rc;

    EMP_ID E
---------- -
        10 N
        20 Y

SQL>
SQL> exec ODD_COLUMNS('MY_TABLE1',:rc);

PL/SQL procedure successfully completed.

SQL> print rc;

        ID    REQ_QTY
---------- ----------
      1001         10
      1001         20
      1001         30
      1002         40
      1003         10
      1003         20

6 rows selected.

SQL>
</code>```

Cheers!!

Title: How to fetch odd columns in oracle

Body:
You need to use the dynamic queries in the procedure as follows:

SQL> CREATE OR REPLACE PROCEDURE ODD_COLUMNS (
  2      TABLE_NAME_P   IN             VARCHAR2,
  3      DATAA          OUT            SYS_REFCURSOR
  4  ) AS
  5      V_SQL   VARCHAR2(4000);
  6  BEGIN
  7      SELECT
  8          'SELECT '
  9          ||
 10              LISTAGG(COLUMN_NAME, ',') WITHIN GROUP(
 11                  ORDER BY
 12                      COLUMN_ID
 13              )
 14          || ' FROM "'
 15          || TABLE_NAME_P
 16          || '"'
 17      INTO V_SQL
 18      FROM
 19          USER_TAB_COLS
 20      WHERE
 21          TABLE_NAME = TABLE_NAME_P
 22          AND MOD(COLUMN_ID, 2) = 1;
 23
 24      OPEN DATAA FOR V_SQL;
 25
 26  END ODD_COLUMNS;
 27  /

Procedure created.

SQL>

Now, Let's test it:

SQL> variable rc refcursor;
SQL> exec ODD_COLUMNS('EMP',:rc);

PL/SQL procedure successfully completed.

SQL> print rc;

    EMP_ID E
---------- -
        10 N
        20 Y

SQL>
SQL> exec ODD_COLUMNS('MY_TABLE1',:rc);

PL/SQL procedure successfully completed.

SQL> print rc;

        ID    REQ_QTY
---------- ----------
      1001         10
      1001         20
      1001         30
      1002         40
      1003         10
      1003         20

6 rows selected.

SQL>

Cheers!!


问:
How can I compile bits of text into lines of code?
I want to produce a line of code that looks something like this:

```<code>search.condition1(ape).condition2(monkey).condition3(gorilla)
</code>```

This is for using it in a construction such as:

```<code>jungle(search.condition1(ape).condition2(monkey).condition3(gorilla))
</code>```

The problem is that I want only the conditions that have been set (at least one will always be set) to be included in the string. I set these through user input. So, let's say I have received:

```<code>cond1 =
cond2 = giraffe
cond3 = zebra
</code>```

In that case, the line of code should be:

```<code>search.condition2(giraffe).condition3(zebra)
</code>```

That is, excluding the condition1 altogether.

I have tried this solution:

```<code>searchstring = "search."

if len(cond1) > 1:
    searchstring += "condition1(cond1)
else: pass

if len(cond2) > 1:
    searchstring += ".condition(cond2)"
else: pass

if len(cond3) > 1:
    searchstring += ".condition(cond3)"
else:pass
</code>```

This correctly compiles, through string appending, what I want, but does so -- obviously -- as a string.

So, when I write ...

```<code>jungle(searchstring)
</code>```

... that does not achieve the same thing as if it had been raw code, so to speak. It is not executable.

Any ideas for solutions, or better practices?

答:
You do not want to construct code. You want to modify your queryset as needed.

E.g.:

```<code>conditions = ['foo', 'bar', 'baz']

query = search

for term in conditions:
    query = query.condition(term)

jungle(query)
</code>```

This is equivalent to search.condition('foo').condition('bar').... You're calling the .condition() method on the return value of the previous condition(), and are using the final result as argument to jungle().

If you somehow need to call different methods instead of always the same condition() (which isn't entirely clear from your question), you'll need to figure out what the logic is there and then simply do:

```<code>query = getattr(query, 'name_of_method_to_call')(term)
</code>```

Construct the "'name_of_method_to_call'" as needed dynamically.

Body:
I want to produce a line of code that looks something like this:

search.condition1(ape).condition2(monkey).condition3(gorilla)

This is for using it in a construction such as:

jungle(search.condition1(ape).condition2(monkey).condition3(gorilla))

The problem is that I want only the conditions that have been set (at least one will always be set) to be included in the string. I set these through user input. So, let's say I have received:

cond1 =
cond2 = giraffe
cond3 = zebra

In that case, the line of code should be:

search.condition2(giraffe).condition3(zebra)

That is, excluding the condition1 altogether.

I have tried this solution:

searchstring = "search."

if len(cond1) > 1:
    searchstring += "condition1(cond1)
else: pass

if len(cond2) > 1:
    searchstring += ".condition(cond2)"
else: pass

if len(cond3) > 1:
    searchstring += ".condition(cond3)"
else:pass

This correctly compiles, through string appending, what I want, but does so -- obviously -- as a string.

So, when I write ...

jungle(searchstring)

... that does not achieve the same thing as if it had been raw code, so to speak. It is not executable.

Any ideas for solutions, or better practices?

Body:
You do not want to construct code. You want to modify your queryset as needed.

E.g.:

conditions = ['foo', 'bar', 'baz']

query = search

for term in conditions:
    query = query.condition(term)

jungle(query)

This is equivalent to search.condition('foo').condition('bar').... You're calling the .condition() method on the return value of the previous condition(), and are using the final result as argument to jungle().

If you somehow need to call different methods instead of always the same condition() (which isn't entirely clear from your question), you'll need to figure out what the logic is there and then simply do:

query = getattr(query, 'name_of_method_to_call')(term)

Construct the "'name_of_method_to_call'" as needed dynamically.


问:
Why does one of MY WPF DataGrids give the "'EditItem' is not allowed for this view" exception?
I have read all the Q&A I could find here and on the MS forums about this exception, and tried most of the suggestions that I understood, and a few others. It seems that this exception can come up for a wide range of causes.

As with others, I have a WPF DataGrid bound to a collection, which throws this exception when one tries to edit one of the cells. They are set to be write-able, the collection is an ObservableCollection, I've implemented get and set handlers which send notification messages.

The suggestions I haven't tried are the ones involving implementing IList's non-generic interface, because I have no idea what I would do to do that. Also, I have many DataGrids bound to various lists and collections in my app which work, and this one used to work when it was bound to a LINQ collection.

Please help me figure out what I need to do here.

The Data Grid is:

```<code><DataGrid Name="dgIngredients" Margin="567,32,0,44" Width="360" ItemsSource="{Binding}" IsReadOnly="False"
           AutoGenerateColumns="False" HorizontalAlignment="Left" CanUserAddRows="False" CanUserDeleteRows="False">
    <DataGrid.Columns>
        <DataGridTextColumn Width="63" Header="Percent" Binding="{Binding Preference}" IsReadOnly="False" />
        <DataGridTextColumn SortDirection="Descending" Width="301" Header="Ingredient" Binding="{Binding Ingredient}" IsReadOnly="True" CanUserSort="True" CanUserReorder="False" />
    </DataGrid.Columns>
</DataGrid>
</code>```

The column being edited is the non-read-only one, Preference.

The collection is:

```<code>private ObservableCollection<RAM_Ingredient> MemberIngredientPrefs = new ObservableCollection<RAM_Ingredient>();
</code>```

The binding is:

```<code>dgIngredients.DataContext = MemberIngredientPrefs.OrderBy("Ingredient",true);
</code>```

RAM_Ingredient is:

```<code>public class RAM_Ingredient : INotifyPropertyChanged
</code>```

etc.

Where RAM_Ingredient.Preference is:

```<code>private int _Preference;
public int Preference
{
    get
    {
        return _Preference;
    }
    set
    {
        // This is needed to send notification of changes (and to not throw an exception on grid edit!):
        if ((_Preference != value))
        {
            SendPropertyChanging();
            _Preference = value;
            SendPropertyChanged("Preference");
        }
    }
}
</code>```

The exception is:

```<code>System.InvalidOperationException was unhandled
  Message='EditItem' is not allowed for this view.
  Source=PresentationFramework
  StackTrace:
       at System.Windows.Controls.ItemCollection.System.ComponentModel.IEditableCollectionView.EditItem(Object item)
       at System.Windows.Controls.DataGrid.EditRowItem(Object rowItem)
       at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(ExecutedRoutedEventArgs e)
</code>```

etc...

答:
even if this thread is old, it could help someone.
The issue is that LINQ returns a IEnumerable, as said VaelynPhi, but the cause is that editing a datagrid requires a source that implements IEditableCollectionView.
You can then use a list, an observableCollection or any collection implementing this interface.

I found this solution thanks to Shoe who gave an answer on this tread.

Body:
I have read all the Q&A I could find here and on the MS forums about this exception, and tried most of the suggestions that I understood, and a few others. It seems that this exception can come up for a wide range of causes.

As with others, I have a WPF DataGrid bound to a collection, which throws this exception when one tries to edit one of the cells. They are set to be write-able, the collection is an ObservableCollection, I've implemented get and set handlers which send notification messages.

The suggestions I haven't tried are the ones involving implementing IList's non-generic interface, because I have no idea what I would do to do that. Also, I have many DataGrids bound to various lists and collections in my app which work, and this one used to work when it was bound to a LINQ collection.

Please help me figure out what I need to do here.

The Data Grid is:

<DataGrid Name="dgIngredients" Margin="567,32,0,44" Width="360" ItemsSource="{Binding}" IsReadOnly="False"
           AutoGenerateColumns="False" HorizontalAlignment="Left" CanUserAddRows="False" CanUserDeleteRows="False">
    <DataGrid.Columns>
        <DataGridTextColumn Width="63" Header="Percent" Binding="{Binding Preference}" IsReadOnly="False" />
        <DataGridTextColumn SortDirection="Descending" Width="301" Header="Ingredient" Binding="{Binding Ingredient}" IsReadOnly="True" CanUserSort="True" CanUserReorder="False" />
    </DataGrid.Columns>
</DataGrid>

The column being edited is the non-read-only one, Preference.

The collection is:

private ObservableCollection<RAM_Ingredient> MemberIngredientPrefs = new ObservableCollection<RAM_Ingredient>();

The binding is:

dgIngredients.DataContext = MemberIngredientPrefs.OrderBy("Ingredient",true);

RAM_Ingredient is:

public class RAM_Ingredient : INotifyPropertyChanged

etc.

Where RAM_Ingredient.Preference is:

private int _Preference;
public int Preference
{
    get
    {
        return _Preference;
    }
    set
    {
        // This is needed to send notification of changes (and to not throw an exception on grid edit!):
        if ((_Preference != value))
        {
            SendPropertyChanging();
            _Preference = value;
            SendPropertyChanged("Preference");
        }
    }
}

The exception is:

System.InvalidOperationException was unhandled
  Message='EditItem' is not allowed for this view.
  Source=PresentationFramework
  StackTrace:
       at System.Windows.Controls.ItemCollection.System.ComponentModel.IEditableCollectionView.EditItem(Object item)
       at System.Windows.Controls.DataGrid.EditRowItem(Object rowItem)
       at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(ExecutedRoutedEventArgs e)

etc...


问:
How to display my background-image in my html/css?
I've seen another topic about my issue, but it doesn't resolve it, I try to put a background image for my portfolio but it doesn't work. I don't understand why, do you have an idea ?

my code:

html:

          Project
          Skills
          Contact

```

```css:

.main{
background-image: url(../img/dev-dots.png);
background-position: center;
background-repeat: no-repeat;
background-size: cover;

}

.navbar{
    height: 10vh;
    background-color: purple;
    position: fixed;
}
```

PS: Sorry for my english, it's not my first language.

答:
```<code>.main {
  background-image: url(../img/dev-dots.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  width: 200px;
  height: 100px;
}
</code>```

Body:
I've seen another topic about my issue, but it doesn't resolve it, I try to put a background image for my portfolio but it doesn't work. I don't understand why, do you have an idea ?

my code:

html:

          Project
          Skills
          Contact

css:

.main{
background-image: url(../img/dev-dots.png);
background-position: center;
background-repeat: no-repeat;
background-size: cover;

}

.navbar{
    height: 10vh;
    background-color: purple;
    position: fixed;
}

PS: Sorry for my english, it's not my first language.


问:
Google login token to localstorage (React)
I am still quite new to this and in need of help. I am building a log in, which includes "Log in with Google".

I have the following Google authentication I am using to log into a PrivateRoute. For the route to be accessible, the jwt token needs to be stored locally (as is the one that is not created through Google, but locally). This is my google login:

```<code>router.get('/google', passport.authenticate('google', {
    scope: ['email', 'profile']
}));

router.get('/google/redirect', passport.authenticate('google'), (req, res) => {
    let user = req.user
    console.log('user :', user);
    const payload = {
        user: {
            id: user.id
        }
    }
    jwt.sign(
        payload,
        keys.secret,
        {
            expiresIn: 2592000
        },
        (err, token) => {
            res.redirect('/?code=' + token);

        }
    );
    //redirect to front-end
    res.redirect('/?code=' + token);
    window.localStorage.setItem('bearer' + token)
});
</code>```

But I cannot seem to store it, meaning take it from the address bar and store it in the application. Thanks for any help, really appreciated.

答:
Eventually, I did in my PrivateRoute:</p>

```<code>{localStorage.setItem("token", window.location.search.split("=")[1])}
</code>```

Body:
I am still quite new to this and in need of help. I am building a log in, which includes "Log in with Google".

I have the following Google authentication I am using to log into a PrivateRoute. For the route to be accessible, the jwt token needs to be stored locally (as is the one that is not created through Google, but locally). This is my google login:

router.get('/google', passport.authenticate('google', {
    scope: ['email', 'profile']
}));

router.get('/google/redirect', passport.authenticate('google'), (req, res) => {
    let user = req.user
    console.log('user :', user);
    const payload = {
        user: {
            id: user.id
        }
    }
    jwt.sign(
        payload,
        keys.secret,
        {
            expiresIn: 2592000
        },
        (err, token) => {
            res.redirect('/?code=' + token);

        }
    );
    //redirect to front-end
    res.redirect('/?code=' + token);
    window.localStorage.setItem('bearer' + token)
});

But I cannot seem to store it, meaning take it from the address bar and store it in the application. Thanks for any help, really appreciated.

Body:
Eventually, I did in my PrivateRoute:

{localStorage.setItem("token", window.location.search.split("=")[1])}


问:
Anyone who knows how to configure the Amazon AWS platform to program skills?
I'm working with Amazon's AWS platform and I need to program Lambda functions that I will need use as Skills for Alexa. But when I have to connect my Lambda function with the Alexa Developer platform I am experiencing problems especially when it asks me to enter the data relating to the linking account.

The data I entered are these, however, once I turn on my app and go to the skill that I have programmed to activate it on my alexa, I get this error:

答: If i get your question right- you want to link Alexa Dev Console to the lambda function. First you need to go to Alexa developer console. On the "Build" category there is a topic called "Endpoint". Click on that. Copy your skill id and head over to Lambda. In there you need to enter the skill id, while creating a function. After the function is set up, head to the editor. On the upper right corner of the page you see your "ARN". Click on the copy button at the end of the line. Get back to Alexa developer console. At "Endpoint" you enter the ARN value in the "default region". After saving (at lambda and developer console), your link should be established.


问:
Send email from a react native app in background
I want to send an email through a react native app when some action happens in background.</p>

答:
In case it helps anyone.

To send email from react native app you need a service that would send the email for you. You can as well create your own service if you want.

If you wan to send email using SMTP protocol then you can use the react native smtp module. You can read about it from here.


问:
How to convert directory SASS/SCSS to CSS via command line?
I tried:

```<code>sass-convert --from scss --to css --recursive app/assets/stylesheets temp
</code>```

But this only converts css to SASS, and I want the other way around.

Then I looked at the sass command, but it doesn't look like I can pass it a directory.

答:
you can use this code

sass --watch file.sass:file.css

or

sass --watch folderSass:foldercss

if you want to create css.main you can use this code

sass --watch sass:css --style compressed

Body:
I tried:

sass-convert --from scss --to css --recursive app/assets/stylesheets temp

But this only converts css to SASS, and I want the other way around.

Then I looked at the sass command, but it doesn't look like I can pass it a directory.


Title: From two dates and frequency get daterange list

Body:
I have two dates:

'1990-01-01'

'2020-02-18'

I would want to convert them in a date range list of as maximum, 25 years:

[ ['1990-01-01', '2015-01-01'], ['2015-01-01', '2020-02-18'] ]

Or as maximun, 5 years:

[ ['1990-01-01', 1995-01-01'], [1995-01-01', '2000-01-01'], ['2000-01-01', '2005-01-01'], ['2005-01-01', '2010-01-01'], ['2010-01-01', '2015-01-01'], ['2015-01-01', '2020-01-01'], ['2020-01-01', '2020-02-18'] ]

I tried with pandas.interval_range with no success.

Body:
Looks like you need pd.date_range.

Ex:

data = pd.date_range('1990-01-01', '2020-02-18',freq="5YS")
print(data)

Output:

DatetimeIndex(['1990-01-01', '1995-01-01', '2000-01-01', '2005-01-01',
               '2010-01-01', '2015-01-01', '2020-01-01'],
              dtype='datetime64[ns]', freq='5AS-JAN')


问:
Dynamic BigQuery Schema using Auto Detection:Error Schema has no fields
I am trying to mess with the auto detection feature in Bigquery and currently I am encountering issues on updating the schema on my table.

What currently I have done.

I created manually a dataset and table name in Bigquery.

Execute my first bq load command (Works perfectly fine):

```<code>bq --location=${LOCATION} load --autodetect --source_format=${FORMAT} ${DATASET}.${TABLE} ${PATH_TO_SOURCE}.
</code>```

I try to append a new JSON object introduced with new field to update the current schema.

Execute 2nd bq load command:

```<code>bq --location=${LOCATION} load --autodetect --schema_update_option=ALLOW_FIELD_ADDITION --source_format=${FORMAT} ${DATASET}.${TABLE} ${PATH_TO_SOURCE}
</code>```

Throws an error:

Error in query string.
  Error processing job. Schema has no fields.

I thought when --autodetect flag is enabled bq load command will not request for schema on your load job. Has anyone already encountered this issue?

First object:

```<code>  {
    "chatSessionId": "123",
    "chatRequestId": "1234",
    "senderType": "CUSTOMER",
    "senderFriendlyName": "Player"
  }
</code>```

Second Object:

```<code>{
    "chatSessionId": "456",
    "chatRequestId": "5678",
    "senderType": "CUSTOMER",
    "senderFriendlyName": "Player",
    "languageCode": "EN"
  }
</code>```

答:
I reproduced your steps but I couldn't reproduce the same error as you can see in the images below:

Loading first JSON

First table's data

Loading second JSON

Second's table data

The only thing I changed in your data was the format: you provided a JSON and I turned it into a NEWLINE DELIMITED JSON (type of JSON that BigQuery expects).
You can find more information about it here.
Please let me know if it clarifies something for you.

I hope it helps.

Body:
I am trying to mess with the auto detection feature in Bigquery and currently I am encountering issues on updating the schema on my table.

What currently I have done.

I created manually a dataset and table name in Bigquery.

Execute my first bq load command (Works perfectly fine):

bq --location=${LOCATION} load --autodetect --source_format=${FORMAT} ${DATASET}.${TABLE} ${PATH_TO_SOURCE}.

I try to append a new JSON object introduced with new field to update the current schema.

Execute 2nd bq load command:

bq --location=${LOCATION} load --autodetect --schema_update_option=ALLOW_FIELD_ADDITION --source_format=${FORMAT} ${DATASET}.${TABLE} ${PATH_TO_SOURCE}

Throws an error:

Error in query string.
  Error processing job. Schema has no fields.

I thought when --autodetect flag is enabled bq load command will not request for schema on your load job. Has anyone already encountered this issue?

First object:

  {
    "chatSessionId": "123",
    "chatRequestId": "1234",
    "senderType": "CUSTOMER",
    "senderFriendlyName": "Player"
  }

Second Object:

{
    "chatSessionId": "456",
    "chatRequestId": "5678",
    "senderType": "CUSTOMER",
    "senderFriendlyName": "Player",
    "languageCode": "EN"
  }


问:
Sort doubly linked list by next id Ramda.js
I want to sort doubly linked list by next_id value.

My DLL:

```<code>const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]
</code>```

As a result:

```<code>const dll_result = [
  {id: '14', prev_id: null, next_id: '41'}, // next item - 41
  {id: '41', prev_id: '14', next_id: '22'}, // next item - 22
  {id: '22', prev_id: '41', next_id: '45'}, // next item - 45
  {id: '45', prev_id: '22', next_id: null},
]
</code>```

I understand that it may not make sense to sort the DLL, but in my case I need to sequentially visualize the data from the array using next_id.

P.S. It would be nice to know even a native solution, and then I could try to convert to Ramda.js myself

答:
Create an index of items by id, find the 1st item (prev_id === null), and then iterate with a while loop, and push the current object into the result array:

const findStart = R.find(R.propEq('prev_id', null))
const indexById = R.indexBy(R.prop('id'))

const sortByNextId = arr => {
  const index = indexById(arr)
  let current = findStart(arr)

  const sorted = []

  while(current) {
    sorted.push(current)
    current = index[current.next_id]
  }

  return sorted
}

const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]

const result = sortByNextId(dll)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script></code>```

Body:
I want to sort doubly linked list by next_id value.

My DLL:

const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]

As a result:

const dll_result = [
  {id: '14', prev_id: null, next_id: '41'}, // next item - 41
  {id: '41', prev_id: '14', next_id: '22'}, // next item - 22
  {id: '22', prev_id: '41', next_id: '45'}, // next item - 45
  {id: '45', prev_id: '22', next_id: null},
]

I understand that it may not make sense to sort the DLL, but in my case I need to sequentially visualize the data from the array using next_id.

P.S. It would be nice to know even a native solution, and then I could try to convert to Ramda.js myself

Body:
Create an index of items by id, find the 1st item (prev_id === null), and then iterate with a while loop, and push the current object into the result array:

const findStart = R.find(R.propEq('prev_id', null))
const indexById = R.indexBy(R.prop('id'))

const sortByNextId = arr => {
  const index = indexById(arr)
  let current = findStart(arr)

  const sorted = []

  while(current) {
    sorted.push(current)
    current = index[current.next_id]
  }

  return sorted
}

const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]

const result = sortByNextId(dll)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>


问:
Entity Framework - Filtering rows with where() after include
If I have two objects or models as below:

```<code>   class School
    {
        ICollection<Student> students { get; set; }
    }

    class Student
    {
        string Name { get; set; }
        School school { get; set; }
        bool Deleted { get; set; }
    }
</code>```

Howcome when trying to get a school with only students that are not deleted doesn't work properly using the where clause?

```<code>var school = DatabaseContext.Schools
             .Include(x => x.Students)
             .Where(y => !y.Deleted).FirstOrDefault();
</code>```

Shouldn't the where clause filter the students that are not deleted? Using where clause inside the include is not allowed too without using any third party libs.

答:
You need to go the other way, that is, select not deleted students and from them, project the schools:

```<code>var school = DatabaseContext.Students
                 .Where(s => !s.Deleted)
                 .Select(s => s.School)
                 .Distinct()
                 .FirstOrDefault();
</code>```

This depends on a School property on the Student class, which is not present in your model, probably was forgotten.

Body:
If I have two objects or models as below:

   class School
    {
        ICollection<Student> students { get; set; }
    }

    class Student
    {
        string Name { get; set; }
        School school { get; set; }
        bool Deleted { get; set; }
    }

Howcome when trying to get a school with only students that are not deleted doesn't work properly using the where clause?

var school = DatabaseContext.Schools
             .Include(x => x.Students)
             .Where(y => !y.Deleted).FirstOrDefault();

Shouldn't the where clause filter the students that are not deleted? Using where clause inside the include is not allowed too without using any third party libs.

Body:
You need to go the other way, that is, select not deleted students and from them, project the schools:

var school = DatabaseContext.Students
                 .Where(s => !s.Deleted)
                 .Select(s => s.School)
                 .Distinct()
                 .FirstOrDefault();

This depends on a School property on the Student class, which is not present in your model, probably was forgotten.


问:
Removing a line break after using list in paragraph
I am working on website where i have to put information so I am using a list inside a paragraph but after the list name the text moves to another line. I want to start a paragraph after the list.I have attached the output and my target.The output Output The target Target</p>

```<code>    <div class="history">
        <h1 class="h-history">History</h1>
        <p class="p">It was established in 1879....</p>
        <h1 class="h-history">Areas and attractions</h1>
        <p class="p"><li>Elephant House</li>is the first....</p>

    </div>
</code>```

答:
 is not a list. It is a list item. By default, the list item is rendered as a block element and hence the following text will be shown below that block.

However, you can achieve your target like this:

History

It was established in 1879....

Areas and attractions

Elephant house is the most famous exhibit in the zoo.

Ape house be carefull! Some inhabitants might throw smelly stuff at you

```

Here,
 (which is for unordered list) is used to markup a list. The list has 2 list items. A portion of the text content of the list items is emphasized as bold text ().

Body:
I am working on website where i have to put information so I am using a list inside a paragraph but after the list name the text moves to another line. I want to start a paragraph after the list.I have attached the output and my target.The output Output The target Target

History

It was established in 1879....

Areas and attractions

Elephant House
is the first....

Body:
<li> is not a list. It is a list item. By default, the list item is rendered as a block element and hence the following text will be shown below that block.

However, you can achieve your target like this:

<div class="history">
    <h1>History</h1>
    <p>It was established in 1879....</p>
    <h1>Areas and attractions</h1>
    <ul>
        <li><b>Elephant house</b> is the most famous exhibit in the zoo.</li>
        <li><b>Ape house</b> be carefull! Some inhabitants might throw smelly stuff at you</li>
    </ul>

</div>

Here, <ul> (which is for unordered list) is used to markup a list. The list has 2 list items. A portion of the text content of the list items is emphasized as bold text (<b>).


问:
C#: Is there a way to stop a random from generating again after it has been displayed
i need a way to store the random numbers generated in the parenthesis for a true/false or if statement but can't because it keeps regenerating new numbers after i input an answer. also if it generated a random of 44 and i answered 48 how do i call the random to display whether if it is correct or not?
Just a simple exercise to help myself with C# coding. Thank you for any answers given.

//There wasn't any problem with the coding at all. The problem was the Online compiler i was using, it kept refreshing every time i enter an input for answer so i thought it was giving me a new random set of numbers after it was already done with printing the entire set in the for loops. i apologize for the confusion! I don't have a visual studio so i was using an online compiler.

```<code>public static void Main()
{

    Random rand = new Random();
    int count, a, b, x, y;

    Console.Write("Sequence: ");
    count = int.Parse(Console.ReadLine());

    Console.Write("Minima: ");
    x = int.Parse(Console.ReadLine());

    Console.Write("Maxima: ");
    y = int.Parse(Console.ReadLine());

    int[] roll = new int[count];

    for(a = 0; a < count; a++){
        roll[a] = rand.Next(x, y);
    }

    Console.Write("( ");
    foreach(var nr in roll){
        Console.Write(nr + " ");
    }
    Console.WriteLine(")");

    Console.WriteLine("");
    int[] answer = new int[count];

    for(b = 0; b < count; b++){
        Console.Write("{0}. Answer: ",b+1);
        answer[b] =int.Parse(Console.ReadLine());
    }
    Console.ReadLine();
}
</code>```

}

答:
The solution is this

for(int i = 0; i < count; i++)
{
    if(roll[i] == answer[i])
    {
        Console.WriteLine("Question " + i + " is correct");
    }
}

```

Body:
i need a way to store the random numbers generated in the parenthesis for a true/false or if statement but can't because it keeps regenerating new numbers after i input an answer. also if it generated a random of 44 and i answered 48 how do i call the random to display whether if it is correct or not?
Just a simple exercise to help myself with C# coding. Thank you for any answers given.

//There wasn't any problem with the coding at all. The problem was the Online compiler i was using, it kept refreshing every time i enter an input for answer so i thought it was giving me a new random set of numbers after it was already done with printing the entire set in the for loops. i apologize for the confusion! I don't have a visual studio so i was using an online compiler.

public static void Main()
{

    Random rand = new Random();
    int count, a, b, x, y;

    Console.Write("Sequence: ");
    count = int.Parse(Console.ReadLine());

    Console.Write("Minima: ");
    x = int.Parse(Console.ReadLine());

    Console.Write("Maxima: ");
    y = int.Parse(Console.ReadLine());

    int[] roll = new int[count];

    for(a = 0; a < count; a++){
        roll[a] = rand.Next(x, y);
    }

    Console.Write("( ");
    foreach(var nr in roll){
        Console.Write(nr + " ");
    }
    Console.WriteLine(")");

    Console.WriteLine("");
    int[] answer = new int[count];

    for(b = 0; b < count; b++){
        Console.Write("{0}. Answer: ",b+1);
        answer[b] =int.Parse(Console.ReadLine());
    }
    Console.ReadLine();
}

}


问:
Extract unique constraint fields from sql exception
Is there any way to extract field names comming from sql exception? In the first example i get Geto in the second: Rest, 1

Example 1:

```<code>Violation of UNIQUE KEY constraint 'UQ__T_Client_NameSector'. Cannot insert duplicate key in object 'dbo.T_Clients'.
The duplicate key value is (Geto).
The statement has been terminated.
</code>```

Example 2:

```<code>Violation of UNIQUE KEY constraint 'UQ__T_Client_NameSector'. Cannot insert duplicate key in object 'dbo.T_Clients'.
The duplicate key value is (Rest, 1).
The statement has been terminated.
</code>```

答:
I think you are looking for something like </p>

```<code>catch (SqlException ex1) {
int start_index = ex1.StackTrace.IndexOf("The duplicate key value is (");
if (start_index > 1) {
in end_index = ex1.StackTrace.SubString(start_index).IndexOf(")");
string[] myVariableName = ex1.SubString(start_index, end_index).split(',');
.... use as best you see fit ...
}
}
</code>```

Body:
Is there any way to extract field names comming from sql exception? In the first example i get Geto in the second: Rest, 1

Example 1:

Violation of UNIQUE KEY constraint 'UQ__T_Client_NameSector'. Cannot insert duplicate key in object 'dbo.T_Clients'.
The duplicate key value is (Geto).
The statement has been terminated.

Example 2:

Violation of UNIQUE KEY constraint 'UQ__T_Client_NameSector'. Cannot insert duplicate key in object 'dbo.T_Clients'.
The duplicate key value is (Rest, 1).
The statement has been terminated.

Body:
I think you are looking for something like

catch (SqlException ex1) {
int start_index = ex1.StackTrace.IndexOf("The duplicate key value is (");
if (start_index > 1) {
in end_index = ex1.StackTrace.SubString(start_index).IndexOf(")");
string[] myVariableName = ex1.SubString(start_index, end_index).split(',');
.... use as best you see fit ...
}
}


问:
Regex find match word with some range front word
I Have a list of Word

"Dany buy some pear and apple"

"Dany eat the apple"

"Dany love apple"

"Dany make apple pie"

I really dont understand the keyword what is this.
But i want make some like this
Dany{2}(apple) =  find dany with the apple but max between dany and apple is 2 word

so it will give the result

```<code>Dany love apple
Dany make apple pie
Dany eat the apple
</code>```

答:
You may look for it:

```<code>Dany\s+(\w+\s+){0,2}apple.*
</code>```

Example

Body:
I Have a list of Word

"Dany buy some pear and apple"

"Dany eat the apple"

"Dany love apple"

"Dany make apple pie"

I really dont understand the keyword what is this.
But i want make some like this
Dany{2}(apple) =  find dany with the apple but max between dany and apple is 2 word

so it will give the result

Dany love apple
Dany make apple pie
Dany eat the apple

Body:
You may look for it:

Dany\s+(\w+\s+){0,2}apple.*

Example


问:
How do I store a .Net MemorySteam value in DynamoDB?
I am using AWS KMS Encrypt API to encrypt a text. The Encrypt API returns a EncryptResponse object that has a MemoryStream attribute which is the encrypted value.

I am using the AWS .Net SDK and trying to save this value to DynamoDB.

How can I save this value? I tried converting this to a String but while the conversion saving DynamoDB and retrieval gave me back the MemoryStream object, the resultant cipher text from the recreated MemoryStream object cannot be decrypted with an error "Invalid ciphertext."

Here is the code used to save and retrieve the string

```<code>// convert stream to string
StreamReader reader = new StreamReader(ciphertextBlob);
string text = reader.ReadToEnd();

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream = new MemoryStream(byteArray);
</code>```

When retrieving the stream it was noticed that the ciphertext was different for the object before saving and that during retrieval.

The EncryptFunction

The EncryptResponse

答:
This issue was solved by converting the memory stream object into a byte[] and saving it as a String in DynamoDB.

```<code>byte[] byteArray = ReadFully(ciphertextBlob);
                    string AccessKeycipherText = Convert.ToBase64String(byteArray);
</code>```

The base64 encoding was used to get a String representation of the byte array.

The memory stream object was retrieved using the reverse.

```<code>byte[] temp_backToBytes = Convert.FromBase64String(AccessKey);
                 MemoryStream stream = new MemoryStream(temp_backToBytes);
</code>```

Body:
I am using AWS KMS Encrypt API to encrypt a text. The Encrypt API returns a EncryptResponse object that has a MemoryStream attribute which is the encrypted value.

I am using the AWS .Net SDK and trying to save this value to DynamoDB.

How can I save this value? I tried converting this to a String but while the conversion saving DynamoDB and retrieval gave me back the MemoryStream object, the resultant cipher text from the recreated MemoryStream object cannot be decrypted with an error "Invalid ciphertext."

Here is the code used to save and retrieve the string

// convert stream to string
StreamReader reader = new StreamReader(ciphertextBlob);
string text = reader.ReadToEnd();

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream = new MemoryStream(byteArray);

When retrieving the stream it was noticed that the ciphertext was different for the object before saving and that during retrieval.

The EncryptFunction

The EncryptResponse

Body:
This issue was solved by converting the memory stream object into a byte[] and saving it as a String in DynamoDB.

byte[] byteArray = ReadFully(ciphertextBlob);
                    string AccessKeycipherText = Convert.ToBase64String(byteArray);

The base64 encoding was used to get a String representation of the byte array.

The memory stream object was retrieved using the reverse.

byte[] temp_backToBytes = Convert.FromBase64String(AccessKey);
                 MemoryStream stream = new MemoryStream(temp_backToBytes);


问:
RecyclerView scrolls to top after adding items
I have a RecyclerView that I use to display items in an activity. When I scroll to the bottom, I make another API call to fetch an additional set of data. When the items load, my RecyclerView scrolls to the top. I have tried the other solutions listed without success. I have attempted many if not all of the suggestions mentioned in similar threads. None of them worked for me.

activity_see_more.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/see_more_frameLayout" />
</LinearLayout>
</code>```

In the SeeMoreActivity.java I override the following method from the MvpView

```<code>@Override
public void loadPropertiesForCategory(List<Property> propertyList) {
    Preferences sharedPref = new Preferences(this);
    if (!properties.containsAll(propertyList)) {
        properties.addAll(propertyList);
    }
    sharedPref.setFilterList(properties);
    ResultListFragment fragment = ResultListFragment.setTag("see_more_filter");
    getSupportFragmentManager().beginTransaction().add(R.id.see_more_frameLayout, fragment, "search").commit();
}
</code>```

ResultListFragment.java

```<code>private void setListOfCategoryProperties() {
    page = 2;
    mSearchList = mPreferences.getFilterList();
    setListAdapter(false, false, View.VISIBLE, View.GONE, false);
    mResultRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (linearLayoutManager != null && linearLayoutManager.findLastVisibleItemPosition() == mSearchList.size() - 1) {
                ((SeeMoreActivity) getActivity()).setLoadPropertiesParamsAndCallApi(page);
                if (mSearchList.size() != mPreferences.getFilterList().size()) {
                    page++;
                    mSearchList = mPreferences.getFilterList();
                    //mAdapter.notifyDataSetChanged();
                    mAdapter.notifyItemInserted(mSearchList.size() - 1);
                }
            }
        }
    });
}

public void listAdapter() {
    mResultRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
    mResultRecycleView.setItemAnimator(new DefaultItemAnimator());
    mResultRecycleView.setNestedScrollingEnabled(true);
    mResultRecycleView.setAdapter(mAdapter);
}

private void setListAdapter(boolean showDeleteButton, boolean changeVisibility, int showNoResult, int showNoSavedSearch, boolean reverseFavorite) {
        if (mSearchList != null && mSearchList.size() != 0) {
            if (changeVisibility) {
                setVisibility(View.VISIBLE, View.GONE, View.GONE);
            }
            mAdapter = new SearchListAdapter(R.layout.item_single_element, mSearchList, showDeleteButton, this, reverseFavorite);
            listAdapter();
        } else {
            setVisibility(View.GONE, showNoSavedSearch, showNoResult);
        }
    }

public void handleTags() {
        switch (mTag) {
            case "result_search":
                setListAdapterForHomeSearch();
                break;
            case "see_more_filter":
                setListOfCategoryProperties();
                break;
            case Constants.USER_FAVORITES_KEY:
                setListOfUserFavoriteProperties();
                break;
        }
    }
</code>```

答:
It's a bit hard to tell, but it looks like you're re-setting the adapter to a new adapter every time you receive more data.  That resets a bunch of internal state in RecyclerView, so that's probably what's causing this.

To solve it, you should leave the existing adapter in place and instead call one of the Adapter.notify... methods (probably notifyItemRangeInserted) to inform the adapter that more data has been added.  You could also use ListAdapter and its submitList method to automatically handle it for you.

Body:
I have a RecyclerView that I use to display items in an activity. When I scroll to the bottom, I make another API call to fetch an additional set of data. When the items load, my RecyclerView scrolls to the top. I have tried the other solutions listed without success. I have attempted many if not all of the suggestions mentioned in similar threads. None of them worked for me.

activity_see_more.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/see_more_frameLayout" />
</LinearLayout>

In the SeeMoreActivity.java I override the following method from the MvpView

@Override
public void loadPropertiesForCategory(List<Property> propertyList) {
    Preferences sharedPref = new Preferences(this);
    if (!properties.containsAll(propertyList)) {
        properties.addAll(propertyList);
    }
    sharedPref.setFilterList(properties);
    ResultListFragment fragment = ResultListFragment.setTag("see_more_filter");
    getSupportFragmentManager().beginTransaction().add(R.id.see_more_frameLayout, fragment, "search").commit();
}

ResultListFragment.java

private void setListOfCategoryProperties() {
    page = 2;
    mSearchList = mPreferences.getFilterList();
    setListAdapter(false, false, View.VISIBLE, View.GONE, false);
    mResultRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (linearLayoutManager != null && linearLayoutManager.findLastVisibleItemPosition() == mSearchList.size() - 1) {
                ((SeeMoreActivity) getActivity()).setLoadPropertiesParamsAndCallApi(page);
                if (mSearchList.size() != mPreferences.getFilterList().size()) {
                    page++;
                    mSearchList = mPreferences.getFilterList();
                    //mAdapter.notifyDataSetChanged();
                    mAdapter.notifyItemInserted(mSearchList.size() - 1);
                }
            }
        }
    });
}

public void listAdapter() {
    mResultRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
    mResultRecycleView.setItemAnimator(new DefaultItemAnimator());
    mResultRecycleView.setNestedScrollingEnabled(true);
    mResultRecycleView.setAdapter(mAdapter);
}

private void setListAdapter(boolean showDeleteButton, boolean changeVisibility, int showNoResult, int showNoSavedSearch, boolean reverseFavorite) {
        if (mSearchList != null && mSearchList.size() != 0) {
            if (changeVisibility) {
                setVisibility(View.VISIBLE, View.GONE, View.GONE);
            }
            mAdapter = new SearchListAdapter(R.layout.item_single_element, mSearchList, showDeleteButton, this, reverseFavorite);
            listAdapter();
        } else {
            setVisibility(View.GONE, showNoSavedSearch, showNoResult);
        }
    }

public void handleTags() {
        switch (mTag) {
            case "result_search":
                setListAdapterForHomeSearch();
                break;
            case "see_more_filter":
                setListOfCategoryProperties();
                break;
            case Constants.USER_FAVORITES_KEY:
                setListOfUserFavoriteProperties();
                break;
        }
    }


问:
Skip an entry WHERE ROW_NUMBER() = X And corresponding entry = 'Y'
I have a table with the ROW_NUMBER() partitioned over the User:

```<code>Row|Activity|User
-----------------
1  |A       |Jeff
2  |A       |Jeff
3  |A       |Jeff
1  |A       |Bob
2  |B       |Bob
3  |C       |Bob
1  |A       |Sam
2  |B       |Sam
3  |A       |Sam
4  |D       |Sam
</code>```

I would like to skip, during the row count, the entry 3 for Jeff and Sam because if a User's 3rd Activity is A, I should skip it. I call the to-be-skipped rows 'restricted rows'. Basically, I want this table as a result (Without the comments obviously):

```<code>Row|Activity|User
-----------------
1  |A       |Jeff
2  |A       |Jeff --3rd activity is A so it gets skipped
1  |A       |Bob
2  |B       |Bob
3  |C       |Bob --3rd activity isn't A so it doesn't get skipped
1  |A       |Sam
2  |B       |Sam --3rd activity is A so it gets skipped
3  |D       |Sam
</code>```

My query:

```<code>SELECT ROW_NUMBER() OVER(PARTITION BY User) AS Row, Activity, User FROM Table1
WHERE [Filters]
AND User IN(SELECT User IN Table1
            WHERE [Filters] --Same filters as above
            GROUP BY User HAVING COUNT(User) > 1) --Let's call this the 'Minimum 1 Activity Filter'
</code>```

I am going to be perfectly honest, right now, I don't know if the Minimum 1 Activity Filter will cause problems later, aka if Row 2 will also have restrictions. Because of that, I prefer treading on the safe side and imagine that I will have to check the Minimum 1 Activity Filter once all the restricted rows have been taken care of.

答:
if a User's 3rd Activity is A, I should skip it

Consider:

```<code>select
    row_number() over(partition by user order by id) rn,
    activity,
    user
from (
    select
        t.*,
        row_number() over(partiton by user order id) rn
    from mytable t
) t
where not (rn = 3 and activity = 'A')
</code>```

Note that, for this to work, you do need a column that can be used to sort the records - I assumed column id.

Body:
I have a table with the ROW_NUMBER() partitioned over the User:

Row|Activity|User
-----------------
1  |A       |Jeff
2  |A       |Jeff
3  |A       |Jeff
1  |A       |Bob
2  |B       |Bob
3  |C       |Bob
1  |A       |Sam
2  |B       |Sam
3  |A       |Sam
4  |D       |Sam

I would like to skip, during the row count, the entry 3 for Jeff and Sam because if a User's 3rd Activity is A, I should skip it. I call the to-be-skipped rows 'restricted rows'. Basically, I want this table as a result (Without the comments obviously):

Row|Activity|User
-----------------
1  |A       |Jeff
2  |A       |Jeff --3rd activity is A so it gets skipped
1  |A       |Bob
2  |B       |Bob
3  |C       |Bob --3rd activity isn't A so it doesn't get skipped
1  |A       |Sam
2  |B       |Sam --3rd activity is A so it gets skipped
3  |D       |Sam

My query:

SELECT ROW_NUMBER() OVER(PARTITION BY User) AS Row, Activity, User FROM Table1
WHERE [Filters]
AND User IN(SELECT User IN Table1
            WHERE [Filters] --Same filters as above
            GROUP BY User HAVING COUNT(User) > 1) --Let's call this the 'Minimum 1 Activity Filter'

I am going to be perfectly honest, right now, I don't know if the Minimum 1 Activity Filter will cause problems later, aka if Row 2 will also have restrictions. Because of that, I prefer treading on the safe side and imagine that I will have to check the Minimum 1 Activity Filter once all the restricted rows have been taken care of.

Body:
if a User's 3rd Activity is A, I should skip it

Consider:

select
    row_number() over(partition by user order by id) rn,
    activity,
    user
from (
    select
        t.*,
        row_number() over(partiton by user order id) rn
    from mytable t
) t
where not (rn = 3 and activity = 'A')

Note that, for this to work, you do need a column that can be used to sort the records - I assumed column id.