问:
Mongoose: Property 'forEach' does not exist on type 'ObjectId | [BaseAction]'
I just get this error.
Property 'forEach' does not exist on type 'ObjectId | [BaseAction]'.

The error is on the last line, the code is :

```<code>    ServiceModel.findOne({name: "slack"}).populate({
        path: 'actions',
        model: 'BaseActionModel',
    }).then((res) => {
        if (!res?.actions) return // null verif

        res.actions.forEach((action: BaseAction) => {
</code>```

I search but I found nothing on it.
To add more context, my models are :

```<code>@ObjectType({description: 'Services'})
export class Service {
    @Field(() => ID)
    id!: string;

    @Field()
    @Property()
    name!: String;

    @Field()
    @Property()
    out_url!: String;

    @Field()
    @Property()
    in_url!: String;

    @Field((_type) => [BaseAction])
    @Property({ref: BaseAction})
    actions: Ref<[BaseAction]>;
}
</code>```

You can ask for more code if you want

答:
In order to perform a OneToMany relationship in type-graphql, you need to use typeorm.</p>
```<code>import {ObjectType, Field, ID, InputType} from 'type-graphql';
import {prop as Property, getModelForClass, Ref} from '@typegoose/typegoose';
import {OneToMany} from "typeorm"; // import this

@ObjectType({description: 'Services'})
export class Service {
    @Field(() => ID)
    id!: string;

    @Field()
    @Property()
    name!: String;

    @Field()
    @Property()
    out_url!: String;

    @Field()
    @Property()
    in_url!: String;

    @Field((_type) => [BaseAction])
    // @ts-ignore type unused
    @OneToMany(type => BaseAction, action => action.id) // add this
    actions?: BaseAction[];
}

</code>```

Body:
I just get this error.
Property 'forEach' does not exist on type 'ObjectId | [BaseAction]'.

The error is on the last line, the code is :

    ServiceModel.findOne({name: "slack"}).populate({
        path: 'actions',
        model: 'BaseActionModel',
    }).then((res) => {
        if (!res?.actions) return // null verif

        res.actions.forEach((action: BaseAction) => {

I search but I found nothing on it.
To add more context, my models are :

@ObjectType({description: 'Services'})
export class Service {
    @Field(() => ID)
    id!: string;

    @Field()
    @Property()
    name!: String;

    @Field()
    @Property()
    out_url!: String;

    @Field()
    @Property()
    in_url!: String;

    @Field((_type) => [BaseAction])
    @Property({ref: BaseAction})
    actions: Ref<[BaseAction]>;
}

You can ask for more code if you want

Body:
In order to perform a OneToMany relationship in type-graphql, you need to use typeorm.

import {ObjectType, Field, ID, InputType} from 'type-graphql';
import {prop as Property, getModelForClass, Ref} from '@typegoose/typegoose';
import {OneToMany} from "typeorm"; // import this

@ObjectType({description: 'Services'})
export class Service {
    @Field(() => ID)
    id!: string;

    @Field()
    @Property()
    name!: String;

    @Field()
    @Property()
    out_url!: String;

    @Field()
    @Property()
    in_url!: String;

    @Field((_type) => [BaseAction])
    // @ts-ignore type unused
    @OneToMany(type => BaseAction, action => action.id) // add this
    actions?: BaseAction[];
}


来源: stackexchange

问:
Jmeter test error : URI does not specify a valid host name
I have configured  Jmeter  in Jenkins pipeline but when the stage runs it appears as if the tests are not executing as expected and in the console output I can see an error
Non HTTP response message: URI does not specify a valid host name: http:/http:10.XXX.XXX.XXX:32518/account?field4=3025202645050&field7=generic01&field10=abc098 . The URL is being intepreted incorrectly as it has http appearing twice.

This is part of the Jenkins pipeline :

```<code>pipeline {
agent any
triggers {
    githubPush()
}
environment {
.......
   REPOSITORY_URI = "${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${IMAGE_REPO_NAME}"
}
    stages {
......
.......
      stage ("UnitTest Report") {
                 steps{
                         publishHTML target: [
          allowMissing: false,
          alwaysLinkToLastBuild: true,
          keepAll: true,
          reportDir: '/var/lib/jenkins/workspace/FlexToEcocash_main/IntegrationTests/BuildReports/Coverage',
          reportFiles: 'index.html',
          reportName: 'Code Coverage'
          ]
                   archiveArtifacts artifacts: 'IntegrationTests/BuildReports/Coverage/*.*'
                   }
             }
                stage ("Perfomance Test") {
                steps {
                         build job: 'EcoToFlexPerfomanceTests'
                }
             }
    }

    }
</code>```

The stage Perfomance Test triggers a Freestyle Job named EcoToFlexPerfomanceTests and this will be the one that runs Jmeter tests.

Part of the console output :

Looking at the Performance Test Reports I am not sure if they are also showing the data correctly, they seem not populated as of now:

Environment:
Debian 10 Buster
.Net 5 API running on k0s

What am I missing ?

答:
There is a problem with the URL of the HTTP Request sampler in your script:

It should look like:

```<code>http://10.XXX.XXX.XXX:32518/account......
</code>```

so use Debug Sampler and View Results Tree listener combination to see all JMeter Variables with their values and correct the URL of the sampler and the problem should go away.

ContentLicense: CC BY-SA 4.0

Body:
I have configured  Jmeter  in Jenkins pipeline but when the stage runs it appears as if the tests are not executing as expected and in the console output I can see an error
Non HTTP response message: URI does not specify a valid host name: http:/http:10.XXX.XXX.XXX:32518/account?field4=3025202645050&field7=generic01&field10=abc098 . The URL is being intepreted incorrectly as it has http appearing twice.

This is part of the Jenkins pipeline :

pipeline {
agent any
triggers {
    githubPush()
}
environment {
.......
   REPOSITORY_URI = "${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${IMAGE_REPO_NAME}"
}
    stages {
......
.......
      stage ("UnitTest Report") {
                 steps{
                         publishHTML target: [
          allowMissing: false,
          alwaysLinkToLastBuild: true,
          keepAll: true,
          reportDir: '/var/lib/jenkins/workspace/FlexToEcocash_main/IntegrationTests/BuildReports/Coverage',
          reportFiles: 'index.html',
          reportName: 'Code Coverage'
          ]
                   archiveArtifacts artifacts: 'IntegrationTests/BuildReports/Coverage/*.*'
                   }
             }
                stage ("Perfomance Test") {
                steps {
                         build job: 'EcoToFlexPerfomanceTests'
                }
             }
    }

    }

The stage Perfomance Test triggers a Freestyle Job named EcoToFlexPerfomanceTests and this will be the one that runs Jmeter tests.

Part of the console output :

Looking at the Performance Test Reports I am not sure if they are also showing the data correctly, they seem not populated as of now:

Environment:
Debian 10 Buster
.Net 5 API running on k0s

What am I missing ?

Body:
There is a problem with the URL of the HTTP Request sampler in your script:

It should look like:

http://10.XXX.XXX.XXX:32518/account......

so use Debug Sampler and View Results Tree listener combination to see all JMeter Variables with their values and correct the URL of the sampler and the problem should go away.


问:
Creating a Silverlight DataTemplate in code
How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.

Edit: Here's the code I'm now using this for, based on the answer from Santiago below.

```<code>public DataTemplate Create(Type type)
{
  return (DataTemplate)XamlReader.Load(
          @"<DataTemplate
            xmlns=""http://schemas.microsoft.com/client/2007"">
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
            </DataTemplate>"
   );
}
</code>```

This works really nicely and allows me to change the binding on the fly.

答:
Yes, Silverligt 4 older than WPF's current versions.
When you add a template as a resource i.e. as I did
I added a userControl Template in Application.xaml MergedResources between ResourceDictionary.
In XAML if tag implemented IDictionary you could user x:Key attribute. Like that

```<code>   <ResourceDictionary>
    <DataTemplate x:Key="TextBoxEditTemplate">
    <Some user control x:Name="myOwnControl" />
    </DataTemplate>
   </ResourceDictionary>
</code>```

Ok! You may reach your template by coding that, Application.Current.resources["TextBoxEditTemplate"]
on the other hand some methods for finding members of this template will not work. Beside this DataTemplate doesn't implement IDictionary so you cannot assign x:Key attribute for items in this dataTemplate. as myOwnControl in example.

Without xaml current silverlight has some restrictions about creation fully dynamic code-behind DataTemplates.Even it works on WPF.

Anyway the best solution by this point is creation of XAML script for datatemplate ,You may assing some values element in DataTemplate script. We created our own usercontrols has some properties with DependencyObjectProperty...

At last if your object has no inherits ,i.e. not a MyControl:UserControl you may inherit MyObject:DependencyObject by this way you can reach your object by calling like Application.Current.Resources.FirstChilderen...

FindName works only in WPF

OwnerDisplayName: Nick R

ContentLicense: CC BY-SA 2.5

Body:
How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.

Edit: Here's the code I'm now using this for, based on the answer from Santiago below.

public DataTemplate Create(Type type)
{
  return (DataTemplate)XamlReader.Load(
          @"<DataTemplate
            xmlns=""http://schemas.microsoft.com/client/2007"">
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
            </DataTemplate>"
   );
}

This works really nicely and allows me to change the binding on the fly.

LastEditorDisplayName: Nick R

Body:
Yes, Silverligt 4 older than WPF's current versions.
When you add a template as a resource i.e. as I did
I added a userControl Template in Application.xaml MergedResources between ResourceDictionary.
In XAML if tag implemented IDictionary you could user x:Key attribute. Like that

   <ResourceDictionary>
    <DataTemplate x:Key="TextBoxEditTemplate">
    <Some user control x:Name="myOwnControl" />
    </DataTemplate>
   </ResourceDictionary>

Ok! You may reach your template by coding that, Application.Current.resources["TextBoxEditTemplate"]
on the other hand some methods for finding members of this template will not work. Beside this DataTemplate doesn't implement IDictionary so you cannot assign x:Key attribute for items in this dataTemplate. as myOwnControl in example.

Without xaml current silverlight has some restrictions about creation fully dynamic code-behind DataTemplates.Even it works on WPF.

Anyway the best solution by this point is creation of XAML script for datatemplate ,You may assing some values element in DataTemplate script. We created our own usercontrols has some properties with DependencyObjectProperty...

At last if your object has no inherits ,i.e. not a MyControl:UserControl you may inherit MyObject:DependencyObject by this way you can reach your object by calling like Application.Current.Resources.FirstChilderen...

FindName works only in WPF

ContentLicense: CC BY-SA 3.0


问:
`pd.read_sql(sql, engine)` raises NotImplementedError: This method is not implemented for SQLAlchemy 2.0
I tried to create a pandas DataFrame directly from my sqlserver database using an sqlalchemy engine:

```<code>engine = create_engine(URL_string, echo=False, future=True)
query_string = "..."
dt = pd.read_sql(query_string, engine)
</code>```

But this raises this error:

```<code>File <redacted>/venv/lib/python3.8/site-packages/sqlalchemy/future/engine.py:320, in Engine._not_implemented(self, *arg, **kw)
    319 def _not_implemented(self, *arg, **kw):
--> 320     raise NotImplementedError(
    321         "This method is not implemented for SQLAlchemy 2.0."
    322     )

NotImplementedError: This method is not implemented for SQLAlchemy 2.0.
</code>```

I do this because using pyodbc's connection alone gives a warning:

```<code>UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy
  warnings.warn(
</code>```

I'm using sqlalchemy version 1.4 ... so how do I fix this?

答:
Just remove future=True from the engine parameters:

```<code>engine = create_engine(URL_string, echo=False)
</code>```

Then you should be good to go!

Body:
I tried to create a pandas DataFrame directly from my sqlserver database using an sqlalchemy engine:

engine = create_engine(URL_string, echo=False, future=True)
query_string = "..."
dt = pd.read_sql(query_string, engine)

But this raises this error:

File <redacted>/venv/lib/python3.8/site-packages/sqlalchemy/future/engine.py:320, in Engine._not_implemented(self, *arg, **kw)
    319 def _not_implemented(self, *arg, **kw):
--> 320     raise NotImplementedError(
    321         "This method is not implemented for SQLAlchemy 2.0."
    322     )

NotImplementedError: This method is not implemented for SQLAlchemy 2.0.

I do this because using pyodbc's connection alone gives a warning:

UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy
  warnings.warn(

I'm using sqlalchemy version 1.4 ... so how do I fix this?

Body:
Just remove future=True from the engine parameters:

engine = create_engine(URL_string, echo=False)

Then you should be good to go!


问:
C# - Crop Transparent/White space
I'm trying to remove all white or transparent pixels from an image, leaving the actual image (cropped). I've tried a few solutions, but none seem to work. Any suggestions or am I going to spend the night writing image cropping code?</p>

答:
Adding to this, if you are in WPF and you have excess space around your image, check the properties of the image and make sure your Stretch property is set to fill. This eliminated the space around the image.

Screen shot of the property in WPF

Title: C# - Crop Transparent/White space


问:
How to execute multiple coroutines concurrently and do something when some coroutines finishes?

Context

I have three recipe classes which shares a common ingredient.

class BrewedNoodle:
    ingredients: list[Coroutine] = [Noodle]

    async def cook(noodle: Noodle):
        pass

class PorkNoodle:
    ingredients: list[Coroutine] = [Noodle, Pork]

    async def cook(noodle: Noodle, pork: Pork):
        pass

class BeefNoodle:
    ingredients: list[Coroutine] = [Noodle, Beef]

    async def cook(noodle: Noodle, beef: Beef):
        pass

```
<p>please consider each indredient as an API (needs network call)</p>
<h2>What I want to do</h2>
<p>I want to perform <code>asyncio.gather()</code> to fetch(prepare) each ingredients concurrently.
and as soon as all necessary ingredients are prepared for a specific recipe, I want to cook it immediately, not waiting for other ingredients.</p>
<p>For example:</p>
<ol>
<li>as soon as Noodle is prepared, I cook BrewedNoodle.</li>
<li>And Pork is prepared, (since Noodle and Pork is ready) then I cook PorkNoodle.</li>
<li>And after the beef is prepared I cook BeefNoodle.</li>
</ol>
<h2>What I actually did</h2>
<p>but I'm awaiting <code>asyncio.gather()</code>, I'm destined to wait until all ingredients are ready. (I can not pre-cook BrewedNoodle even if Noodle is prepared)</p>
<pre class="lang-py prettyprint-override"><code># prepare ingredients
noodle, pork, beef = await asyncio.gather(Noodle(), Pork(), Beef())

# cook
BrewedNoodle().cook(noodle)
PorkNoodle().cook(noodle, pork)
BeefNoodle().cook(noodle, beef)
</code>```

Question

How can I cook a Recipe when necessary ingredients are ready without waiting for other ingredients?

答:
If I understand your example correctly, there needs to be some kind of explicit mapping from ingredients to the dishes that can be created from them. The special case of Noodle being required for the other dishes also needs to be addressed separately. The core of the algorithm is asyncio.as_completed():

dishes = {
    Noodle: BrewedNoodle,
    Pork: PorkNoodle,
    Beef: BeefNoodle,
}
ingredients = [Noodle(), Pork(), Beef()]
noodle = None
for coro in asyncio.as_completed(ingredients):
    ingredient = await coro
    dish = dishes[type(ingredient)]
    if isinstance(ingredient, Noodle):
        dish.cook(ingredient)
        noodle = ingredient
    else:
        # Pork or Beef, assuming noodle has already finished
        dish.cook(noodle, ingredient)
```

Body:
Context

I have three recipe classes which shares a common ingredient.

class BrewedNoodle:
    ingredients: list[Coroutine] = [Noodle]

    async def cook(noodle: Noodle):
        pass

class PorkNoodle:
    ingredients: list[Coroutine] = [Noodle, Pork]

    async def cook(noodle: Noodle, pork: Pork):
        pass

class BeefNoodle:
    ingredients: list[Coroutine] = [Noodle, Beef]

    async def cook(noodle: Noodle, beef: Beef):
        pass

please consider each indredient as an API (needs network call)

What I want to do

I want to perform asyncio.gather() to fetch(prepare) each ingredients concurrently.
and as soon as all necessary ingredients are prepared for a specific recipe, I want to cook it immediately, not waiting for other ingredients.

For example:

as soon as Noodle is prepared, I cook BrewedNoodle.

And Pork is prepared, (since Noodle and Pork is ready) then I cook PorkNoodle.

And after the beef is prepared I cook BeefNoodle.

What I actually did

but I'm awaiting asyncio.gather(), I'm destined to wait until all ingredients are ready. (I can not pre-cook BrewedNoodle even if Noodle is prepared)

# prepare ingredients
noodle, pork, beef = await asyncio.gather(Noodle(), Pork(), Beef())

# cook
BrewedNoodle().cook(noodle)
PorkNoodle().cook(noodle, pork)
BeefNoodle().cook(noodle, beef)

Question

How can I cook a Recipe when necessary ingredients are ready without waiting for other ingredients?


问:
How to set up Blazor project and Razorpages project in the same solution
I created ASP.NET Blazor project and RazorPages project in the same solution. How can I integrate these two projects in the same solution?</p>

答: You need to add reference using visual studio. See here</p>


问:
Livy on K8S, namespace restriction
I have spark (3.0.1), livy (0.8.0) and Jupyterhub (sparkmagic) running on K8S in specific namespace, Kubernetes master is used as a resource manager.

When trying to create pyspark session in Jupyterhub's notebook I get the error:

22/02/04 12:09:16 WARN InteractiveSession: Failed to stop RSCDriver.
Killing it... 22/02/04 12:09:18 WARN InteractiveSession: Error
stopping session 2.
io.fabric8.kubernetes.client.KubernetesClientException: Failure
executing: GET at:
https://kubernetes.default.svc.cluster.local/api/v1/pods?labelSelector=spark-app-tag%2Cspark-role%3Ddriver%2Cspark-app-selector.
Message: Forbidden!Configured service account doesn't have access.
Service account may have been revoked. pods is forbidden: User
"system:serviceaccount:namespace:livy-acc" cannot list resource
"pods" in API group "" at the cluster scope.

This error states that livy's Kubernetes client tries to list all the pods clusterwide but lacking permissions to do that.

Is it possible to restrict/limit the livy to operate in a certain namespace on Kubernetes, as the alternative of giving away cluster role is not an option due some security concerns.

答:
During code examination of livy 0.8.0 from this repo: https://github.com/jahstreet/incubator-livy.git --branch merge/first I have discovered some undocumented livy.server.kubernetes.* properties that can be used to configure how livy runs on K8S.

For K8S namespace restriction following properties can be used:

```<code># Comma-separated list of the Kubernetes namespaces to allow for applications creation.
# All namespaces are allowed if empty
livy.server.kubernetes.allowedNamespaces = namespace

# Kubernetes client default namespace
livy.server.kubernetes.defaultNamespace = namespace
</code>```

Title: Livy on K8S, namespace restriction

Body:
During code examination of livy 0.8.0 from this repo: https://github.com/jahstreet/incubator-livy.git --branch merge/first I have discovered some undocumented livy.server.kubernetes.* properties that can be used to configure how livy runs on K8S.

For K8S namespace restriction following properties can be used:

# Comma-separated list of the Kubernetes namespaces to allow for applications creation.
# All namespaces are allowed if empty
livy.server.kubernetes.allowedNamespaces = namespace

# Kubernetes client default namespace
livy.server.kubernetes.defaultNamespace = namespace


问:
Detail Meshing for Airfoil Forepart
I study on this airfoil and ı want to detail meshing on forepart. Actually my element quality was good for in this mesh but ı dont want to red ared on this airfoil. In addition to, ı want to hear all of your ideas. enter image description here

答:
As you are providing very little information on what you are trying to achieve (Is this a structural, fluid or thermal problem? ) I can only guess:

Increasing the element count on the edge could produce less skewed elements.

In reality the edge is probalby not sharp but has some kind of chamfer. Try to model it accordingly

Title: Detail Meshing for Airfoil Forepart


问:
Take URL to open larger map from iFrame?
I want to get a link to open a larger map from the iFrame URL:

```<code><iframe
src='https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d414225.88930329087!2d14.068999827954114!3d46.99590051638977!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47707345308f7e65%3A0x687eb6df8c618d2b!2sKlagenfurt%2C%20Austria!5e0!3m2!1sen!2srs!4v1643793775072!5m2!1sen!2srs'
style='border:0;' allowfullscreen='' loading='lazy'></iframe>

</code>```

This URL from iframe to open in a new tab is invalid :

```<code>https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d414225.88930329087!2d14.068999827954114!3d46.99590051638977!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47707345308f7e65%3A0x687eb6df8c618d2b!2sKlagenfurt%2C%20Austria!5e0!3m2!1sen!2srs!4v1643793775072!5m2!1sen!2srs
</code>```

I tried to take the URL from iFrame :

But in website mounting time, JS cannot read iFrame DOM... Any suggestions?

答:
You should read what the response from your URL already tells you:

The Google Maps Embed API must be used in an iframe.

As you can see in the example in the Google Maps Embed API docs:

```

You're missing the ?key=API_KEY part. So, set up an API key as described on the website, and you're good to go.

Body:
I want to get a link to open a larger map from the iFrame URL:

This URL from iframe to open in a new tab is invalid :

https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d414225.88930329087!2d14.068999827954114!3d46.99590051638977!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47707345308f7e65%3A0x687eb6df8c618d2b!2sKlagenfurt%2C%20Austria!5e0!3m2!1sen!2srs!4v1643793775072!5m2!1sen!2srs

I tried to take the URL from iFrame :

But in website mounting time, JS cannot read iFrame DOM... Any suggestions?

Body:
You should read what the response from your URL already tells you:

The Google Maps Embed API must be used in an iframe.

As you can see in the example in the Google Maps Embed API docs:

<iframe
  width="600"
  height="450"
  style="border:0"
  loading="lazy"
  allowfullscreen
  src="https://www.google.com/maps/embed/v1/place?key=API_KEY
    &q=Space+Needle,Seattle+WA">
</iframe>

You're missing the ?key=API_KEY part. So, set up an API key as described on the website, and you're good to go.


问:
Why is this code printing a line after reading one line of content
```<code>file = 'pi'
with open(file) as object:
    for line in object:
        print(line)
</code>```

The file content includes the first 30 digits of pi, and I don't understand why it is printing a line after reading a particular line. As in, how can print(line) actually print a line?

The contents of the file are henceforth:

```<code>3.1415926535
8979323846
2643383279
</code>```

And this is the output:

```<code>3.1415926535

8979323846

2643383279
</code>```

答:
According to the documentation provided here:

```<code>print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
</code>```

Print objects to the text stream file, separated by sep and followed
by end. sep, end, file, and flush, if present, must be given as
keyword arguments.

If no parameters are provided, end parameter takes "\n" by default.

So, you could print the lines like:

```<code>print(line, end='')
</code>```

Body:
file = 'pi'
with open(file) as object:
    for line in object:
        print(line)

The file content includes the first 30 digits of pi, and I don't understand why it is printing a line after reading a particular line. As in, how can print(line) actually print a line?

The contents of the file are henceforth:

3.1415926535
8979323846
2643383279

And this is the output:

3.1415926535

8979323846

2643383279

Body:
According to the documentation provided here:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the text stream file, separated by sep and followed
by end. sep, end, file, and flush, if present, must be given as
keyword arguments.

If no parameters are provided, end parameter takes "\n" by default.

So, you could print the lines like:

print(line, end='')


问:
Reflection problems with super class in Spring Boot
My goal is to create class level annotations, but I keep getting this error. For some reason, reflection isn't working when I use getClass to get the information of the annotation. I tried using aspects, but I'm not sure how to make spring boot aspect annotations class level.

```<code>org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.lang.Class.
</code>```

Below are the classes I used

```<code>@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.TYPE)
public @interface ValidateInput {
    short minLength();
    short maxLength();
    String regex() default "";
}
</code>```
```<code>public abstract class SimpleValidation {

    private String text;
    private ValidateInput info = this.getClass().getAnnotation(ValidateInput.class);

    protected SimpleValidation(String text) {
        this.text = text;
    }
}
</code>```
```<code>@Value
@EqualsAndHashCode(callSuper = true)
@ValidateInput(maxLength = 50, minLength = 5, regex = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$")
public class Email extends SimpleValidation {
    String email;

    public Email(String email) {
        super(email);
        this.email = email;
    }
}
</code>```

答:
I think you are trying to recreate the Bean validation behaviour which is already something standard, try to use it, as it will be easier than creating a heavy hierarchy of classes for achieving that.

Spring will be able to verify your validation automatically (After deserializing a JSON body, before inserting in DB..)

Body:
My goal is to create class level annotations, but I keep getting this error. For some reason, reflection isn't working when I use getClass to get the information of the annotation. I tried using aspects, but I'm not sure how to make spring boot aspect annotations class level.

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.lang.Class.

Below are the classes I used

@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.TYPE)
public @interface ValidateInput {
    short minLength();
    short maxLength();
    String regex() default "";
}

public abstract class SimpleValidation {

    private String text;
    private ValidateInput info = this.getClass().getAnnotation(ValidateInput.class);

    protected SimpleValidation(String text) {
        this.text = text;
    }
}

@Value
@EqualsAndHashCode(callSuper = true)
@ValidateInput(maxLength = 50, minLength = 5, regex = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$")
public class Email extends SimpleValidation {
    String email;

    public Email(String email) {
        super(email);
        this.email = email;
    }
}


问:
AcquireTokenForClient(ewsScopes).ExecuteAsync() "Request to the endpoint timed out" in IIS
I have a Webforms (ASP.Net) application which is trying to get a accesstoken from office365.

I succesfully get the token running the Website in IIS Express in Visual Studio (2019).

Running the website in IIS, i get the error "Request to the endpoint timed out".

Please, can anybody help?

```<code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim cca = ConfidentialClientApplicationBuilder.
            Create("000000-0000-0000").
            WithClientSecret("xxxxxxxxxxxxx").
            WithTenantId("00000-0000-0000").
            Build()

    Dim ewsScopes() As String = {"https://outlook.office365.com/.default"}
    Dim rc As String = cca.AcquireTokenForClient(ewsScopes).ExecuteAsync().GetAwaiter().GetResult().AccessToken
    Page.Response.Write(rc)
End Sub
</code>```

答:
You can try to increase request time in the web.config.</p>
```<code><system.web>
  <httpRuntime executionTimeout="180" />
</system.web>
</code>```

Body:
I have a Webforms (ASP.Net) application which is trying to get a accesstoken from office365.

I succesfully get the token running the Website in IIS Express in Visual Studio (2019).

Running the website in IIS, i get the error "Request to the endpoint timed out".

Please, can anybody help?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim cca = ConfidentialClientApplicationBuilder.
            Create("000000-0000-0000").
            WithClientSecret("xxxxxxxxxxxxx").
            WithTenantId("00000-0000-0000").
            Build()

    Dim ewsScopes() As String = {"https://outlook.office365.com/.default"}
    Dim rc As String = cca.AcquireTokenForClient(ewsScopes).ExecuteAsync().GetAwaiter().GetResult().AccessToken
    Page.Response.Write(rc)
End Sub

Body:
You can try to increase request time in the web.config.

<system.web>
  <httpRuntime executionTimeout="180" />
</system.web>


问:
Upgrade Apache Superset 0.19.0 to the latest (1.3.2?)
We want to upgrade our old superset installation (0.19.0) to the latest version (1.3.2 or 1.4.0), and are just wondering whether there is anything we need to do to migrate the existing dashboards?

All meta data sits in AWS RDS database. Do we need to make any change in the DB, or just simply connect to it from the new Superset version?

答: Export all the dashboards, connect the to the  database from the new supersert version and import the dashboards to the new environment</p>


问:
OledbConnection Invalid Arguments
I try to read Excel file in Selenium Webdriver C# but got Invalid Arguments at connection.Open() . What am I wrong?

```<code>using System.Configuration;
using System.Data.OleDb;
using System.Linq;

namespace LeTuanAnh_Training.TestDataAccess
{
    class ExcelDataAccess
    {
        public static string TestDataFileConnection()
        {
            var fileName = ConfigurationManager.AppSettings["TestDataSheetPath"];
            var con = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = {0}; Extended Properties=Excel 12.0;", fileName);
            return con;
        }

        public static UserData GetTestData(string keyName)
        {
            using (var connection = new OleDbConnection(TestDataFileConnection()))
            {
                connection.Open();
                var query = string.Format("select * from [Sheet1$] where key='{0}'", keyName);
                var value = connection.Query<UserData>(query).FirstOrDefault();
                connection.Close();
                return value;
            }
        }
    }
}
</code>```

App.config file

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings configSource="Configurations\Environment.config" />
</configuration>
</code>```

Environment.config file

```<code><?xml version="1.0" encoding="utf-8" ?>
    <appSettings>
      <add key="TestDataSheetPath" value="TestDataAccess/Data.xlsx"/>
</appSettings>
</code>```

Error Pic

答:
When you are doing

```<code>using (var connection = new OleDbConnection(TestDataFileConnection()))
</code>```

The Using keyword open the connection and closes it when the using block ends. So you don't need the connection.Open() and the connection.Close().

Try to connect to your DB and double-check the DB connection data. Your question has nothing to do with Selenium...

Title: OledbConnection Invalid Arguments

Body:
I try to read Excel file in Selenium Webdriver C# but got Invalid Arguments at connection.Open() . What am I wrong?

using System.Configuration;
using System.Data.OleDb;
using System.Linq;

namespace LeTuanAnh_Training.TestDataAccess
{
    class ExcelDataAccess
    {
        public static string TestDataFileConnection()
        {
            var fileName = ConfigurationManager.AppSettings["TestDataSheetPath"];
            var con = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = {0}; Extended Properties=Excel 12.0;", fileName);
            return con;
        }

        public static UserData GetTestData(string keyName)
        {
            using (var connection = new OleDbConnection(TestDataFileConnection()))
            {
                connection.Open();
                var query = string.Format("select * from [Sheet1$] where key='{0}'", keyName);
                var value = connection.Query<UserData>(query).FirstOrDefault();
                connection.Close();
                return value;
            }
        }
    }
}

App.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings configSource="Configurations\Environment.config" />
</configuration>

Environment.config file

<?xml version="1.0" encoding="utf-8" ?>
    <appSettings>
      <add key="TestDataSheetPath" value="TestDataAccess/Data.xlsx"/>
</appSettings>

Error Pic

Body:
When you are doing

using (var connection = new OleDbConnection(TestDataFileConnection()))

The Using keyword open the connection and closes it when the using block ends. So you don't need the connection.Open() and the connection.Close().

Try to connect to your DB and double-check the DB connection data. Your question has nothing to do with Selenium...


问:
How we can share a google docs link with others without requesting access using PHP?
Is it possible to share a google docs link to others so that they can see and edit my google docs without requesting access. I already gone through this link https://developers.google.com/drive/api/v3/reference/files for "webView link". But I am not getting it how to use it in my code using PHP so that I can share my google docs without requesting access.

This is my code-

```<code><?php
require __DIR__ . '/vendor/autoload.php';

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Docs API PHP Quickstart');
    $client->setScopes([
                        "https://www.googleapis.com/auth/documents",
                        "https://www.googleapis.com/auth/drive.file",
                        "https://www.googleapis.com/auth/drive"
                        ]);
    // $client->setScopes(Google_Service_Drive::DRIVE);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory('token.json');

    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';

        $authCode = trim(fgets(STDIN));
        // print_f("code:",$authCode);

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        // printf("Credentials saved to %s\n", $credentialsPath);
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {

        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());

        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }

    return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path)
{
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Docs($client);

$title = 'Demo document';
$document = new Google_Service_Docs_Document(array(
    'title' => $title
));

$document = $service->documents->create($document);
printf("Created document with title: %s\n", $document->title);
$documentId = $document->getdocumentId();
printf("Document Id: %s\n", $documentId);

$longText = "The lorem ipsum is a placeholder text used in publishing and graphic design. This filler text is a short paragraph that contains all the letters of the alphabet.";
$requests = array();
$requests[] = new Google_Service_Docs_Request([
    'insertText' => [
        'text' => $longText,
        'location' => [
            'index' => 1,
        ],
    ],
]);

$requests [] = new Google_Service_Docs_Request([
    'insertTable' => [
        'rows' =>  2,
        'columns' =>  2,
        'endOfSegmentLocation' => [
          'segmentId' => ''
        ],
    ],
]);

$requests[] = new Google_Service_Docs_Request(array(
    'insertInlineImage' => array(
        'uri' => 'https://www.gstatic.com/images/branding/product/1x/docs_64dp.png',
        'location' => array(
            'index' => 1,
        ),
        'objectSize' => array(
            'height' => array(
                'magnitude' => 50,
                'unit' => 'PT',
            ),
            'width' => array(
                'magnitude' => 50,
                'unit' => 'PT',
            ),
        )
        ),
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

</code>```

I have also used the proper scopes and after changing the scopes i have also deleted the token.json file and again authenticated the user.

Then also I am unable to execute how to share a google docs with others using PHP so that they can see my docs without requesting access.

Through the above mentioned code I am able to create a doc file and insert text in it properly but now i want to share it with others.What else I have to do to achieve this. Please help me out with this query.

for help and documentation i was following this link https://developers.google.com/drive/api/v2/manage-sharing
and inserted my code at the same as--

```<code>$fileId = $documentId;
$service->getClient()->setUseBatch(true);
try {
    $batch = $service->createBatch();

    $userPermission = new Google_Service_Drive_Permission(array(
        'type' => 'user',
        'role' => 'writer',
        'value' => 'user@example.com'
    ));
    $request = $service->permissions->insert(
        $fileId, $userPermission, array('fields' => 'id'));
    $batch->add($request, 'user');
    $domainPermission = new Google_Service_Drive_Permission(array(
        'type' => 'domain',
        'role' => 'reader',
        'value' => 'example.com'
    ));
    $request = $service->permissions->insert(
        $fileId, $domainPermission, array('fields' => 'id'));
    $batch->add($request, 'domain');
    $results = $batch->execute();

    foreach ($results as $result) {
        if ($result instanceof Google_Service_Exception) {
            // Handle error
            printf($result);
        } else {
            printf("Permission ID: %s\n", $result->id);
        }
    }
} finally {
    $service->getClient()->setUseBatch(false);
}
</code>```

it's giving this error-

```<code>PHP Fatal error:  Uncaught Error: Call to undefined method Google\Service\Drive\Resource\Permissions::insert()
</code>```

答:
You need to use the Permissions: create method of the Google Drive API to create a new Permission with the parameters you require.

Make a Permissions: create request to the Drive API with the ID of the file you wish to set the permission on will set up the permission.

With the file ID you can make the request along with a request body which contains the permission type:

Example cURL Request:

```<code>curl --request POST \
  'https://www.googleapis.com/drive/v3/files/<YOUR-FILE-ID-GOES-HERE>/permissions?key=[YOUR_API_KEY]' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"role":"editor","type":"user","emailAddress":"user@example.com"}' \
  --compressed
</code>```

The data '{"role":"editor","type":"user","emailAddress":"user@example.com"}' line sets the permissions so that the user with email address user@example.com has edit permissions for the file. You can read more about the Permissions resource here

Body:
Is it possible to share a google docs link to others so that they can see and edit my google docs without requesting access. I already gone through this link https://developers.google.com/drive/api/v3/reference/files for "webView link". But I am not getting it how to use it in my code using PHP so that I can share my google docs without requesting access.

This is my code-

<?php
require __DIR__ . '/vendor/autoload.php';

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Docs API PHP Quickstart');
    $client->setScopes([
                        "https://www.googleapis.com/auth/documents",
                        "https://www.googleapis.com/auth/drive.file",
                        "https://www.googleapis.com/auth/drive"
                        ]);
    // $client->setScopes(Google_Service_Drive::DRIVE);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory('token.json');

    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';

        $authCode = trim(fgets(STDIN));
        // print_f("code:",$authCode);

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        // printf("Credentials saved to %s\n", $credentialsPath);
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {

        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());

        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }

    return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path)
{
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Docs($client);

$title = 'Demo document';
$document = new Google_Service_Docs_Document(array(
    'title' => $title
));

$document = $service->documents->create($document);
printf("Created document with title: %s\n", $document->title);
$documentId = $document->getdocumentId();
printf("Document Id: %s\n", $documentId);

$longText = "The lorem ipsum is a placeholder text used in publishing and graphic design. This filler text is a short paragraph that contains all the letters of the alphabet.";
$requests = array();
$requests[] = new Google_Service_Docs_Request([
    'insertText' => [
        'text' => $longText,
        'location' => [
            'index' => 1,
        ],
    ],
]);

$requests [] = new Google_Service_Docs_Request([
    'insertTable' => [
        'rows' =>  2,
        'columns' =>  2,
        'endOfSegmentLocation' => [
          'segmentId' => ''
        ],
    ],
]);

$requests[] = new Google_Service_Docs_Request(array(
    'insertInlineImage' => array(
        'uri' => 'https://www.gstatic.com/images/branding/product/1x/docs_64dp.png',
        'location' => array(
            'index' => 1,
        ),
        'objectSize' => array(
            'height' => array(
                'magnitude' => 50,
                'unit' => 'PT',
            ),
            'width' => array(
                'magnitude' => 50,
                'unit' => 'PT',
            ),
        )
        ),
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

I have also used the proper scopes and after changing the scopes i have also deleted the token.json file and again authenticated the user.

Then also I am unable to execute how to share a google docs with others using PHP so that they can see my docs without requesting access.

Through the above mentioned code I am able to create a doc file and insert text in it properly but now i want to share it with others.What else I have to do to achieve this. Please help me out with this query.

for help and documentation i was following this link https://developers.google.com/drive/api/v2/manage-sharing
and inserted my code at the same as--

$fileId = $documentId;
$service->getClient()->setUseBatch(true);
try {
    $batch = $service->createBatch();

    $userPermission = new Google_Service_Drive_Permission(array(
        'type' => 'user',
        'role' => 'writer',
        'value' => 'user@example.com'
    ));
    $request = $service->permissions->insert(
        $fileId, $userPermission, array('fields' => 'id'));
    $batch->add($request, 'user');
    $domainPermission = new Google_Service_Drive_Permission(array(
        'type' => 'domain',
        'role' => 'reader',
        'value' => 'example.com'
    ));
    $request = $service->permissions->insert(
        $fileId, $domainPermission, array('fields' => 'id'));
    $batch->add($request, 'domain');
    $results = $batch->execute();

    foreach ($results as $result) {
        if ($result instanceof Google_Service_Exception) {
            // Handle error
            printf($result);
        } else {
            printf("Permission ID: %s\n", $result->id);
        }
    }
} finally {
    $service->getClient()->setUseBatch(false);
}

it's giving this error-

PHP Fatal error:  Uncaught Error: Call to undefined method Google\Service\Drive\Resource\Permissions::insert()

Body:
You need to use the Permissions: create method of the Google Drive API to create a new Permission with the parameters you require.

Make a Permissions: create request to the Drive API with the ID of the file you wish to set the permission on will set up the permission.

With the file ID you can make the request along with a request body which contains the permission type:

Example cURL Request:

curl --request POST \
  'https://www.googleapis.com/drive/v3/files/<YOUR-FILE-ID-GOES-HERE>/permissions?key=[YOUR_API_KEY]' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"role":"editor","type":"user","emailAddress":"user@example.com"}' \
  --compressed

The data '{"role":"editor","type":"user","emailAddress":"user@example.com"}' line sets the permissions so that the user with email address user@example.com has edit permissions for the file. You can read more about the Permissions resource here


问:
Oracle Oracle hierarchical query to disable foreign keys
I have some code (see below), which uses a hierarchical query that traverses down a table to find all the related Foriegn keys. This seems to be working fine.

Can this be modified not to display the top level table, in this case the TABLE_NAME='PARENT' as I want to wrap this code in PL/SQL in order to create the desired syntax to enable/disable Foriegn keys for all the descendants of a table.

In my example, I have 3 tables. A grandchild table, which REFERENCES a child table and a child table, which REFERENCES the parent table, which is the master table.

The reason for this is to clean up some massive tables and I am trying to figure out the most effective and efficient way to go about this exercise.

We don't have CASCADE DELETE setup as that is too dangerous and some people learned that the hard way unfortunately.

Below is my test case and expected results, which I plan to execute in a procedure.

create table parent (
  id NUMBER(10),
  value      varchar2(30),
constraint parent_pk primary key (id)
);

CREATE TABLE child
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint child_pk primary key (id,value),
CONSTRAINT parent_child_fk
FOREIGN KEY (id)
REFERENCES parent(id));

CREATE TABLE grandchild
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint grandchild_pk primary key (id,value),
CONSTRAINT child_grandchild_fk
FOREIGN KEY (id,value)
REFERENCES child(id,value));

insert into parent values (1,'a');
insert into parent values (2,'b');
insert into parent values (3,'c');

insert into child  values (1,1);
insert into child  values (1,2);
insert into child  values (1,3);
insert into child  values (2,1);
insert into child  values (2,2);
insert into child  values (2,3);
insert into child  values (3,1);
insert into child  values (3,2);
insert into child  values (3,3);

insert into grandchild  values (1,1);
insert into grandchild  values (1,2);
insert into grandchild  values (1,3);
insert into grandchild  values (2,1);
insert into grandchild  values (2,2);
insert into grandchild  values (2,3);
insert into grandchild  values (3,1);
insert into grandchild  values (3,2);
insert into grandchild  values (3,3);
```
<p>In the query I hard code the column name ID.</p>
<p>If possible, I would like to figure it out else I can live with the hard coded value.</p>
<pre class="lang-sql prettyprint-override"><code>select distinct table_name, constraint_name, column_name, r_table_name, position, constraint_type
from (
    SELECT uc.table_name,
    uc.constraint_name,
    cols.column_name,
    (select table_name from user_constraints where constraint_name = uc.r_constraint_name)
        r_table_name,
    (select column_name from user_cons_columns where constraint_name = uc.r_constraint_name and position = cols.position)
        r_column_name,
    cols.position,
    uc.constraint_type
    FROM user_constraints uc
    inner join user_cons_columns cols on uc.constraint_name = cols.constraint_name
    where constraint_type != 'C'
)
start with table_name = 'PARENT' and column_name = 'ID'
connect by nocycle
prior table_name = r_table_name
and prior column_name = r_column_name;
</code>```

TABLE_NAME
CONSTRAINT_NAME
COLUMN_NAME
R_TABLE_NAME
POSITION
CONSTRAINT_TYPE

PARENT
PARENT_PK
ID
-
1
P

GRANDCHILD
CHILD_GRANDCHILD_FK
ID
CHILD
1
R

CHILD
PARENT_CHILD_FK
ID
PARENT
1
R

Expected results for my test CASE is to generate this syntax:

alter table CHILD disable constraint PARENT_CHILD_FK;
alter table GRANDCHILD disable constraint CHILD_GRANDCHILD_FK;
```

答:
It is not necessary to use hard code, in fact, it is more troublesome to display the top-level table

with tab1 as (
select t1.CONSTRAINT_NAME,
       t1.CONSTRAINT_TYPE,
       t1.TABLE_NAME,
       t1.R_CONSTRAINT_NAME,
       t2.CONSTRAINT_TYPE r_type,
       t2.TABLE_NAME r_name
  from user_constraints t1,
       user_constraints t2
 where t1.CONSTRAINT_TYPE = 'R'
   and t1.R_CONSTRAINT_NAME = t2.CONSTRAINT_NAME
)
, tab2 as(
select t1.*
  from tab1 t1
 start with not exists(
       select 1 from tab1 v1 where t1.r_name = v1.table_name
 )
 connect by prior t1.table_name = t1.r_name
)
select 'alter table ' || t1.table_name || ' disable constraint ' || t1.CONSTRAINT_NAME || ';'
  from tab2 t1
;

```

Body:
I have some code (see below), which uses a hierarchical query that traverses down a table to find all the related Foriegn keys. This seems to be working fine.

Can this be modified not to display the top level table, in this case the TABLE_NAME='PARENT' as I want to wrap this code in PL/SQL in order to create the desired syntax to enable/disable Foriegn keys for all the descendants of a table.

In my example, I have 3 tables. A grandchild table, which REFERENCES a child table and a child table, which REFERENCES the parent table, which is the master table.

The reason for this is to clean up some massive tables and I am trying to figure out the most effective and efficient way to go about this exercise.

We don't have CASCADE DELETE setup as that is too dangerous and some people learned that the hard way unfortunately.

Below is my test case and expected results, which I plan to execute in a procedure.

create table parent (
  id NUMBER(10),
  value      varchar2(30),
constraint parent_pk primary key (id)
);

CREATE TABLE child
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint child_pk primary key (id,value),
CONSTRAINT parent_child_fk
FOREIGN KEY (id)
REFERENCES parent(id));

CREATE TABLE grandchild
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint grandchild_pk primary key (id,value),
CONSTRAINT child_grandchild_fk
FOREIGN KEY (id,value)
REFERENCES child(id,value));

insert into parent values (1,'a');
insert into parent values (2,'b');
insert into parent values (3,'c');

insert into child  values (1,1);
insert into child  values (1,2);
insert into child  values (1,3);
insert into child  values (2,1);
insert into child  values (2,2);
insert into child  values (2,3);
insert into child  values (3,1);
insert into child  values (3,2);
insert into child  values (3,3);

insert into grandchild  values (1,1);
insert into grandchild  values (1,2);
insert into grandchild  values (1,3);
insert into grandchild  values (2,1);
insert into grandchild  values (2,2);
insert into grandchild  values (2,3);
insert into grandchild  values (3,1);
insert into grandchild  values (3,2);
insert into grandchild  values (3,3);

In the query I hard code the column name ID.

If possible, I would like to figure it out else I can live with the hard coded value.

select distinct table_name, constraint_name, column_name, r_table_name, position, constraint_type
from (
    SELECT uc.table_name,
    uc.constraint_name,
    cols.column_name,
    (select table_name from user_constraints where constraint_name = uc.r_constraint_name)
        r_table_name,
    (select column_name from user_cons_columns where constraint_name = uc.r_constraint_name and position = cols.position)
        r_column_name,
    cols.position,
    uc.constraint_type
    FROM user_constraints uc
    inner join user_cons_columns cols on uc.constraint_name = cols.constraint_name
    where constraint_type != 'C'
)
start with table_name = 'PARENT' and column_name = 'ID'
connect by nocycle
prior table_name = r_table_name
and prior column_name = r_column_name;

TABLE_NAME
CONSTRAINT_NAME
COLUMN_NAME
R_TABLE_NAME
POSITION
CONSTRAINT_TYPE

PARENT
PARENT_PK
ID
-
1
P

GRANDCHILD
CHILD_GRANDCHILD_FK
ID
CHILD
1
R

CHILD
PARENT_CHILD_FK
ID
PARENT
1
R

Expected results for my test CASE is to generate this syntax:

alter table CHILD disable constraint PARENT_CHILD_FK;
alter table GRANDCHILD disable constraint CHILD_GRANDCHILD_FK;


问:
Radio button and saving the state values in iphone
I need to create two radio buttons and I want to store there state values (enabled or disabled) in an array. can anybody share the code?</p>

答:
How about this

take a mutable dictionary in header file

```<code>NSMutableDicionary *dictionaryForRadioStates;
</code>```

and in implementation

ANd in implementation file on tap of radio button

```<code> [dictionaryForRadioStates setObject:[NSNumber numberWithBool:radioButton.enabled] forKey:@"radioButton1"];

[dictionaryForRadioStates setObject:[NSNumber numberWithBool:radioButton.enabled] forKey:@"radioButton2"];
</code>```

You can get values back like this

```<code>BOOL state = [[dictionaryForRadioStates valueForKey:@"radioButton1"] boolValue];
</code>```

Body:
How about this

take a mutable dictionary in header file

NSMutableDicionary *dictionaryForRadioStates;

and in implementation

ANd in implementation file on tap of radio button

 [dictionaryForRadioStates setObject:[NSNumber numberWithBool:radioButton.enabled] forKey:@"radioButton1"];

[dictionaryForRadioStates setObject:[NSNumber numberWithBool:radioButton.enabled] forKey:@"radioButton2"];

You can get values back like this

BOOL state = [[dictionaryForRadioStates valueForKey:@"radioButton1"] boolValue];


问:
DrRacket – Finding total number of vowels in list of characters
I am using DrRacket on the Beginner Language mode.

Code below:

```<code>(define vowels '(#\a #\e #\i #\o #\u))

(define total 0)

(define (any-in-list lst check)
  (cond
    [(empty? lst) (+ 0 total)]
    [(member? (first lst) check) (add1 total)]
    [else (any-in-list (rest lst) check)]))

(define (count-vowels string)
  (any-in-list (string->list string) vowels))

(count-vowels "how do i do this?")
</code>```

The total value stays stuck at 1. After debugging, I realized that the 2nd cond statement evaluates to #true and then stops. How can I keep it going for the rest of the list after updating the total value?

答:
You forgot to recurse when you found a match.

Also, since total is 0, (+ 0 total) is always 0, and (add1 total) is always 1.

Don't try to use global variables and mutation - recurse and use the recursive value.

```<code>(cond
    ; The empty list contains nothing, so the result is 0.
    [(empty? lst) 0]
    ; If the first element is a member, the result is
    ; one more than the count in the tail.
    [(member? (first lst) check) (add1 (any-in-list (rest lst) check))]
    ; Otherwise, the count is the same as in the tail.
    [else (any-in-list (rest lst) check)]))
</code>```

Body:
I am using DrRacket on the Beginner Language mode.

Code below:

(define vowels '(#\a #\e #\i #\o #\u))

(define total 0)

(define (any-in-list lst check)
  (cond
    [(empty? lst) (+ 0 total)]
    [(member? (first lst) check) (add1 total)]
    [else (any-in-list (rest lst) check)]))

(define (count-vowels string)
  (any-in-list (string->list string) vowels))

(count-vowels "how do i do this?")

The total value stays stuck at 1. After debugging, I realized that the 2nd cond statement evaluates to #true and then stops. How can I keep it going for the rest of the list after updating the total value?

Body:
You forgot to recurse when you found a match.

Also, since total is 0, (+ 0 total) is always 0, and (add1 total) is always 1.

Don't try to use global variables and mutation - recurse and use the recursive value.

(cond
    ; The empty list contains nothing, so the result is 0.
    [(empty? lst) 0]
    ; If the first element is a member, the result is
    ; one more than the count in the tail.
    [(member? (first lst) check) (add1 (any-in-list (rest lst) check))]
    ; Otherwise, the count is the same as in the tail.
    [else (any-in-list (rest lst) check)]))


问:
CDate Function is being reformatted and creates an Error
I have a select query which has a date stored as string e.g. 20211231 (Dec 31, 2021).  I am trying to use the CDate function to convert the string. If I enter the following in the SQL view

```<code>SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"####/##/##")) AS DteAdded
FROM XLCustOrdDtl;
</code>```

The result are as expected, however when I go back to Design view and run the query, Access reformats the string to

```<code>SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"#\/#\/#")) AS DteAdded
FROM XLCustOrdDtl;
</code>```

This results in #Error

Any thoughts on why this is happening and how I might correct the issue?

答:
As your date is text, let Format know this and use @.

Also be aware, that to Format a slash is not a slash but the local date separator. To force a literal slash, escape it with a backslash:

SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"@@@@\/@@\/@@")) AS DteAdded
FROM XLCustOrdDtl;
```

Body:
I have a select query which has a date stored as string e.g. 20211231 (Dec 31, 2021).  I am trying to use the CDate function to convert the string. If I enter the following in the SQL view

SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"####/##/##")) AS DteAdded
FROM XLCustOrdDtl;

The result are as expected, however when I go back to Design view and run the query, Access reformats the string to

SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"#\/#\/#")) AS DteAdded
FROM XLCustOrdDtl;

This results in #Error

Any thoughts on why this is happening and how I might correct the issue?


问:
(bitbucket-pipelines.)yml file has weird indentation?
Why is every section in this file indented by 2 except the step

```<code>  image: atlassian/default-image:2
  pipelines:
    default:
    - step:
        deployment: production
        script:
        - git submodule update --recursive --init
        - zip -r $FILENAME . -x bitbucket-pipelines.yml *.git*
        - pipe: atlassian/bitbucket-upload-file:0.1.6
          variables:
            BITBUCKET_USERNAME: $BITBUCKET_USERNAME
            BITBUCKET_APP_PASSWORD: $BITBUCKET_APP_PASSWORD
            FILENAME: $FILENAME
</code>```

And gives an error if changed to two?

https://bitbucket-pipelines.prod.public.atl-paas.net/validator

This topic seems to say because YAML does not consider - to be the first character? But after pipe is the same sequence with only two?

https://community.atlassian.com/t5/Bitbucket-questions/Is-it-intentional-that-bitbucket-pipelinese-yml-indentation/qaq-p/582084

答:
You will usually see two things in YAML

Sequences — in other programming languages, this is commonly referred as arrays, lists, ...:

- apple
- banana
- pear
```
</li>
<li>Mappings — in other programming languages, this is commonly referred as objects, hashes, dictionaries, associative arrays, ...:
<pre class="lang-yaml prettyprint-override"><code>question: how do I foobar?
body: Can you help?
tag: yaml
</code>```

So if you want to store a mapping of mapping you would do:

pier1:
  boat: yes
  in_activity: yes
  comments: needs some painting in 2023
## The mapping above this comment refers to the pier1,
## as it is indented one level below the key `pier1`

pier2:
  boat: no
  in_activity: no
  comments: currently inactive, needs urgent repair
## The mapping above this comment refers to the pier2,
## as it is indented one level below the key `pier2`
```
<p>While, if you store a list in a mapping, you could go without the indent, indeed:</p>
<pre class="lang-yaml prettyprint-override"><code>fruits:
- apple
- banana
- pear
</code>```

Is strictly equal to

fruits:
  - apple
  - banana
  - pear
```
<hr />
<p>But, if you are trying to indent the first step of your pipeline only, like so:</p>
<pre class="lang-yaml prettyprint-override"><code>pipelines:
  default:
    - step:
      deployment: production
</code>```

You end up with an valid YAML, but, a YAML that does not have the same meaning anymore.

When your original yaml means: I do have a default pipeline with a list of actions, the first action being a step that consists of a deployment to production.

The resulting incorrectly indented YAML means: I do have a default pipeline with a list of actions, the first action having two properties, the first property being an empty step, and the second property is that it is a deployment to production.

So, here, really, the deplyement key that was a property of the step mapping became a property of the first element of the list default!

To indent all this as you would like, you will have to go:

pipelines:
  default:
    - step:
        deployment: production
##      ^-- This property is now further indented too
```
<p>So, you end up with the YAML:</p>
<pre class="lang-yaml prettyprint-override"><code>image: atlassian/default-image:2
pipelines:
  default:
    - step:
        deployment: production
        script:
          - git submodule update --recursive --init
          - zip -r $FILENAME . -x bitbucket-pipelines.yml *.git*
          - pipe: atlassian/bitbucket-upload-file:0.1.6
            variables:
              BITBUCKET_USERNAME: $BITBUCKET_USERNAME
              BITBUCKET_APP_PASSWORD: $BITBUCKET_APP_PASSWORD
              FILENAME: $FILENAME
</code>```

Body:
Why is every section in this file indented by 2 except the step

  image: atlassian/default-image:2
  pipelines:
    default:
    - step:
        deployment: production
        script:
        - git submodule update --recursive --init
        - zip -r $FILENAME . -x bitbucket-pipelines.yml *.git*
        - pipe: atlassian/bitbucket-upload-file:0.1.6
          variables:
            BITBUCKET_USERNAME: $BITBUCKET_USERNAME
            BITBUCKET_APP_PASSWORD: $BITBUCKET_APP_PASSWORD
            FILENAME: $FILENAME

And gives an error if changed to two?

https://bitbucket-pipelines.prod.public.atl-paas.net/validator

This topic seems to say because YAML does not consider - to be the first character? But after pipe is the same sequence with only two?

https://community.atlassian.com/t5/Bitbucket-questions/Is-it-intentional-that-bitbucket-pipelinese-yml-indentation/qaq-p/582084

Body:
You will usually see two things in YAML

Sequences — in other programming languages, this is commonly referred as arrays, lists, ...:

- apple
- banana
- pear

Mappings — in other programming languages, this is commonly referred as objects, hashes, dictionaries, associative arrays, ...:

question: how do I foobar?
body: Can you help?
tag: yaml

So if you want to store a mapping of mapping you would do:

pier1:
  boat: yes
  in_activity: yes
  comments: needs some painting in 2023
## The mapping above this comment refers to the pier1,
## as it is indented one level below the key `pier1`

pier2:
  boat: no
  in_activity: no
  comments: currently inactive, needs urgent repair
## The mapping above this comment refers to the pier2,
## as it is indented one level below the key `pier2`

While, if you store a list in a mapping, you could go without the indent, indeed:

fruits:
- apple
- banana
- pear

Is strictly equal to

fruits:
  - apple
  - banana
  - pear

But, if you are trying to indent the first step of your pipeline only, like so:

pipelines:
  default:
    - step:
      deployment: production

You end up with an valid YAML, but, a YAML that does not have the same meaning anymore.

When your original yaml means: I do have a default pipeline with a list of actions, the first action being a step that consists of a deployment to production.

The resulting incorrectly indented YAML means: I do have a default pipeline with a list of actions, the first action having two properties, the first property being an empty step, and the second property is that it is a deployment to production.

So, here, really, the deplyement key that was a property of the step mapping became a property of the first element of the list default!

To indent all this as you would like, you will have to go:

pipelines:
  default:
    - step:
        deployment: production
##      ^-- This property is now further indented too

So, you end up with the YAML:

image: atlassian/default-image:2
pipelines:
  default:
    - step:
        deployment: production
        script:
          - git submodule update --recursive --init
          - zip -r $FILENAME . -x bitbucket-pipelines.yml *.git*
          - pipe: atlassian/bitbucket-upload-file:0.1.6
            variables:
              BITBUCKET_USERNAME: $BITBUCKET_USERNAME
              BITBUCKET_APP_PASSWORD: $BITBUCKET_APP_PASSWORD
              FILENAME: $FILENAME


问:
Why Bootstrap 5 navbar does not collapsing?
I try to compile Bootstrap 5 with sass but I think I miss importing some scss files. If I added <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> navbar collapsing fine, but when I added my compailed css file navbar not collapsing.

Here is my navbar codes

      Workshop

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
      aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

```
<p>Here is my main.scss codes</p>
<pre class="lang-css prettyprint-override"><code>// PATHS ARE TRUE
// 1. Include functions first (so you can manipulate colors, SVGs, calc, etc)
@import "../../node_modules/bootstrap/scss/functions";

// 2. Include any default variable overrides here

// 3. Include remainder of required Bootstrap stylesheets
@import "../../node_modules/bootstrap/scss/variables";
@import "../../node_modules/bootstrap/scss/mixins";
@import "../../node_modules/bootstrap/scss/root";

// 4. Include any optional Bootstrap CSS as needed
// I GUEST MISSING IN HERE
@import "../../node_modules/bootstrap/scss/utilities";
@import "../../node_modules/bootstrap/scss/reboot";
@import "../../node_modules/bootstrap/scss/type";
@import "../../node_modules/bootstrap/scss/containers";
@import "../../node_modules/bootstrap/scss/grid";
@import "../../node_modules/bootstrap/scss/helpers";
@import "../../node_modules/bootstrap/scss/nav";
@import "../../node_modules/bootstrap/scss/navbar";
@import "../../node_modules/bootstrap/scss/buttons";
@import "../../node_modules/bootstrap/scss/tables";
@import "../../node_modules/bootstrap/scss/images";
@import "../../node_modules/bootstrap/scss/card";

// 5. Optionally include utilities API last to generate classes based on the Sass map in `_utilities.scss`
@import "../../node_modules/bootstrap/scss/utilities/api";

// 6. Add additional custom code here
</code>```

And here is my index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="{{site.baseurl}}/assets/css/main.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
  <title>{{site.title}}</title>
  <link rel="icon" type="image/x-icon" href="{{site.baseurl}}/assets/images/favicon.ico">

  {{content}}

```

Why my navbar does not collapsing? Which scss files i have to import? I have read the documents but I missing something. Could not fix. Please help.

Thank you

答: Give a id for the navbar and change a style by giving it manually, it worked for me</p>

Body:
I try to compile Bootstrap 5 with sass but I think I miss importing some scss files. If I added <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> navbar collapsing fine, but when I added my compailed css file navbar not collapsing.

Here is my navbar codes

      Workshop

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
      aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

Here is my main.scss codes

// PATHS ARE TRUE
// 1. Include functions first (so you can manipulate colors, SVGs, calc, etc)
@import "../../node_modules/bootstrap/scss/functions";

// 2. Include any default variable overrides here

// 3. Include remainder of required Bootstrap stylesheets
@import "../../node_modules/bootstrap/scss/variables";
@import "../../node_modules/bootstrap/scss/mixins";
@import "../../node_modules/bootstrap/scss/root";

// 4. Include any optional Bootstrap CSS as needed
// I GUEST MISSING IN HERE
@import "../../node_modules/bootstrap/scss/utilities";
@import "../../node_modules/bootstrap/scss/reboot";
@import "../../node_modules/bootstrap/scss/type";
@import "../../node_modules/bootstrap/scss/containers";
@import "../../node_modules/bootstrap/scss/grid";
@import "../../node_modules/bootstrap/scss/helpers";
@import "../../node_modules/bootstrap/scss/nav";
@import "../../node_modules/bootstrap/scss/navbar";
@import "../../node_modules/bootstrap/scss/buttons";
@import "../../node_modules/bootstrap/scss/tables";
@import "../../node_modules/bootstrap/scss/images";
@import "../../node_modules/bootstrap/scss/card";

// 5. Optionally include utilities API last to generate classes based on the Sass map in `_utilities.scss`
@import "../../node_modules/bootstrap/scss/utilities/api";

// 6. Add additional custom code here

And here is my index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="{{site.baseurl}}/assets/css/main.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
  <title>{{site.title}}</title>
  <link rel="icon" type="image/x-icon" href="{{site.baseurl}}/assets/images/favicon.ico">

  {{content}}

Why my navbar does not collapsing? Which scss files i have to import? I have read the documents but I missing something. Could not fix. Please help.

Thank you


问:
Pass value using pipe symbol to a powershell Start-Process command, from cmd window
I have a batch script like below. I want to call this script from a terminal window (cmd), by running it using powershell Start-Process command (Doing this in Azure ARM Template).
I want to pass the INPUT value while calling the script, probably by using a pipe symbol.

Not able to pass the INPUT value through pipe symbol to a Start-Process command.
Am I missing something?
How can I achieve this (without any modifications to this batch file)?

```<code>@echo off
SETLOCAL EnableDelayedExpansion

set INPUT=
set /P INPUT=Type yes or no: %=%

echo[
echo actually typed %INPUT%

IF "%INPUT%"=="n" goto :CLICKEDNO
IF "%INPUT%"=="N" goto :CLICKEDNO
IF "%INPUT%"=="NO" goto :CLICKEDNO
IF "%INPUT%"=="no" goto :CLICKEDNO
IF "%INPUT%"=="No" goto :CLICKEDNO
IF "%INPUT%"=="yes" goto :CLICKEDYES
IF "%INPUT%"=="Yes" goto :CLICKEDYES
IF "%INPUT%"=="Y" goto :CLICKEDYES
IF "%INPUT%"=="y" goto :CLICKEDYES

:CLICKEDYES
echo Typed yes
goto :eof

:CLICKEDNO
echo Typed no
goto :eof

echo end of file
</code>```

Even though I am trying to pass the value "no", it is printing "yes".

Below are some of the commands that I have tried.

echo no | powershell Set-Location -Path C:\CAP\CAP-Installer ; Start-Process -NoNewWindow  .\test.bat

echo no | powershell Start-Process -NoNewWindow -FilePath C:\CAP\CAP-Installer\test.bat

Output for the comands 1 and 2:

```<code>Type yes or no:
actually typed no
Typed yes
</code>```

powershell -Command "echo no | Start-Process -NoNewWindow -FilePath C:\CAP\CAP-Installer\test.bat"

echo no | powershell -Command "$input | Start-Process -NoNewWindow -FilePath C:\CAP\CAP-Installer\test.bat"

Output for the comands 3 and 4:

```<code>Type yes or no: Start-Process : The input object cannot be bound to any parameters for the command
either because the command does not take pipeline input or the input and its
properties do not match any of the parameters that take pipeline input.
At line:1 char:11
+ echo no | Start-Process -NoNewWindow -FilePath C:\CAP ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (no:PSObject) [Start-Process], Paramet
   erBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.Start
   ProcessCommand

C:\Users\CAP-VM>

actually typed
Typed yes

C:\Users\CAP-VM>
</code>```

Any help is appreciated. Thanks is advance.

答:
You do not need to do a match for each case. use if /i to match case insensitive, we also need to use %1 to specify :

```<code>@echo off

echo Type Yes/no & set /P "in=%1"

if /i "%in%" == "n" goto :no
if /i "%in%" == "no" goto :no
if /i "%in%" == "y" goto :yes
if /i "%in%" == "yes" goto :yes

:yes
echo Typed yes
goto :eof

:no
echo Typed no
goto :eof
</code>```

obviously it is not even needed to set anything, so this is a better option:

```<code>@echo off

if /i "%~1" == "n" goto :no
if /i "%~1" == "no" goto :no
if /i "%~1" == "y" goto :yes
if /i "%~1" == "yes" goto :yes

:yes
echo Typed yes
goto :eof

:no
echo Typed no
goto :eof
</code>```

and Even better, use choice to make choices instead of using if

```<code>@echo off
choice /c yn /m "yes/no"
if not "%errorlevel%" equ "0" goto _opt%errorlevel%
exit /b 0
:_opt1
echo You chose Yes
goto :EOF

:_opt2
echo You chose No
goto :EOF
</code>```

You can simply run it directly from cmd and not via cmd to call powershell to run a batch-file which runs in cmd. Much simpler:

```<code>echo yes|"C:\CAP\CAP-Installer\test.bat"
</code>```

If you really need to use it via powershell send it as a paramater:

```<code>powershell Start-Process -NoNewWindow -FilePath C:\CAP\CAP-Installer\test.bat yes
</code>```

Body:
I have a batch script like below. I want to call this script from a terminal window (cmd), by running it using powershell Start-Process command (Doing this in Azure ARM Template).
I want to pass the INPUT value while calling the script, probably by using a pipe symbol.

Not able to pass the INPUT value through pipe symbol to a Start-Process command.
Am I missing something?
How can I achieve this (without any modifications to this batch file)?

@echo off
SETLOCAL EnableDelayedExpansion

set INPUT=
set /P INPUT=Type yes or no: %=%

echo[
echo actually typed %INPUT%

IF "%INPUT%"=="n" goto :CLICKEDNO
IF "%INPUT%"=="N" goto :CLICKEDNO
IF "%INPUT%"=="NO" goto :CLICKEDNO
IF "%INPUT%"=="no" goto :CLICKEDNO
IF "%INPUT%"=="No" goto :CLICKEDNO
IF "%INPUT%"=="yes" goto :CLICKEDYES
IF "%INPUT%"=="Yes" goto :CLICKEDYES
IF "%INPUT%"=="Y" goto :CLICKEDYES
IF "%INPUT%"=="y" goto :CLICKEDYES

:CLICKEDYES
echo Typed yes
goto :eof

:CLICKEDNO
echo Typed no
goto :eof

echo end of file

Even though I am trying to pass the value "no", it is printing "yes".

Below are some of the commands that I have tried.

echo no | powershell Set-Location -Path C:\CAP\CAP-Installer ; Start-Process -NoNewWindow  .\test.bat

echo no | powershell Start-Process -NoNewWindow -FilePath C:\CAP\CAP-Installer\test.bat

Output for the comands 1 and 2:

Type yes or no:
actually typed no
Typed yes

powershell -Command "echo no | Start-Process -NoNewWindow -FilePath C:\CAP\CAP-Installer\test.bat"

echo no | powershell -Command "$input | Start-Process -NoNewWindow -FilePath C:\CAP\CAP-Installer\test.bat"

Output for the comands 3 and 4:

Type yes or no: Start-Process : The input object cannot be bound to any parameters for the command
either because the command does not take pipeline input or the input and its
properties do not match any of the parameters that take pipeline input.
At line:1 char:11
+ echo no | Start-Process -NoNewWindow -FilePath C:\CAP ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (no:PSObject) [Start-Process], Paramet
   erBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.Start
   ProcessCommand

C:\Users\CAP-VM>

actually typed
Typed yes

C:\Users\CAP-VM>

Any help is appreciated. Thanks is advance.

Body:
You do not need to do a match for each case. use if /i to match case insensitive, we also need to use %1 to specify :

@echo off

echo Type Yes/no & set /P "in=%1"

if /i "%in%" == "n" goto :no
if /i "%in%" == "no" goto :no
if /i "%in%" == "y" goto :yes
if /i "%in%" == "yes" goto :yes

:yes
echo Typed yes
goto :eof

:no
echo Typed no
goto :eof

obviously it is not even needed to set anything, so this is a better option:

@echo off

if /i "%~1" == "n" goto :no
if /i "%~1" == "no" goto :no
if /i "%~1" == "y" goto :yes
if /i "%~1" == "yes" goto :yes

:yes
echo Typed yes
goto :eof

:no
echo Typed no
goto :eof

and Even better, use choice to make choices instead of using if

@echo off
choice /c yn /m "yes/no"
if not "%errorlevel%" equ "0" goto _opt%errorlevel%
exit /b 0
:_opt1
echo You chose Yes
goto :EOF

:_opt2
echo You chose No
goto :EOF

You can simply run it directly from cmd and not via cmd to call powershell to run a batch-file which runs in cmd. Much simpler:

echo yes|"C:\CAP\CAP-Installer\test.bat"

If you really need to use it via powershell send it as a paramater:

powershell Start-Process -NoNewWindow -FilePath C:\CAP\CAP-Installer\test.bat yes


问:
Java Spring - write to existing file in resource folder
I have a simple in-memory db in which I load users from XML file at app startup.
Now whenever someone registers I want to save that new user in this xml file.
My approach is to everytime get all the users, append new one and save to xml.
However, seems like nothing is written in file at time the new user registers.
I am aware that this approach is not save but this is for educational reason only.

This is my save to xml class

```<code>public class SaveXml {
    @Autowired
    private UserRepository userRepository;

    public void saveUserToXml (User newUser) {
        try {
            ClassLoader classLoader = getClass().getClassLoader();
            File file = new File(classLoader.getResource("Users.xml").getFile());
            FileWriter fileWriter = new FileWriter(file);

            List<User> usersList = new ArrayList<>();
            //populate arraylist with all users;
            userRepository.findAll().forEach(usersList::add);
            usersList.add(newUser);

            XmlMapper xmlMapper = new XmlMapper();
            String xmlContent = xmlMapper.writeValueAsString(usersList);
            fileWriter.close();
        }
        catch (Exception e){}
    }
}
</code>```

Xml file that is placed in resource folder:

```<code><?xml version="1.0" encoding="UTF-8"?>
<users>
    <user>
        <username>Tom</username>
        <password>123</password>
    </user>
    <user>
        <username>Moc</username>
        <password>1234</password>
    </user>
</users>
</code>```

Users class

```<code>@JacksonXmlRootElement(localName = "users")
@Data
@NoArgsConstructor
public class Users {
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<User> user;

    public Users(List<User> newUser) {
        this.user = newUser;
    }

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }
}
</code>```

User class

```<code>@Data
public class User
{
    @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
    //defining id as column name
    @Column
    private int id;
    //defining name as column name
    @Column
    private String username;
    //defining password column
    @Column
    private String password;
}
</code>```

答:
You could use FileUtils from Apache.

```<code>    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
    </dependency>
</code>```

https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

```<code>  FileUtils.writeStringToFile(
                    file,
                    xmlContent,
                    StandardCharsets.UTF_8,
                    true // == append to end of file
            );
</code>```

The JavaDoc of this method:

```<code>         /**
         * Writes a String to a file creating the file if it does not exist.
         *
         * @param file     the file to write
         * @param data     the content to write to the file
         * @param charset the charset to use, {@code null} means platform default
         * @param append   if {@code true}, then the String will be added to the
         *                 end of the file rather than overwriting
         * @throws IOException in case of an I/O error
         * @since 2.3
         */
</code>```

Body:
I have a simple in-memory db in which I load users from XML file at app startup.
Now whenever someone registers I want to save that new user in this xml file.
My approach is to everytime get all the users, append new one and save to xml.
However, seems like nothing is written in file at time the new user registers.
I am aware that this approach is not save but this is for educational reason only.

This is my save to xml class

public class SaveXml {
    @Autowired
    private UserRepository userRepository;

    public void saveUserToXml (User newUser) {
        try {
            ClassLoader classLoader = getClass().getClassLoader();
            File file = new File(classLoader.getResource("Users.xml").getFile());
            FileWriter fileWriter = new FileWriter(file);

            List<User> usersList = new ArrayList<>();
            //populate arraylist with all users;
            userRepository.findAll().forEach(usersList::add);
            usersList.add(newUser);

            XmlMapper xmlMapper = new XmlMapper();
            String xmlContent = xmlMapper.writeValueAsString(usersList);
            fileWriter.close();
        }
        catch (Exception e){}
    }
}

Xml file that is placed in resource folder:

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user>
        <username>Tom</username>
        <password>123</password>
    </user>
    <user>
        <username>Moc</username>
        <password>1234</password>
    </user>
</users>

Users class

@JacksonXmlRootElement(localName = "users")
@Data
@NoArgsConstructor
public class Users {
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<User> user;

    public Users(List<User> newUser) {
        this.user = newUser;
    }

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }
}

User class

@Data
public class User
{
    @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
    //defining id as column name
    @Column
    private int id;
    //defining name as column name
    @Column
    private String username;
    //defining password column
    @Column
    private String password;
}

Body:
You could use FileUtils from Apache.

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
    </dependency>

https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

  FileUtils.writeStringToFile(
                    file,
                    xmlContent,
                    StandardCharsets.UTF_8,
                    true // == append to end of file
            );

The JavaDoc of this method:

         /**
         * Writes a String to a file creating the file if it does not exist.
         *
         * @param file     the file to write
         * @param data     the content to write to the file
         * @param charset the charset to use, {@code null} means platform default
         * @param append   if {@code true}, then the String will be added to the
         *                 end of the file rather than overwriting
         * @throws IOException in case of an I/O error
         * @since 2.3
         */


问:
Vuetify grid of cards aligned with a divider
I'm trying to make a grid of cards that hold an image and a title using Vuetify.

I have managed to make a grid with the help of a few examples and managed to make this (This is on breakpoint XL):

But the problem is that, if the screen goes smaller, the grid isn't much of a grid anymore, but rather looks like this (this is on breakpoint LG):

I'm using justification: space-between but if I use start this is the result:

My goal is to have a grid aligned with the v-divider above and also is justified in the start without the awkward gap in the second row in the LG breakpoint.

Here's my code:

<v-container>
    <v-row justify="space-between">
      <v-col md="6" cols="12">

Grid

      </v-col>

      <v-col md="6" cols="12">
        <v-text-field
          outlined
          dense
          hide-details
          :placeholder="$t('search')"
          prepend-inner-icon="mdi-magnify"
          :class="$vuetify.breakpoint.smAndUp ? 'mt-2' : ''"
        ></v-text-field>
      </v-col>
    </v-row>

    <v-row justify="space-between">
      <v-col cols="12">
        <v-divider></v-divider>
      </v-col>
    </v-row>

    <v-row :justify="$vuetify.breakpoint.smAndDown ? 'center' : 'start'">
        <v-col cols="auto" v-for="(item, index) in machines" :key="index">
          <v-hover v-slot="{ hover }">
            <v-card class="mb-4" :elevation="hover ? 5 : 2">
              <v-card-text>
                <v-img
                src="https://static.wikia.nocookie.net/bc87eadb-62dd-4748-bcb6-cc4f38594988"
                contain
                :width="$vuetify.breakpoint.lgAndUp ? '300' : '385'"
                height="250"
              ></v-img>
              </v-card-text>

              <v-card-actions>
                <v-btn text color="deep-orange">
                  Arthur Morgan
                </v-btn>
              </v-card-actions>
            </v-card>
          </v-hover>
        </v-col>
    </v-row>
  </v-container>
```

答:
I guess, the correct answer is: you should not use flexboxes from v-col and v-row classes for these purposes.

In this question you can find a wide variety of answers. But most of them looks like crutches or lead to unexpected effects.

But you may use CSS Grid Layouts to fix your problem.

So change your row code to:

<v-row :justify="$vuetify.breakpoint.smAndDown ? 'center' : 'space-between'" :class="getClassByScreenSize()">
  ...
</v-row>
```
<p>Then create some CSS classes using grid layouts (fr unit explanation is here):</p>
```.two-cols {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.three-cols {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.five-cols {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
}
```
<p>And then create <code>getClassByScreenSize</code> method to put classes to your template based on current vuetify breakpoint:</p>
<pre class="lang-js prettyprint-override"><code>...
methods: {
  getClassByScreenSize() {
    if (this.$vuetify.breakpoint.xlOnly) {
      return 'five-cols'
    }
    if (this.$vuetify.breakpoint.lgOnly) {
      return 'three-cols'
    }
    if (this.$vuetify.mdOnly) {
      return 'two-cols'
    }
    return ''
  }
}
</code>```

Check this at CodePen.

Body:
I guess, the correct answer is: you should not use flexboxes from v-col and v-row classes for these purposes.

In this question you can find a wide variety of answers. But most of them looks like crutches or lead to unexpected effects.

But you may use CSS Grid Layouts to fix your problem.

So change your row code to:

<v-row :justify="$vuetify.breakpoint.smAndDown ? 'center' : 'space-between'" :class="getClassByScreenSize()">
  ...
</v-row>

Then create some CSS classes using grid layouts (fr unit explanation is here):

.two-cols {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.three-cols {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.five-cols {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
}

And then create getClassByScreenSize method to put classes to your template based on current vuetify breakpoint:

...
methods: {
  getClassByScreenSize() {
    if (this.$vuetify.breakpoint.xlOnly) {
      return 'five-cols'
    }
    if (this.$vuetify.breakpoint.lgOnly) {
      return 'three-cols'
    }
    if (this.$vuetify.mdOnly) {
      return 'two-cols'
    }
    return ''
  }
}

Check this at CodePen.


问:
annotation mapping bidirectional OneToMany/ManyToOne not fetching?
I'm clearly struggling to understand this so help greatly appreciated...

I have the following mapping:

```<code>@Entity
@Table(name = "parent")
public class ParentEntity
{
...
    @Id
    @Column(name = "parent_id")
    private Long id;
...
    @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER)
    private List<ChildEntity> children;
...
}

@Entity
@Table(name = "child")
public class ChildEntity
{
...
    @Id
    @Column(name = "child_id")
    private Long id;
...
    @ManyToOne(fetch = FetchType.EAGER)
    @NotFound(action = NotFoundAction.IGNORE)
    @JoinColumn(name = "parent_id")
    private ParentEntity parent;
...
}
</code>```

in my db i have:

```<code>parent
------
parent_id: 1

child
------
child_id: 1, parent_id: 1
</code>```

However

```<code>((Parent) session.get(Parent.class, 1)).getChildren()
</code>```

returns null.

can anyone see what I have missing?

thanks, p.

EDIT

It seems to be more-so to do with session state in that the collection is not populated in the context of the same session, but the collection is populated in the next session...

consider the following:

```<code>void setupRender()
{
    debug("existing not just added", (ParentEntity) session.get(ParentEntity.class, 13L));

    ParentEntity parent = new ParentEntity();
    session.save(parent);

    ChildEntity child = new ChildEntity();
    child.setParent(parent);
    session.save(child);

    debug("new one before commit", parent);

    sessionManager.commit();

    debug("new one after commit", parent);

    debug("new one after re-fetch", (ParentEntity) session.load(ParentEntity.class, parent.getId()));
}

private void debug(String prefix, ParentEntity parent)
{
    log.debug(prefix + ": parent id: " + parent.getId() + ", Children is "
            + (parent.getChildren() == null ? "null" : "size:" + parent.getChildren().size()));
}
</code>```

results in the following output:

```<code>DEBUG - existing not just added: parent id: 13, Children is size:1
DEBUG - new one before commit: parent id: 23, Children is null
DEBUG - new one after commit: parent id: 23, Children is null
DEBUG - new one after re-fetch: parent id: 23, Children is null
</code>```

so if it's due to session state, and commit isn't enough to trigger a re-fetch, what do I have to do to get the mapping to fetch the collection?

thanks again!

答:
The solution I use at the moment is to initialize the collection manually during construction:

```<code>private List<ChildEntity> children
    = new ArrayList<ChildEntity>;
</code>```

I'm not sure if that is a good practice, but it works and is simple.

Body:
I'm clearly struggling to understand this so help greatly appreciated...

I have the following mapping:

@Entity
@Table(name = "parent")
public class ParentEntity
{
...
    @Id
    @Column(name = "parent_id")
    private Long id;
...
    @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER)
    private List<ChildEntity> children;
...
}

@Entity
@Table(name = "child")
public class ChildEntity
{
...
    @Id
    @Column(name = "child_id")
    private Long id;
...
    @ManyToOne(fetch = FetchType.EAGER)
    @NotFound(action = NotFoundAction.IGNORE)
    @JoinColumn(name = "parent_id")
    private ParentEntity parent;
...
}

in my db i have:

parent
------
parent_id: 1

child
------
child_id: 1, parent_id: 1

However

((Parent) session.get(Parent.class, 1)).getChildren()

returns null.

can anyone see what I have missing?

thanks, p.

EDIT

It seems to be more-so to do with session state in that the collection is not populated in the context of the same session, but the collection is populated in the next session...

consider the following:

void setupRender()
{
    debug("existing not just added", (ParentEntity) session.get(ParentEntity.class, 13L));

    ParentEntity parent = new ParentEntity();
    session.save(parent);

    ChildEntity child = new ChildEntity();
    child.setParent(parent);
    session.save(child);

    debug("new one before commit", parent);

    sessionManager.commit();

    debug("new one after commit", parent);

    debug("new one after re-fetch", (ParentEntity) session.load(ParentEntity.class, parent.getId()));
}

private void debug(String prefix, ParentEntity parent)
{
    log.debug(prefix + ": parent id: " + parent.getId() + ", Children is "
            + (parent.getChildren() == null ? "null" : "size:" + parent.getChildren().size()));
}

results in the following output:

DEBUG - existing not just added: parent id: 13, Children is size:1
DEBUG - new one before commit: parent id: 23, Children is null
DEBUG - new one after commit: parent id: 23, Children is null
DEBUG - new one after re-fetch: parent id: 23, Children is null

so if it's due to session state, and commit isn't enough to trigger a re-fetch, what do I have to do to get the mapping to fetch the collection?

thanks again!

Body:
The solution I use at the moment is to initialize the collection manually during construction:

private List<ChildEntity> children
    = new ArrayList<ChildEntity>;

I'm not sure if that is a good practice, but it works and is simple.