问:
How to prevent Kotlin from caching the state of ImageView inside an included XML layout by several fragments/activities
I have an XML layout named layout_image like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/grumpy_cat"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

I include the XML in several activites/fragments

```<code><include
    android:id="@+id/llytImage"
    layout="@layout/layout_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</code>```

I set a color filter on imageViewin Actitivty A by accessing it with kotlinx synthetic:

```<code>import kotlinx.android.synthetic.main.layout_image.view.*

llytImage.imageView.setColorFilter(Color.RED)
</code>```

It becomes red and I navigate to Activity B. Activity B also includes the same XML layout with the same id. However, imageView is still red in Activity B.

It seems Kotlin caches the state of imageView and use the same view aiming better performance.

However, I don't want it to cache imageView. I need the default state. I tried 2 ways to prevent Kotlin from caching it:

Using @ContainerOptions(CacheImplementation.NO_CACHE) annotation in activities which include the XML

Calling imageView.clearFindViewByIdCache() when navigating to Activity B

None of them worked for me.

If you know the true solution, I will be very appreciated.
Thanks

答:
Manipulating the drawable rather than the image view by calling mutate() worked for me:

```<code>import kotlinx.android.synthetic.main.layout_image.view.*

val drawable = llytImage.imageView.drawable.mutate()
val colorFilter = PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SRC_IN)
drawable.colorFilter = colorFilter
</code>```

Body:
I have an XML layout named layout_image like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/grumpy_cat"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

I include the XML in several activites/fragments

<include
    android:id="@+id/llytImage"
    layout="@layout/layout_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

I set a color filter on imageViewin Actitivty A by accessing it with kotlinx synthetic:

import kotlinx.android.synthetic.main.layout_image.view.*

llytImage.imageView.setColorFilter(Color.RED)

It becomes red and I navigate to Activity B. Activity B also includes the same XML layout with the same id. However, imageView is still red in Activity B.

It seems Kotlin caches the state of imageView and use the same view aiming better performance.

However, I don't want it to cache imageView. I need the default state. I tried 2 ways to prevent Kotlin from caching it:

Using @ContainerOptions(CacheImplementation.NO_CACHE) annotation in activities which include the XML

Calling imageView.clearFindViewByIdCache() when navigating to Activity B

None of them worked for me.

If you know the true solution, I will be very appreciated.
Thanks

Body:
Manipulating the drawable rather than the image view by calling mutate() worked for me:

import kotlinx.android.synthetic.main.layout_image.view.*

val drawable = llytImage.imageView.drawable.mutate()
val colorFilter = PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SRC_IN)
drawable.colorFilter = colorFilter


来源: stackexchange

问:
IOS UI Testing: how to dismiss a series of system alerts( microphone access ) via code using fastlane snapshot
I use mac mojave 10.14.3 and react-native version - 0.59.1, fastlane latest version. I tried to run the fastlane screenshot via ios xcuitest But I couldn't dismiss the system alert. I have attached my code and alert screen

Could you please help me

```<code>addUIInterruptionMonitor(withDescription: "System Dialog") {
        (alert) -> Bool in
        let okButton = alert.buttons["OK"]
        if okButton.exists {
          okButton.tap()
        }

        let allowButton = alert.buttons["Allow"]
        if allowButton.exists {
          allowButton.tap()
        }

        return true
      }

      app.tap()
      snapshot("04EndRecord")
</code>```

this is my alert and app. this alert shows outside of the app, then how can i handle that?

答:
I faced this issue a few months ago. It appeared when I wanted to use sounds in the app. I disabled sounds during running UI tests.

Can you apply the same process to your app ?

ContentLicense: CC BY-SA 4.0

Body:
I use mac mojave 10.14.3 and react-native version - 0.59.1, fastlane latest version. I tried to run the fastlane screenshot via ios xcuitest But I couldn't dismiss the system alert. I have attached my code and alert screen

Could you please help me

addUIInterruptionMonitor(withDescription: "System Dialog") {
        (alert) -> Bool in
        let okButton = alert.buttons["OK"]
        if okButton.exists {
          okButton.tap()
        }

        let allowButton = alert.buttons["Allow"]
        if allowButton.exists {
          allowButton.tap()
        }

        return true
      }

      app.tap()
      snapshot("04EndRecord")

this is my alert and app. this alert shows outside of the app, then how can i handle that?


问:
error MSB6006: "CL.exe" exited with code 2
I'm writing with visual c++ and when I compile this error occures:

```<code>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\Microsoft.Cpp.Win32.Targets(147,5): error MSB6006: "CL.exe" terminato con il codice 2.
</code>```

Does anyone know why?

Thanks in advance!

答:
I got the same error when I forgot the return statement in the following method:</p>

```<code>char SpiRAM::write_byte(int address, char data_byte)
{
    assert(address >= 0);
    assert(address < SRAM_SIZE);

    _sram[address] = data_byte;

    return data_byte;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing with visual c++ and when I compile this error occures:

C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\Microsoft.Cpp.Win32.Targets(147,5): error MSB6006: "CL.exe" terminato con il codice 2.

Does anyone know why?

Thanks in advance!

Body:
I got the same error when I forgot the return statement in the following method:

char SpiRAM::write_byte(int address, char data_byte)
{
    assert(address >= 0);
    assert(address < SRAM_SIZE);

    _sram[address] = data_byte;

    return data_byte;
}


问:
How to send and receive a generically typed object in a list
I'm trying to create a class in which I have two override functions via an interface. The interface will be generically typed and I want the functions to simple be conversions.

I've been able to make this work, however, when I create multiples of these objects and put them into a list and access them singularly then the function that should take the generic type as input gives the error: Type mismatch: inferred type is Any but Nothing was expected

In other words:

```<code>interface ConverterInterface<T>{
    fun sender(value: T): ByteArray
    fun receiver(bytes: ByteArray): T
}
</code>```

And this does work when first implemented:

```<code>class TestClass {
    val objA = object: ConverterInterface<String>{
        override fun sender(value: String): ByteArray {
            //...
        }

        override fun receiver(bytes: ByteArray): String {
            //...
        }
    }
}
</code>```

However, I want to store a list of these objects and access them later.

```<code>fun test(){
    val testList: List<ConverterInterface<*>> = listOf(objA)

    // This works
    testList[0].receiver(byteArrayOf())

    // This does not
    testList[0].sender("")
    /* Out-projected type 'ConverterInterface<*>' prohibits the use of
    'public abstract fun sender(value: T): ByteArray defined in ConverterInterface */
}
</code>```

I had to use the wildcard * for the list type because if I tried to use Any I would get a type inference failed error. To make it work I could set the type as out Any but this doesn't fix anything and causes only the receiver function to work.

I feel that what I'm trying to do may not be possible. Simply put I want to be able to access these functions without doing type casting.

答:
I think you'll have to do a bit of redesign here.  The compiler is warning you about a serious type-safety problem in your code, and if you don't fix it properly, it's likely to come back to bite you.

You have a List of converters, but you can't tell what each one can convert; each one implements the ConverterInterface<T> for some type T, but you don't know what T is for any particular item in the list.

testList[0] (assuming the list has at least one item) could implement ConverterInterface<String>, or ConverterInterface<Int>, or ConverterInterface<Map<URL, LinkedList<LinearGradientPaint>>, or anything else.  So it's not safe to testList[0].realSender(""), because it might not accept a String.

That's why the compiler complains; it doesn't know anything about the type involved, so it has to assume the worst case, and disallow the call.  Otherwise, you'd risk a ClassCastException at runtime when the converter couldn't handle the type of parameter you pass it.

Even worse, due to type erasure, you can't find out that type at runtime, either.  (At runtime, after the compiler has done its magic, there's only a simple ConverterInterface.)

By the way, the answer with a realSender() isn't fixing this problem, just telling the compiler to shut up about it.  It'll still bite you at runtime.

So I think you'll need to think more carefully about what you're trying to achieve here.

Why are you storing these converters in a list, and why do you need to access them that way?

If you you know every implementation will be able to accept Strings, then make the list a List<ConverterInterface<String>>: the compiler will ensure that everything in the list can take Strings, and you can then safely pass a String to any converter in the list.

But if the list could contain different types of converter, then how will you know that the converter you're looking at can take any particular type?  Even if the code works for now, there's still a risk that an extra item will get inserted into the list later on, and screw things up.  So you'd have to keep track some other way.  And that other way would probably give you a better (typesafe) way to access them.

Body:
I'm trying to create a class in which I have two override functions via an interface. The interface will be generically typed and I want the functions to simple be conversions.

I've been able to make this work, however, when I create multiples of these objects and put them into a list and access them singularly then the function that should take the generic type as input gives the error: Type mismatch: inferred type is Any but Nothing was expected

In other words:

interface ConverterInterface<T>{
    fun sender(value: T): ByteArray
    fun receiver(bytes: ByteArray): T
}

And this does work when first implemented:

class TestClass {
    val objA = object: ConverterInterface<String>{
        override fun sender(value: String): ByteArray {
            //...
        }

        override fun receiver(bytes: ByteArray): String {
            //...
        }
    }
}

However, I want to store a list of these objects and access them later.

fun test(){
    val testList: List<ConverterInterface<*>> = listOf(objA)

    // This works
    testList[0].receiver(byteArrayOf())

    // This does not
    testList[0].sender("")
    /* Out-projected type 'ConverterInterface<*>' prohibits the use of
    'public abstract fun sender(value: T): ByteArray defined in ConverterInterface */
}

I had to use the wildcard * for the list type because if I tried to use Any I would get a type inference failed error. To make it work I could set the type as out Any but this doesn't fix anything and causes only the receiver function to work.

I feel that what I'm trying to do may not be possible. Simply put I want to be able to access these functions without doing type casting.


问:
Python subprocess blocks in embedded environment
My script takes large number of files as input, calling external programs using subprocess.call(). It works perfectly from regular OS consoles, but hangs after processing 10 files or so when running in an embedded environment using its embedded Python 2.7.x.

I've referred to various similar questions and failed to find one working for me:

Python: subprocess.Popen and subprocess.call hang

Python subprocess hangs

Python subprocess call hangs

and this in-depth discussion: https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/

They all imply the vulnerable buffered PIPE, and suggest using file-like objects for stdout and stderr. So I also added a temporary text file, opened it, and fed it to stdout and stderr of subprocess.call(). It didn't work either.

My old code is fairly straight forward:

```<code># script1.py

folder = "/path/to/my/folder"
for root, dirs, files in os.walk(folder):
    for file in files:
        path = join(root, file)
        try:
            cmd = ['dir', path, '1>&2']
            _logger.debug(' '.join(cmd))
            completed = subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as err:
            _logger.debug(err)
        else:
            _logger.debug('returncode: {}'.format(completed))
print('all done!!')
</code>```

the main script:

```<code>try:
    cmd = ['python', 'script1.py', '1>&2']
    ue.log(' '.join(cmd))
    completed = subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
    _logger.error(err)
</code>```

I've mixed-and-matched a couple of stdout/stderr solutions.
including adding:

```<code>with open(join(_script_dir, 'tmp.txt'), 'w') as tmp:
    #
    # old code
    #
     completed = subprocess.call(cmd, shell=True, stdout=tmp, stderr=tmp)
</code>```

None worked.

答:
I ended up throwing away all the pipes and stdout/stderr, and use the default of Python 3.7.2's subprocess.Popen() arguments, i.e., None for stdout/stderr, and remove 1>&2. So basically just don't bother retrieving the realtime output of another program when the program works with large amount of input and potentially generates a huge wave of output through the narrow and hidden pipe. I turned to using just log files written for each individual script.

I am much happier with this solution than blindly trying all kinds of UNIX tricks to solve the pipe issue on Windows.

P.S.,
Some answers from my above links suggested shell=False, I found that annoying in that the embedded environment will spawn lots of floating console windows out of each subprocess.call().

Body:
My script takes large number of files as input, calling external programs using subprocess.call(). It works perfectly from regular OS consoles, but hangs after processing 10 files or so when running in an embedded environment using its embedded Python 2.7.x.

I've referred to various similar questions and failed to find one working for me:

Python: subprocess.Popen and subprocess.call hang

Python subprocess hangs

Python subprocess call hangs

and this in-depth discussion: https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/

They all imply the vulnerable buffered PIPE, and suggest using file-like objects for stdout and stderr. So I also added a temporary text file, opened it, and fed it to stdout and stderr of subprocess.call(). It didn't work either.

My old code is fairly straight forward:

# script1.py

folder = "/path/to/my/folder"
for root, dirs, files in os.walk(folder):
    for file in files:
        path = join(root, file)
        try:
            cmd = ['dir', path, '1>&2']
            _logger.debug(' '.join(cmd))
            completed = subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as err:
            _logger.debug(err)
        else:
            _logger.debug('returncode: {}'.format(completed))
print('all done!!')

the main script:

try:
    cmd = ['python', 'script1.py', '1>&2']
    ue.log(' '.join(cmd))
    completed = subprocess.call(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
    _logger.error(err)

I've mixed-and-matched a couple of stdout/stderr solutions.
including adding:

with open(join(_script_dir, 'tmp.txt'), 'w') as tmp:
    #
    # old code
    #
     completed = subprocess.call(cmd, shell=True, stdout=tmp, stderr=tmp)

None worked.


问:
Changing iPhone X status bar style color to white
I need to change the status bar content color to white in my iPhone project.

I have done this by

```<code>override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
</code>```

This changes the color but there is one problem. On iPhone X the time on the top left is getting truncated. Any idea how to fix this?

答:
Hey @Santosh Jayapal can you try this In appDelegate.swift , the didFinishLaunchingWithOptions function, add:

UIApplication.shared.statusBarStyle = .lightContent

Body:
I need to change the status bar content color to white in my iPhone project.

I have done this by

override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

This changes the color but there is one problem. On iPhone X the time on the top left is getting truncated. Any idea how to fix this?


问:
How to use AND/OR conditions with dynamic variables on Where Clause using Python?
Hi I am really confused on how I can add "AND / OR" condition on my where statement if the variable is dynamic? I am actually scraping a content.

My Code is this:

```<code>self.curr.execute("SELECT Count(post_id) from tesla_news_items WHERE
post_id = %s COLLATE utf8mb4_unicode_ci",(item['post_id'],) )
</code>```

My logic is something like this:

```<code>Where post_id = %s , (item['post_id'],) AND title = %s, (item['title],)
</code>```

Anyone who can help me please?

答:
You already seem to know how to use a parameterized query. The addition of "or" or "and" should not make much of a difference.</p>

```<code>self.curr.execute("SELECT Count(post_id) from tesla_news_items WHERE
post_id = %s COLLATE utf8mb4_unicode_ci AND title = %s", (item['post_id'], item['title']))
</code>```

Body:
Hi I am really confused on how I can add "AND / OR" condition on my where statement if the variable is dynamic? I am actually scraping a content.

My Code is this:

self.curr.execute("SELECT Count(post_id) from tesla_news_items WHERE
post_id = %s COLLATE utf8mb4_unicode_ci",(item['post_id'],) )

My logic is something like this:

Where post_id = %s , (item['post_id'],) AND title = %s, (item['title],)

Anyone who can help me please?

Body:
You already seem to know how to use a parameterized query. The addition of "or" or "and" should not make much of a difference.

self.curr.execute("SELECT Count(post_id) from tesla_news_items WHERE
post_id = %s COLLATE utf8mb4_unicode_ci AND title = %s", (item['post_id'], item['title']))


问:
Angular Multiple subscriptions then perform action
I have a function that request data from an API using subscriptions. I am trying to re-write it so that it returns a boolean when all API calls have finished. Is there a better way to write this?

My current code:

```<code>public res1=null;
public res2=null;

getData(){
 this.svc.getData1().subscribe(x={this.res1=x;})
 this.svc.getData2().subscribe(x={this.res2=x;})
}
</code>```

I was thinking of trying to create an Observable that listens for changes to the nested subscriptions: (not tested code!)

```<code>getData(): Observable<boolean>{
 this.svc.getData1().subscribe(x=>{
   this.res1=x;
   this.svc.getData2().subscribe(x=>{this.res2=x;
     return true;
   })
 })
)
</code>```

}

答:
you can use merge operator to combine observables and subscribe them in parallel.</p>

```<code> getData(): Observable<boolean>{
    let isCompleted: Observable<boolean>;
    merge(this.svc.getData1(), this.svc.getData2()).subscribe(
      (val) => {console.log(val) },
    (err) => { console.log(err) },
    ()=>{isCompleted = of (true); });
    return isCompleted;
  }
</code>```

Body:
I have a function that request data from an API using subscriptions. I am trying to re-write it so that it returns a boolean when all API calls have finished. Is there a better way to write this?

My current code:

public res1=null;
public res2=null;

getData(){
 this.svc.getData1().subscribe(x={this.res1=x;})
 this.svc.getData2().subscribe(x={this.res2=x;})
}

I was thinking of trying to create an Observable that listens for changes to the nested subscriptions: (not tested code!)

getData(): Observable<boolean>{
 this.svc.getData1().subscribe(x=>{
   this.res1=x;
   this.svc.getData2().subscribe(x=>{this.res2=x;
     return true;
   })
 })
)

}

Body:
you can use merge operator to combine observables and subscribe them in parallel.

 getData(): Observable<boolean>{
    let isCompleted: Observable<boolean>;
    merge(this.svc.getData1(), this.svc.getData2()).subscribe(
      (val) => {console.log(val) },
    (err) => { console.log(err) },
    ()=>{isCompleted = of (true); });
    return isCompleted;
  }


问:
Cross applying or inner joining as subquery for a TVF
Situation:

I have a TVF with one parameter DATE. I want to allow the user to input a list of strings as an additional parameter. I am familiar with user types but I don't want to use it.

Function: dbo.fnExample(@StartDate)

Here are my two options:
Option 1

```<code>SELECT base.*
FROM (SELECT * FROM dbo.fnExample('2019-05-01')) AS base
INNER JOIN ( VALUES
('something'),
('something2'),
('n'),
(...)) AS base2(ColumnA)
ON base.ColumnA=base2.ColumnA
</code>```

Option 2 (not working because im not sure how to join on that column with a cross apply).

```<code>SELECT *
FROM ( VALUES
('something'),
('something2'),
('n'),
(...)) AS base2(ColumnA)
CROSS APPLY dbo.fnExample('2019-05-01')
</code>```

Objective:

My question is three-fold. Which would have a better performance? Are there any other options not mentioned above that could be better? What are the limiations from the proposed options ? Thank you for your help!

答:
I think you want JOIN, not APPLY:

```<code>SELECT *
FROM dbo.fnExample('2019-05-01') f JOIN
     ( VALUES ('something'), ('something2'), ('n'), (...)
     ) AS base2(ColumnA)
     ON  f.columnA = base2.ColumnA;
</code>```

That is, table-valued functions do not have to be called using APPLY.  APPLY is a way to pass in arguments from other FROM-clause entries.

Body:
Situation:

I have a TVF with one parameter DATE. I want to allow the user to input a list of strings as an additional parameter. I am familiar with user types but I don't want to use it.

Function: dbo.fnExample(@StartDate)

Here are my two options:
Option 1

SELECT base.*
FROM (SELECT * FROM dbo.fnExample('2019-05-01')) AS base
INNER JOIN ( VALUES
('something'),
('something2'),
('n'),
(...)) AS base2(ColumnA)
ON base.ColumnA=base2.ColumnA

Option 2 (not working because im not sure how to join on that column with a cross apply).

SELECT *
FROM ( VALUES
('something'),
('something2'),
('n'),
(...)) AS base2(ColumnA)
CROSS APPLY dbo.fnExample('2019-05-01')

Objective:

My question is three-fold. Which would have a better performance? Are there any other options not mentioned above that could be better? What are the limiations from the proposed options ? Thank you for your help!

Body:
I think you want JOIN, not APPLY:

SELECT *
FROM dbo.fnExample('2019-05-01') f JOIN
     ( VALUES ('something'), ('something2'), ('n'), (...)
     ) AS base2(ColumnA)
     ON  f.columnA = base2.ColumnA;

That is, table-valued functions do not have to be called using APPLY.  APPLY is a way to pass in arguments from other FROM-clause entries.


问:
How do I invoke the debugger in a Rails functional test?
With Rails 3, Ruby 1.9, and Test::Unit, what's the right way to invoke the debugger on a functional test? I've tried adding "debugger" and then running rake:test:functionals:

```<code>class AdminControllerTest < ActionController::TestCase
    test "should get index" do
        debugger
        get :index
        assert_redirected_to welcome_url
    end
end
</code>```

but Ruby seems to ignore the call to debugger (the test goes ahead and runs normally). If I try running the test directly:

```<code>ruby -r debug test/functional/admin_controller_test.rb
</code>```

then Ruby can't find test_helper.rb.  If, following the answer below, I run:

```<code>ruby -I "lib:test" test/functional/admin_controller_test.rb
</code>```

then it finds test_helper but again runs the test to completion without invoking the debugger. My Gemfile does have:

```<code>gem 'ruby-debug19', :require => 'ruby-debug', :group => :development
</code>```

答: You're going to need the ruby-debug19 gem.

Body:
With Rails 3, Ruby 1.9, and Test::Unit, what's the right way to invoke the debugger on a functional test? I've tried adding "debugger" and then running rake:test:functionals:

class AdminControllerTest < ActionController::TestCase
    test "should get index" do
        debugger
        get :index
        assert_redirected_to welcome_url
    end
end

but Ruby seems to ignore the call to debugger (the test goes ahead and runs normally). If I try running the test directly:

ruby -r debug test/functional/admin_controller_test.rb

then Ruby can't find test_helper.rb.  If, following the answer below, I run:

ruby -I "lib:test" test/functional/admin_controller_test.rb

then it finds test_helper but again runs the test to completion without invoking the debugger. My Gemfile does have:

gem 'ruby-debug19', :require => 'ruby-debug', :group => :development


问:
merge multiple actions into a single one in effects
I have the following list of action and I want to merge them so that I return a list of action and execute them one by one.

I tried

```<code>    map(drones => {
      const actions = [];
      drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
      actions.push(new featureActions.GetUsedDronesSuccess({drones}));
      return forkJoin(actions);
    }),
</code>```

I also tried

```<code>    map(drones => {
      const actions = [];
      drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
      actions.push(new featureActions.GetUsedDronesSuccess({drones}));
      return merge(actions);
    }),
</code>```

booth doesn't works

ERROR Error: Effect "UsedDronesEffect.getUsedDrones$" dispatched an
  invalid action: {"_isScalar":false}

```<code>core.js:15724 ERROR TypeError: Actions must have a type property
    at
</code>```

How can I merge them ?

答:
You can try the following example or try using mergeMap() to combine your new actions

@Effect() drones = this.dronesEffect.pipe(
   ...,
   switchMap((res: drones[]) => drones.map(x => new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })))
   )
);
```

Check out this Article

Body:
I have the following list of action and I want to merge them so that I return a list of action and execute them one by one.

I tried

    map(drones => {
      const actions = [];
      drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
      actions.push(new featureActions.GetUsedDronesSuccess({drones}));
      return forkJoin(actions);
    }),

I also tried

    map(drones => {
      const actions = [];
      drones.forEach((drone) => actions.push(new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })));
      actions.push(new featureActions.GetUsedDronesSuccess({drones}));
      return merge(actions);
    }),

booth doesn't works

ERROR Error: Effect "UsedDronesEffect.getUsedDrones$" dispatched an
  invalid action: {"_isScalar":false}

core.js:15724 ERROR TypeError: Actions must have a type property
    at

How can I merge them ?

Body:
You can try the following example or try using mergeMap() to combine your new actions

@Effect() drones = this.dronesEffect.pipe(
   ...,
   switchMap((res: drones[]) => drones.map(x => new featureActions.OpenUsedDroneUpdateChannelRequest({ droneId: drone.id, projectId : environment.projectId })))
   )
);

Check out this Article


问:
How would I use an array with the contains operator
I have a CSV file and in that file are 2 columns (this is just for testing purposes before using actual files), I need to get all the data for the specific pets so Dog and Cat in this example.

I have put the animals I want the data for in an array but for some reason the statement is not working it just returns an empty file, when I use a string (so just "dog") in the place of the array then I get the data back fine. Is there anything i'm doing wrong

```<code>$Pets = "Dog", "Cat"

import-csv -Path "C:\Users\User\deletingRows.csv" | where Animal -Contains $Pets | export-csv -Path "C:\Users\User\Result.csv" -NoTypeInformation
</code>```

答:
I believe you're misunderstanding what -Contains is supposed to do. Since you're trying to match a field against more than one value (within $Pets), you're better of using the -In switch. See the working example below.

```<code>$Pets = "Dog", "Cat"

Import-Csv -Path "C:\Users\User\deletingRows.csv" | where "Animal" -In $Pets | Export-Csv -Path "C:\Users\User\Result.csv" -NoTypeInformation
</code>```

Body:
I have a CSV file and in that file are 2 columns (this is just for testing purposes before using actual files), I need to get all the data for the specific pets so Dog and Cat in this example.

I have put the animals I want the data for in an array but for some reason the statement is not working it just returns an empty file, when I use a string (so just "dog") in the place of the array then I get the data back fine. Is there anything i'm doing wrong

$Pets = "Dog", "Cat"

import-csv -Path "C:\Users\User\deletingRows.csv" | where Animal -Contains $Pets | export-csv -Path "C:\Users\User\Result.csv" -NoTypeInformation

Body:
I believe you're misunderstanding what -Contains is supposed to do. Since you're trying to match a field against more than one value (within $Pets), you're better of using the -In switch. See the working example below.

$Pets = "Dog", "Cat"

Import-Csv -Path "C:\Users\User\deletingRows.csv" | where "Animal" -In $Pets | Export-Csv -Path "C:\Users\User\Result.csv" -NoTypeInformation


问:
How to create different object types using spring boot and query annotation?
I need to create an object that has all the fields of a table and that some information from another table is together (not all).

@Query( "SELECT new com.nowigo.systemsheet.User.User (U.id, U.name)
  FROM user U INNER JOIN U.promoter P where P.id = ?1") public
  List findAllById(Long promoterId);

@Query( "SELECT U.id,U.name,P.name FROM user U INNER JOIN U.promoter P
  where P.id = ?1")

Entity User

package com.nowigo.systemsheet.User;

import com.nowigo.systemsheet.base.BaseEntity;
import com.nowigo.systemsheet.Promoter.Promoter;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
//@Inheritance(strategy = InheritanceType.JOINED)
public class User extends BaseEntity implements Serializable{

    @ManyToOne
    @JoinColumn(name = "promoter_id" )
    private Promoter promoter;

    private String name;

    private String username;

    private String password;

    private String description;

    @Column(name = "enabled", columnDefinition = "tinyint")
    private Boolean enabled;

    private Integer types;

    private String permissions;

    private Long restricted_event_id;

    private Long restricted_cashlesscash_id;

    private Long restricted_reseller_id;

    @Column(name = "time_begin_reseller_bat", columnDefinition = "timestamp")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
    private Date time_begin_reseller_bat;

    @Column(name = "time_end_reseller_bat", columnDefinition = "timestamp")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
    private Date time_end_reseller_bat;

    @Column(name = "time_begin_reseller_individual", columnDefinition = "timestamp")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
    private Date time_begin_reseller_individual;

    @Column(name = "time_end_reseller_individual", columnDefinition = "timestamp")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
    private Date time_end_reseller_individual;

    private Long img_id;

    @Column(name = "can_make_return_operation", columnDefinition = "tinyint")
    private Boolean can_make_return_operation;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Long getRestricted_reseller_id() {
        return restricted_reseller_id;
    }

    public void setRestricted_reseller_id(Long restricted_reseller_id) {
        this.restricted_reseller_id = restricted_reseller_id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Boolean getEnabled() {
        return enabled;
    }

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    public Integer getTypes() {
        return types;
    }

    public void setTypes(Integer types) {
        this.types = types;
    }

    public String getPermissions() {
        return permissions;
    }

    public void setPermissions(String premissions) {
        this.permissions = permissions;
    }

    public Long getRestricted_event_id() {
        return restricted_event_id;
    }

    public void setRestricted_event_id(Long restricted_event_id) {
        this.restricted_event_id = restricted_event_id;
    }

    public Long getRestricted_cashlesscash_id() {
        return restricted_cashlesscash_id;
    }

    public void setRestricted_cashlesscash_id(Long restricted_cashlesscash_id) {
        this.restricted_cashlesscash_id = restricted_cashlesscash_id;
    }

    public Long getRestricted_resellet_id() {
        return restricted_reseller_id;
    }

    public void setRestricted_resellet_id(Long restricted_resellet_id) {
        this.restricted_reseller_id = restricted_resellet_id;
    }

    public Date getTime_begin_reseller_bat() {
        return time_begin_reseller_bat;
    }

    public void setTime_begin_reseller_bat(Date time_begin_reseller_bat) {
        this.time_begin_reseller_bat = time_begin_reseller_bat;
    }

    public Date getTime_end_reseller_bat() {
        return time_end_reseller_bat;
    }

    public void setTime_end_reseller_bat(Date time_end_reseller_bat) {
        this.time_end_reseller_bat = time_end_reseller_bat;
    }

    public Date getTime_begin_reseller_individual() {
        return time_begin_reseller_individual;
    }

    public void setTime_begin_reseller_individual(Date time_begin_reseller_individual) {
        this.time_begin_reseller_individual = time_begin_reseller_individual;
    }

    public Date getTime_end_reseller_individual() {
        return time_end_reseller_individual;
    }

    public void setTime_end_reseller_individual(Date time_end_reseller_individual) {
        this.time_end_reseller_individual = time_end_reseller_individual;
    }

    public Long getImg_id() {
        return img_id;
    }

    public void setImg_id(Long img_id) {
        this.img_id = img_id;
    }

    public Boolean getCan_make_return_operation() {
        return can_make_return_operation;
    }

    public void setCan_make_return_operation(Boolean can_make_return_operation) {
        this.can_make_return_operation = can_make_return_operation;
    }

    public Boolean getCan_make_register_operation() {
        return can_make_register_operation;
    }

    public void setCan_make_register_operation(Boolean can_make_register_operation) {
        this.can_make_register_operation = can_make_register_operation;
    }

    @Column(name = "can_make_register_operation", columnDefinition = "tinyint")
    private Boolean can_make_register_operation;

    public Promoter getPromoter() {
        return promoter;
    }

    public void setPromoter(Promoter promoter) {
        this.promoter = promoter;
    }

    public User(String name) {
        this.name = name;
        this.getId();
    }

    public User() {
    }

    public User(Promoter promoter, String name, String username, String password, String description, Boolean enabled, Integer types, String permissions, Long restricted_event_id, Long restricted_cashlesscash_id, Long restricted_reseller_id, Date time_begin_reseller_bat, Date time_end_reseller_bat, Date time_begin_reseller_individual, Date time_end_reseller_individual, Long img_id, Boolean can_make_return_operation, Boolean can_make_register_operation) {
        this.promoter = promoter;
        this.name = name;
        this.username = username;
        this.password = password;
        this.description = description;
        this.enabled = enabled;
        this.types = types;
        this.permissions = permissions;
        this.restricted_event_id = restricted_event_id;
        this.restricted_cashlesscash_id = restricted_cashlesscash_id;
        this.restricted_reseller_id = restricted_reseller_id;
        this.time_begin_reseller_bat = time_begin_reseller_bat;
        this.time_end_reseller_bat = time_end_reseller_bat;
        this.time_begin_reseller_individual = time_begin_reseller_individual;
        this.time_end_reseller_individual = time_end_reseller_individual;
        this.img_id = img_id;
        this.can_make_return_operation = can_make_return_operation;
        this.can_make_register_operation = can_make_register_operation;
    }

}

```

<p>Entity Promoter</p>

```package com.nowigo.systemsheet.Promoter;

import com.nowigo.systemsheet.User.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.nowigo.systemsheet.base.BaseEntity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

@Entity
//@PrimaryKeyJoinColumn(name="user_id")
public class Promoter extends BaseEntity implements Serializable{

    @OneToMany(mappedBy = "promoter", orphanRemoval = true)
    @JsonIgnore
    private List<User> user;

    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    private String address;

    private String address_number;

    private String address_extra;

    private String address_area;

    private String city;

    private String cnpx;

    private String ierg;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getAddress_number() {
        return address_number;
    }

    public void setAddress_number(String address_number) {
        this.address_number = address_number;
    }

    public String getAddress_extra() {
        return address_extra;
    }

    public void setAddress_extra(String address_extra) {
        this.address_extra = address_extra;
    }

    public String getAddress_area() {
        return address_area;
    }

    public void setAddress_area(String address_area) {
        this.address_area = address_area;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCnpx() {
        return cnpx;
    }

    public void setCnpx(String cnpx) {
        this.cnpx = cnpx;
    }

    public String getIerg() {
        return ierg;
    }

    public void setIerg(String ierg) {
        this.ierg = ierg;
    }

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

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

    public Promoter(String address) {
        this.address = address;
    }

    public Promoter() {
    }

    public Promoter(List<User> user, String password, String address, String address_number, String address_extra, String address_area, String city, String cnpx, String ierg) {
        this.user = user;
        this.password = password;
        this.address = address;
        this.address_number = address_number;
        this.address_extra = address_extra;
        this.address_area = address_area;
        this.city = city;
        this.cnpx = cnpx;
        this.ierg = ierg;
    }
}
```

<p>User repository</p>

<pre class="lang-java prettyprint-override"><code>
package com.nowigo.systemsheet.User;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface UserRepository extends JpaRepository<User, Long> {

    public List<User> findByPromoterId(Long promoterId);

        @Query(value = "SELECT U.id,U.name, P.address FROM sheetsystem.user U JOIN sheetsystem.promoter P ON U.promoter_id = P.id where P.id = ?1", nativeQuery = true)
    public List<User> findAllById(Long promoterId);

}
</code>```

Expected:

```<code>    {
            "id": 17,
            "promoter": {
                "id": 4,
                "address": "Av. John Wick"
            },
            "name": "usuario",
            "username": null,
            "description": null,
            "enabled": null,
            "types": null,
            "permissions": null,
            "restricted_event_id": null,
            "restricted_cashlesscash_id": null,
            "restricted_reseller_id": null,
            "time_begin_reseller_bat": null,
            "time_end_reseller_bat": null,
            "time_begin_reseller_individual": null,
            "time_end_reseller_individual": null,
            "img_id": null,
            "can_make_return_operation": null,
            "can_make_register_operation": null,
            "restricted_resellet_id": null
      }
</code>```

I get this:

The field can_make_register_operation is not found

答:
I do not believe using an entity class to return a partially hydrated object from a native query is good practice.  Once you get that instance into the businses layer, you may loose some context in knowing whether it can be persisted later or whether its immutable all because its technically an instance of an annotated entity. You run the risk that someone might accidentally merge the changes to the data store and loose data.

Personally I think its much better practice as well as separation of concerns to design an intermediate object that the persistence layer returns that uniquely fits the data you're after, one which clearly identifies that the returned object is immutable, cannot be changed, nor can be persisted, like this:

```<code>public class UserProfileAddress {
  private Integer id;
  private String name;
  private Promoter promoter;

  UserProfileAddress(Integer id, String name, Promoter promoter) {
    this.id = id;
    this.name = name;
    this.promoter = promoter;
  }

  // .. getter/setters
}
</code>```

You should then be able to write the query as

```<code>SELECT new com.package.UserProfileAddress( u.id, u.name, u.promoter )
  FROM User u
  JOIN FETCH u.promoter
 WHERE u.promoter.id = :promoterId
</code>```

Now you're using a portable JPA query and not a native query, which makes your code than more resilient to potential future changes should you decide to change from one data store to another.

As to your error about what was expected; you'll need to provide more context.

Body:
I need to create an object that has all the fields of a table and that some information from another table is together (not all).

@Query( "SELECT new com.nowigo.systemsheet.User.User (U.id, U.name)
  FROM user U INNER JOIN U.promoter P where P.id = ?1") public
  List findAllById(Long promoterId);

@Query( "SELECT U.id,U.name,P.name FROM user U INNER JOIN U.promoter P
  where P.id = ?1")

Entity User

package com.nowigo.systemsheet.User;

import com.nowigo.systemsheet.base.BaseEntity;
import com.nowigo.systemsheet.Promoter.Promoter;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
//@Inheritance(strategy = InheritanceType.JOINED)
public class User extends BaseEntity implements Serializable{

    @ManyToOne
    @JoinColumn(name = "promoter_id" )
    private Promoter promoter;

    private String name;

    private String username;

    private String password;

    private String description;

    @Column(name = "enabled", columnDefinition = "tinyint")
    private Boolean enabled;

    private Integer types;

    private String permissions;

    private Long restricted_event_id;

    private Long restricted_cashlesscash_id;

    private Long restricted_reseller_id;

    @Column(name = "time_begin_reseller_bat", columnDefinition = "timestamp")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
    private Date time_begin_reseller_bat;

    @Column(name = "time_end_reseller_bat", columnDefinition = "timestamp")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
    private Date time_end_reseller_bat;

    @Column(name = "time_begin_reseller_individual", columnDefinition = "timestamp")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
    private Date time_begin_reseller_individual;

    @Column(name = "time_end_reseller_individual", columnDefinition = "timestamp")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
    private Date time_end_reseller_individual;

    private Long img_id;

    @Column(name = "can_make_return_operation", columnDefinition = "tinyint")
    private Boolean can_make_return_operation;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Long getRestricted_reseller_id() {
        return restricted_reseller_id;
    }

    public void setRestricted_reseller_id(Long restricted_reseller_id) {
        this.restricted_reseller_id = restricted_reseller_id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Boolean getEnabled() {
        return enabled;
    }

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    public Integer getTypes() {
        return types;
    }

    public void setTypes(Integer types) {
        this.types = types;
    }

    public String getPermissions() {
        return permissions;
    }

    public void setPermissions(String premissions) {
        this.permissions = permissions;
    }

    public Long getRestricted_event_id() {
        return restricted_event_id;
    }

    public void setRestricted_event_id(Long restricted_event_id) {
        this.restricted_event_id = restricted_event_id;
    }

    public Long getRestricted_cashlesscash_id() {
        return restricted_cashlesscash_id;
    }

    public void setRestricted_cashlesscash_id(Long restricted_cashlesscash_id) {
        this.restricted_cashlesscash_id = restricted_cashlesscash_id;
    }

    public Long getRestricted_resellet_id() {
        return restricted_reseller_id;
    }

    public void setRestricted_resellet_id(Long restricted_resellet_id) {
        this.restricted_reseller_id = restricted_resellet_id;
    }

    public Date getTime_begin_reseller_bat() {
        return time_begin_reseller_bat;
    }

    public void setTime_begin_reseller_bat(Date time_begin_reseller_bat) {
        this.time_begin_reseller_bat = time_begin_reseller_bat;
    }

    public Date getTime_end_reseller_bat() {
        return time_end_reseller_bat;
    }

    public void setTime_end_reseller_bat(Date time_end_reseller_bat) {
        this.time_end_reseller_bat = time_end_reseller_bat;
    }

    public Date getTime_begin_reseller_individual() {
        return time_begin_reseller_individual;
    }

    public void setTime_begin_reseller_individual(Date time_begin_reseller_individual) {
        this.time_begin_reseller_individual = time_begin_reseller_individual;
    }

    public Date getTime_end_reseller_individual() {
        return time_end_reseller_individual;
    }

    public void setTime_end_reseller_individual(Date time_end_reseller_individual) {
        this.time_end_reseller_individual = time_end_reseller_individual;
    }

    public Long getImg_id() {
        return img_id;
    }

    public void setImg_id(Long img_id) {
        this.img_id = img_id;
    }

    public Boolean getCan_make_return_operation() {
        return can_make_return_operation;
    }

    public void setCan_make_return_operation(Boolean can_make_return_operation) {
        this.can_make_return_operation = can_make_return_operation;
    }

    public Boolean getCan_make_register_operation() {
        return can_make_register_operation;
    }

    public void setCan_make_register_operation(Boolean can_make_register_operation) {
        this.can_make_register_operation = can_make_register_operation;
    }

    @Column(name = "can_make_register_operation", columnDefinition = "tinyint")
    private Boolean can_make_register_operation;

    public Promoter getPromoter() {
        return promoter;
    }

    public void setPromoter(Promoter promoter) {
        this.promoter = promoter;
    }

    public User(String name) {
        this.name = name;
        this.getId();
    }

    public User() {
    }

    public User(Promoter promoter, String name, String username, String password, String description, Boolean enabled, Integer types, String permissions, Long restricted_event_id, Long restricted_cashlesscash_id, Long restricted_reseller_id, Date time_begin_reseller_bat, Date time_end_reseller_bat, Date time_begin_reseller_individual, Date time_end_reseller_individual, Long img_id, Boolean can_make_return_operation, Boolean can_make_register_operation) {
        this.promoter = promoter;
        this.name = name;
        this.username = username;
        this.password = password;
        this.description = description;
        this.enabled = enabled;
        this.types = types;
        this.permissions = permissions;
        this.restricted_event_id = restricted_event_id;
        this.restricted_cashlesscash_id = restricted_cashlesscash_id;
        this.restricted_reseller_id = restricted_reseller_id;
        this.time_begin_reseller_bat = time_begin_reseller_bat;
        this.time_end_reseller_bat = time_end_reseller_bat;
        this.time_begin_reseller_individual = time_begin_reseller_individual;
        this.time_end_reseller_individual = time_end_reseller_individual;
        this.img_id = img_id;
        this.can_make_return_operation = can_make_return_operation;
        this.can_make_register_operation = can_make_register_operation;
    }

}

Entity Promoter

package com.nowigo.systemsheet.Promoter;

import com.nowigo.systemsheet.User.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.nowigo.systemsheet.base.BaseEntity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

@Entity
//@PrimaryKeyJoinColumn(name="user_id")
public class Promoter extends BaseEntity implements Serializable{

    @OneToMany(mappedBy = "promoter", orphanRemoval = true)
    @JsonIgnore
    private List<User> user;

    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    private String address;

    private String address_number;

    private String address_extra;

    private String address_area;

    private String city;

    private String cnpx;

    private String ierg;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getAddress_number() {
        return address_number;
    }

    public void setAddress_number(String address_number) {
        this.address_number = address_number;
    }

    public String getAddress_extra() {
        return address_extra;
    }

    public void setAddress_extra(String address_extra) {
        this.address_extra = address_extra;
    }

    public String getAddress_area() {
        return address_area;
    }

    public void setAddress_area(String address_area) {
        this.address_area = address_area;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCnpx() {
        return cnpx;
    }

    public void setCnpx(String cnpx) {
        this.cnpx = cnpx;
    }

    public String getIerg() {
        return ierg;
    }

    public void setIerg(String ierg) {
        this.ierg = ierg;
    }

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

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

    public Promoter(String address) {
        this.address = address;
    }

    public Promoter() {
    }

    public Promoter(List<User> user, String password, String address, String address_number, String address_extra, String address_area, String city, String cnpx, String ierg) {
        this.user = user;
        this.password = password;
        this.address = address;
        this.address_number = address_number;
        this.address_extra = address_extra;
        this.address_area = address_area;
        this.city = city;
        this.cnpx = cnpx;
        this.ierg = ierg;
    }
}

User repository

package com.nowigo.systemsheet.User;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface UserRepository extends JpaRepository<User, Long> {

    public List<User> findByPromoterId(Long promoterId);

        @Query(value = "SELECT U.id,U.name, P.address FROM sheetsystem.user U JOIN sheetsystem.promoter P ON U.promoter_id = P.id where P.id = ?1", nativeQuery = true)
    public List<User> findAllById(Long promoterId);

}

Expected:

    {
            "id": 17,
            "promoter": {
                "id": 4,
                "address": "Av. John Wick"
            },
            "name": "usuario",
            "username": null,
            "description": null,
            "enabled": null,
            "types": null,
            "permissions": null,
            "restricted_event_id": null,
            "restricted_cashlesscash_id": null,
            "restricted_reseller_id": null,
            "time_begin_reseller_bat": null,
            "time_end_reseller_bat": null,
            "time_begin_reseller_individual": null,
            "time_end_reseller_individual": null,
            "img_id": null,
            "can_make_return_operation": null,
            "can_make_register_operation": null,
            "restricted_resellet_id": null
      }

I get this:

The field can_make_register_operation is not found

Body:
I do not believe using an entity class to return a partially hydrated object from a native query is good practice.  Once you get that instance into the businses layer, you may loose some context in knowing whether it can be persisted later or whether its immutable all because its technically an instance of an annotated entity. You run the risk that someone might accidentally merge the changes to the data store and loose data.

Personally I think its much better practice as well as separation of concerns to design an intermediate object that the persistence layer returns that uniquely fits the data you're after, one which clearly identifies that the returned object is immutable, cannot be changed, nor can be persisted, like this:

public class UserProfileAddress {
  private Integer id;
  private String name;
  private Promoter promoter;

  UserProfileAddress(Integer id, String name, Promoter promoter) {
    this.id = id;
    this.name = name;
    this.promoter = promoter;
  }

  // .. getter/setters
}

You should then be able to write the query as

SELECT new com.package.UserProfileAddress( u.id, u.name, u.promoter )
  FROM User u
  JOIN FETCH u.promoter
 WHERE u.promoter.id = :promoterId

Now you're using a portable JPA query and not a native query, which makes your code than more resilient to potential future changes should you decide to change from one data store to another.

As to your error about what was expected; you'll need to provide more context.


问:
What is the difference between partitioning and bucketing a table in Hive ?
I know both is performed on a column in the table but how is each operation different.</p>

答:
There are great responses here. I would like to keep it short to memorize the difference between partition & buckets.

You generally partition on a less unique column. And bucketing on most unique column.

Example if you consider World population with country, person name and their bio-metric id as an example. As you can guess, country field would be the less unique column and bio-metric id would be the most unique column. So ideally you would need to partition the table by country and bucket it by bio-metric id.


问:
How do i change the language for spellchecking in Libreoffice Calc
I have to create a table with LibeOffice Calc in another language than my native one.

If I run the spellchecking, I manually have to change the language for every word in the document. How do I change it for the whole document at once?

I tried to select the desired language in the Extra/Auto Correction Options menu, which had no effect.

答:
According to LibreOffice Help and a quick check on an existing Calc document.

Choose Tools - Options. Go to Language Settings - Languages.

Under Default languages for documents, select the document language for all newly created documents. If you mark For the current document only, your choice will only apply to the current document. Close the dialog with OK.


问:
How do i save some data from the UIWebView in an application for IPad
I am making an app for an IPad.
I have loaded a local html file in the UIWebView. I have now collected some data from the user. I want to save this locally so it can be used by the application for some other purpose.</p>

答: You could start reading about Property lists. I think that it could be very useful for your purpose.</p>


问:
Specifying one of base class template parameters by derived class template parameter. How to use base class's using declarations
For example, I have the next code:

```<code>template<typename T, typename T2>
class a
{
public:
    using myfl_t = float;

    a(myfl_t fl, double db) {}

    virtual void f()
    {
        std::cout << "a::f()\n";
    }
};

template<typename T>
class b : public a<T, int>
{
    using base_t = a<T, int>;
    using myfl_t = typename base_t::myfl_t;
public:
    b(myfl_t fl, double db)
        : base_t(fl, db) {}

    void f() override
    {
        std::cout << "b::f()\n";
    }
};
</code>```

It seems that I can reuse the base class's  myfl_t declaration only by duplicating using in the derived class.
Is there an easier way to do it?

答:
myflt_t defined in class a is not visible in class b as explained here: https://eli.thegreenplace.net/2012/02/06/dependent-name-lookup-for-c-templates

You can bring myflt_t into class b by without the explicit re-declaration:

```<code>using typename base_t::myfl_t
</code>```

Body:
For example, I have the next code:

template<typename T, typename T2>
class a
{
public:
    using myfl_t = float;

    a(myfl_t fl, double db) {}

    virtual void f()
    {
        std::cout << "a::f()\n";
    }
};

template<typename T>
class b : public a<T, int>
{
    using base_t = a<T, int>;
    using myfl_t = typename base_t::myfl_t;
public:
    b(myfl_t fl, double db)
        : base_t(fl, db) {}

    void f() override
    {
        std::cout << "b::f()\n";
    }
};

It seems that I can reuse the base class's  myfl_t declaration only by duplicating using in the derived class.
Is there an easier way to do it?

Body:
myflt_t defined in class a is not visible in class b as explained here: https://eli.thegreenplace.net/2012/02/06/dependent-name-lookup-for-c-templates

You can bring myflt_t into class b by without the explicit re-declaration:

using typename base_t::myfl_t


问:
Setup of static files in Heroku not working locally for Django
I am setting up a web app with Django 2.2 in Heroku and I was able to deploy it successfully in production but the app doesn't load the css files locally every time I try to run heroku local web.

This is how I setup the configuration of my files in my Django app.

```<code>- src
  - live-static
       - media-root
       - static-root
  - main_app
       - urls.py
       - wsgi.py
       - __init__.py
       - settings
           - __init__.py
           - base.py
           - local.py
           - production.py
  - pages
        - __init__.py
        - admin.py
        - apps.py
        - models.py
        - tests.py
        - views.py
        - templates
           - main_app
             - home.html
  - templates
       - base.html
  - static
       - main_app
           - css
             -cover.css
           - img
             -myimage.jpg
       - admin
           - css
           - img
           - js
</code>```

The following code is a snippet of the configurations from the production and local files:

```<code>production.py

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),)

STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

local.py

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),)

STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')
</code>```

My css and jpg files are not rendered locally but they are rendered in production.

```<code>base.html
{% load static %}

 <link href="{% static 'main_app/css/cover.css' %}" rel="stylesheet">
 <img src="{% static 'main_app/img/myimage.jpg' %}" >
</code>```

I expect that when I run heroku local web I should be able to see the css and images rendered.

答: I found out that the local.py file was missing the middleware whitenoise.middleware.WhiteNoiseMiddleware which is mandatory for visualizing the static files in Django.

Body:
I am setting up a web app with Django 2.2 in Heroku and I was able to deploy it successfully in production but the app doesn't load the css files locally every time I try to run heroku local web.

This is how I setup the configuration of my files in my Django app.

- src
  - live-static
       - media-root
       - static-root
  - main_app
       - urls.py
       - wsgi.py
       - __init__.py
       - settings
           - __init__.py
           - base.py
           - local.py
           - production.py
  - pages
        - __init__.py
        - admin.py
        - apps.py
        - models.py
        - tests.py
        - views.py
        - templates
           - main_app
             - home.html
  - templates
       - base.html
  - static
       - main_app
           - css
             -cover.css
           - img
             -myimage.jpg
       - admin
           - css
           - img
           - js

The following code is a snippet of the configurations from the production and local files:

production.py

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),)

STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

local.py

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),)

STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')

My css and jpg files are not rendered locally but they are rendered in production.

base.html
{% load static %}

 <link href="{% static 'main_app/css/cover.css' %}" rel="stylesheet">

I expect that when I run heroku local web I should be able to see the css and images rendered.


问:
Connect SQL Server from SQL Developer
I searched through all threads on the web available, but none could help me.

I am trying to connect to SQL Server engine from SQL Developer. In order to do that I enabled Named Pipes and TCP/IP from SQL Configuration Manager.

Then I tried different drivers:

I tried Microsoft JDBC driver for SQL Server - I cannot choose in connection manager SQL Server database type, so it does not work..

I tried jTDS driver instead, and it worked - I can choose SQL Server database type, but then all I get is an error informing that it cannot connect to Microsoft SQL Server on localhost (I tried localhost, name of my computer, none of which worked).

Is there anything more I can do?

EDIT

This is what I have so far:

SECOND EDIT

I had more problems:

With error saying

Status: Failur-I/O Error: SSO Failed: Native SSPI library not loaded. Check the java.library.path system property

Using windows authentication, I still got asked for username and password.

(All details and solutions in my answer below)

答:
We only support the jTDS driver for SQL Server and Sybase ASE connections, so that's the way to go.

After that, it's up to you to get a correct connection string to your SQL Server system.

Make sure you have the right port in addition to your 'localhost' network location for your SQL Server instance.

This is using version 19.1 of SQL Developer to connect to a SQL2012 instance overseas..

Title: Connect SQL Server from SQL Developer


问:
Issue with libpq.so.5 and PQencryptPasswordConn version RHPG_10 on Fedora30
I am trying to run my python script but I am getting below error. I tried to install and uninstall psycopg2  in different ways but is not working. My postgres version is 9.6 and my psycopg2 version is 2.8.2. Anyone had the same issue? Thanks in advance.</p>

```<code>   Traceback (most recent call last):
      File "server.py", line 89, in <module>
        cfg = Config(application, WSGI_PATH_PREFIX)
      File "server.py", line 60, in __init__
        self.mgrs = managers.register_managers(self.app)
      File "api/managers_fourwalls.py", line 31, in register_managers
        return Managers(app)
      File "api/managers_fourwalls.py", line 41, in __init__
        self.FourwallsEngine = four_walls({"posgres_db": self.DataManager.pg_connection_string})
      File "api/engine/four_walls_engine.py", line 14, in __init__
        self.engine = create_engine(self.db_string)
      File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/__init__.py", line 387, in create_engine
        return strategy.create(*args, **kwargs)
      File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/strategies.py", line 80, in create
        dbapi = dialect_cls.dbapi(**dbapi_args)
      File "/usr/lib64/python2.7/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 554, in dbapi
        import psycopg2
      File "/usr/lib64/python2.7/site-packages/psycopg2/__init__.py", line 50, in <module>
        from psycopg2._psycopg import (                     # noqa
    ImportError: /usr/lib64/python2.7/site-packages/psycopg2/_psycopg.so: symbol PQencryptPasswordConn version RHPG_10 not defined in file libpq.so.5 with link time reference
</code>```

答:
I solved the issue installing the binary stand alone:</p>

```<code>pip install psycopg2-binary
</code>```

Body:
I am trying to run my python script but I am getting below error. I tried to install and uninstall psycopg2  in different ways but is not working. My postgres version is 9.6 and my psycopg2 version is 2.8.2. Anyone had the same issue? Thanks in advance.

   Traceback (most recent call last):
      File "server.py", line 89, in <module>
        cfg = Config(application, WSGI_PATH_PREFIX)
      File "server.py", line 60, in __init__
        self.mgrs = managers.register_managers(self.app)
      File "api/managers_fourwalls.py", line 31, in register_managers
        return Managers(app)
      File "api/managers_fourwalls.py", line 41, in __init__
        self.FourwallsEngine = four_walls({"posgres_db": self.DataManager.pg_connection_string})
      File "api/engine/four_walls_engine.py", line 14, in __init__
        self.engine = create_engine(self.db_string)
      File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/__init__.py", line 387, in create_engine
        return strategy.create(*args, **kwargs)
      File "/usr/lib64/python2.7/site-packages/sqlalchemy/engine/strategies.py", line 80, in create
        dbapi = dialect_cls.dbapi(**dbapi_args)
      File "/usr/lib64/python2.7/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 554, in dbapi
        import psycopg2
      File "/usr/lib64/python2.7/site-packages/psycopg2/__init__.py", line 50, in <module>
        from psycopg2._psycopg import (                     # noqa
    ImportError: /usr/lib64/python2.7/site-packages/psycopg2/_psycopg.so: symbol PQencryptPasswordConn version RHPG_10 not defined in file libpq.so.5 with link time reference

Body:
I solved the issue installing the binary stand alone:

pip install psycopg2-binary


问:
RuntimeError: Attempting to deserialize object on a CUDA device
I encounter a RunTimeError while I am trying to run the code in my machine's CPU instead of GPU. The code is originally from this GitHub project - IBD: Interpretable Basis Decomposition for Visual Explanation. This is for a research project. I tried putting the CUDA as false and looked at other solutions on this website.

```<code>GPU = False               # running on GPU is highly suggested
CLEAN = False             # set to "True" if you want to clean the temporary large files after generating result
APP = "classification"    # Do not change! mode choide: "classification", "imagecap", "vqa". Currently "imagecap" and "vqa" are not supported.
CATAGORIES = ["object", "part"]   # Do not change! concept categories that are chosen to detect: "object", "part", "scene", "material", "texture", "color"

CAM_THRESHOLD = 0.5                 # the threshold used for CAM visualization
FONT_PATH = "components/font.ttc"   # font file path
FONT_SIZE = 26                      # font size
SEG_RESOLUTION = 7                  # the resolution of cam map
BASIS_NUM = 7                       # In decomposition, this is to decide how many concepts are used to interpret the weight vector of a class.
</code>```

Here is the error:

```<code>Traceback (most recent call last):
  File "test.py", line 22, in <module>
    model = loadmodel()
  File "/home/joshuayun/Desktop/IBD/loader/model_loader.py", line 48, in loadmodel
    checkpoint = torch.load(settings.MODEL_FILE)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 387, in load
    return _load(f, map_location, pickle_module, **pickle_load_args)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 574, in _load
    result = unpickler.load()
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 537, in persistent_load
    deserialized_objects[root_key] = restore_location(obj, location)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 119, in default_restore_location
    result = fn(storage, location)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 95, in _cuda_deserialize
    device = validate_cuda_device(location)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 79, in validate_cuda_device
    raise RuntimeError('Attempting to deserialize object on a CUDA '
RuntimeError: Attempting to deserialize object on a CUDA device but
  torch.cuda.is_available() is False. If you are running on a CPU-only machine,
  please use torch.load with map_location='cpu' to map your storages to the CPU.
</code>```

答: As you state the problem hints you are trying to use a cuda-model on non-cuda machine. Pay attention to the details of the error message - please use torch.load with map_location='cpu' to map your storages to the CPU. I've had similar problem when I tried to load (from a checkpoint) pre-trained model on my cpu-only machine. The model was trained on a cuda machine so it couldn't be properly loaded. Once I added the map_location='cpu' argument to the load method everything worked.

Body:
I encounter a RunTimeError while I am trying to run the code in my machine's CPU instead of GPU. The code is originally from this GitHub project - IBD: Interpretable Basis Decomposition for Visual Explanation. This is for a research project. I tried putting the CUDA as false and looked at other solutions on this website.

GPU = False               # running on GPU is highly suggested
CLEAN = False             # set to "True" if you want to clean the temporary large files after generating result
APP = "classification"    # Do not change! mode choide: "classification", "imagecap", "vqa". Currently "imagecap" and "vqa" are not supported.
CATAGORIES = ["object", "part"]   # Do not change! concept categories that are chosen to detect: "object", "part", "scene", "material", "texture", "color"

CAM_THRESHOLD = 0.5                 # the threshold used for CAM visualization
FONT_PATH = "components/font.ttc"   # font file path
FONT_SIZE = 26                      # font size
SEG_RESOLUTION = 7                  # the resolution of cam map
BASIS_NUM = 7                       # In decomposition, this is to decide how many concepts are used to interpret the weight vector of a class.

Here is the error:

Traceback (most recent call last):
  File "test.py", line 22, in <module>
    model = loadmodel()
  File "/home/joshuayun/Desktop/IBD/loader/model_loader.py", line 48, in loadmodel
    checkpoint = torch.load(settings.MODEL_FILE)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 387, in load
    return _load(f, map_location, pickle_module, **pickle_load_args)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 574, in _load
    result = unpickler.load()
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 537, in persistent_load
    deserialized_objects[root_key] = restore_location(obj, location)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 119, in default_restore_location
    result = fn(storage, location)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 95, in _cuda_deserialize
    device = validate_cuda_device(location)
  File "/home/joshuayun/.local/lib/python3.6/site-packages/torch/serialization.py", line 79, in validate_cuda_device
    raise RuntimeError('Attempting to deserialize object on a CUDA '
RuntimeError: Attempting to deserialize object on a CUDA device but
  torch.cuda.is_available() is False. If you are running on a CPU-only machine,
  please use torch.load with map_location='cpu' to map your storages to the CPU.


问:
how to create a powershell remote session from inside a Java program?
I have the following code to connect to a remote machine and execute commands.It is working if I create a new session for each Invoke-Command call to the remote machine. I don't want to create a new session each time I use Invoke-Command as that will not scale for thousands of commands on hundreds of machines concurrently and session creation itself is a big overhead. I need a way so that I can reuse the same session object in the $session powershell variable for multiple Invoke-Command calls to the remote machines.</p>

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class PowerShellSession {

private static String subModule = "PowerShellSession";
String targetIpAddress;
String username;
String password;

public static Object connectPShellLock = new Object();

public PowerShellSession() {}

public void exec(String cmd, String credentials)  {

    String ex = "Invoke-Command -Session $session -ScriptBlock {" + cmd + "} -Computer " + targetIpAddress;

    String[] args = new String[] { "powershell", ex};
    try {
        execRemote(args);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void close() {
    String command = "Exit-PSSession";
    String[] args = new String[] { "powershell", command};
    try {
        execRemote(args);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private String getCredentials(String domain, String userName,
        String password) throws IOException {
    String creds = "$PlainPassword ='" + password
            + "'; $SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force;"
            + "$mycred = new-object -typename System.Management.Automation.PSCredential('" + userName + "', $SecurePassword);";
    creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";

    String[] args = new String[] { "powershell", creds};
    execRemote(args);
    return creds;
}

private void execRemote(String[] arguments) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(arguments);
    builder.redirectErrorStream(true);
    Process process = builder.start();
    doProcessIO(process);
}

// Do the IO for a passed process
private void doProcessIO(Process p) throws IOException {
    p.getOutputStream().close();
    String line;
    System.out.println("Output:");
    BufferedReader stdout = new BufferedReader(new InputStreamReader(
            p.getInputStream()));
    while ((line = stdout.readLine()) != null) {
        System.out.println(line);
    }
    stdout.close();
    System.out.println("Error:");
    BufferedReader stderr = new BufferedReader(new InputStreamReader(
            p.getErrorStream()));
    while ((line = stderr.readLine()) != null) {
        System.out.println(line);
    }
    stderr.close();
//      System.out.println("Done");
}

public static void main(String[] args) throws IOException {
    PowerShellSession psSession = new PowerShellSession();
    String credentials = psSession.getCredentials("9.120.241.195", "username", "password");
    psSession.targetIpAddress = "9.120.241.195";
    if(!credentials.equals("")) {
        Scanner input = new Scanner(System.in);
        while(true) {
            System.out.print("PS C:\\Windows\\system32> ");
            String cmd = input.nextLine();
            if(cmd.equals("q") || cmd.equals("e") || cmd.equals("quit") || cmd.equals("exit")) break;
            psSession.username = "username";
            psSession.password = "password";
            psSession.exec(cmd, "");
        }
        System.out.println("Finished PowerShell remote session.");
        input.close();
    }
    psSession.close();
}
}
</code>```

答:
```<code>public class PowerShellSession {
    private static String subModule = "PowerShellSession";
    String targetIpAddress;
    String username;
    String password;

    public static Object connectPShellLock = new Object();

    public PowerShellSession() {}

    public void exec(String cmd, String credentials)  {

        String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";

        String[] args = new String[] { "powershell", ex};
        try {
            execRemote(args);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        String command = "Exit-PSSession";
        String[] args = new String[] { "powershell", command};
        try {
            execRemote(args);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String getCredentials(String domain, String userName,
            String password) throws IOException {
        String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
                + "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
                + "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
        //creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";

        String[] args = new String[] { "powershell", creds};
        execRemote(args);
        return creds;
    }

    private void execRemote(String[] arguments) throws IOException {
        ProcessBuilder builder = new ProcessBuilder(arguments);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        doProcessIO(process);
    }

    // Do the IO for a passed process
    private void doProcessIO(Process p) throws IOException {
        p.getOutputStream().close();
        String line;
        System.out.println("Output:");
        BufferedReader stdout = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        while ((line = stdout.readLine()) != null) {
            System.out.println(line);
        }
        stdout.close();
        System.out.println("Error:");
        BufferedReader stderr = new BufferedReader(new InputStreamReader(
                p.getErrorStream()));
        while ((line = stderr.readLine()) != null) {
            System.out.println(line);
        }
        stderr.close();
        System.out.println("Done");
    }

    public static void main(String[] args) throws IOException {
        PropertiesFileReader propReader = new PropertiesFileReader(System.getProperty("user.dir")+"/cred.properties");

        String user = propReader.getPropertyData("user");
        String pass = propReader.getPropertyData("pass");
        String ip_add = propReader.getPropertyData("ip");

        PowerShellSession psSession = new PowerShellSession();
        String credentials = psSession.getCredentials(ip_add, user, pass);
        psSession.targetIpAddress = ip_add;//;

        String cmdd = propReader.getPropertyData("command");//"Get-Culture";
        if(!credentials.equals("")) {

            psSession.exec(cmdd, credentials);

            System.out.println("Finished PowerShell remote session.");

        }
        psSession.close();
    }

}
</code>```

Body:
I have the following code to connect to a remote machine and execute commands.It is working if I create a new session for each Invoke-Command call to the remote machine. I don't want to create a new session each time I use Invoke-Command as that will not scale for thousands of commands on hundreds of machines concurrently and session creation itself is a big overhead. I need a way so that I can reuse the same session object in the $session powershell variable for multiple Invoke-Command calls to the remote machines.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class PowerShellSession {

private static String subModule = "PowerShellSession";
String targetIpAddress;
String username;
String password;

public static Object connectPShellLock = new Object();

public PowerShellSession() {}

public void exec(String cmd, String credentials)  {

    String ex = "Invoke-Command -Session $session -ScriptBlock {" + cmd + "} -Computer " + targetIpAddress;

    String[] args = new String[] { "powershell", ex};
    try {
        execRemote(args);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void close() {
    String command = "Exit-PSSession";
    String[] args = new String[] { "powershell", command};
    try {
        execRemote(args);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private String getCredentials(String domain, String userName,
        String password) throws IOException {
    String creds = "$PlainPassword ='" + password
            + "'; $SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force;"
            + "$mycred = new-object -typename System.Management.Automation.PSCredential('" + userName + "', $SecurePassword);";
    creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";

    String[] args = new String[] { "powershell", creds};
    execRemote(args);
    return creds;
}

private void execRemote(String[] arguments) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(arguments);
    builder.redirectErrorStream(true);
    Process process = builder.start();
    doProcessIO(process);
}

// Do the IO for a passed process
private void doProcessIO(Process p) throws IOException {
    p.getOutputStream().close();
    String line;
    System.out.println("Output:");
    BufferedReader stdout = new BufferedReader(new InputStreamReader(
            p.getInputStream()));
    while ((line = stdout.readLine()) != null) {
        System.out.println(line);
    }
    stdout.close();
    System.out.println("Error:");
    BufferedReader stderr = new BufferedReader(new InputStreamReader(
            p.getErrorStream()));
    while ((line = stderr.readLine()) != null) {
        System.out.println(line);
    }
    stderr.close();
//      System.out.println("Done");
}

public static void main(String[] args) throws IOException {
    PowerShellSession psSession = new PowerShellSession();
    String credentials = psSession.getCredentials("9.120.241.195", "username", "password");
    psSession.targetIpAddress = "9.120.241.195";
    if(!credentials.equals("")) {
        Scanner input = new Scanner(System.in);
        while(true) {
            System.out.print("PS C:\\Windows\\system32> ");
            String cmd = input.nextLine();
            if(cmd.equals("q") || cmd.equals("e") || cmd.equals("quit") || cmd.equals("exit")) break;
            psSession.username = "username";
            psSession.password = "password";
            psSession.exec(cmd, "");
        }
        System.out.println("Finished PowerShell remote session.");
        input.close();
    }
    psSession.close();
}
}


问:
Problem with plugin in zend framework
I have created one plugin that is reside in application/controllers/plugin/view.php and below is its content

```
class Application_Controller_Plugin_View extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $frontController = Zend_Controller_Front::getInstance();
        $view = $frontController->getParam('bootstrap')->getResource('view');
        echo 'erace';
        exit;
        $view->doctype('XHTML1_STRICT');

        $baseUrl = $request->getBaseUrl();
        if (defined('RUNNING_FROM_ROOT')) {
            $baseUrl .= '/public';
            $frontController->setBaseUrl($baseUrl);
        }
      /*  $view->headLink()->appendStylesheet($baseUrl . '/css/main.css');
        $view->headLink()->appendStylesheet($baseUrl . '/css/screen.css', 'screen');
        $view->headLink()->appendStylesheet($baseUrl . '/css/print.css', 'print');*/
    }
}

```

Then I have registered this plugin in bootstrap as follow :

```
protected function _initLayoutHelper()
    {

        $front = Zend_Controller_Front::getInstance();
        $front->registerPlugin(new Application_Controller_Plugin_View());

    }
```

but its give me an error like

```
( ! ) Fatal error: Class 'Application_Controller_Plugin_View' not found in C:\wamp\www\saet_new\application\Bootstrap.php on line 42
```

Please help me.

答:
Is the plugin here:

library/application/controller/plugin/view.php

?

Custom code belongs in the library folder in my opinion, and that path is already defined in index.php

I register my namespaces in the bootstrap as follows:

```<code>$autoLoader = Zend_Loader_Autoloader::getInstance();
$autoLoader->registerNamespace('Custom_');
</code>```

Then library code can be put in the folder library/custom

Title: Problem with plugin in zend framework

Body:
I have created one plugin that is reside in application/controllers/plugin/view.php and below is its content

class Application_Controller_Plugin_View extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $frontController = Zend_Controller_Front::getInstance();
        $view = $frontController->getParam('bootstrap')->getResource('view');
        echo 'erace';
        exit;
        $view->doctype('XHTML1_STRICT');

        $baseUrl = $request->getBaseUrl();
        if (defined('RUNNING_FROM_ROOT')) {
            $baseUrl .= '/public';
            $frontController->setBaseUrl($baseUrl);
        }
      /*  $view->headLink()->appendStylesheet($baseUrl . '/css/main.css');
        $view->headLink()->appendStylesheet($baseUrl . '/css/screen.css', 'screen');
        $view->headLink()->appendStylesheet($baseUrl . '/css/print.css', 'print');*/
    }
}

Then I have registered this plugin in bootstrap as follow :

protected function _initLayoutHelper()
    {

        $front = Zend_Controller_Front::getInstance();
        $front->registerPlugin(new Application_Controller_Plugin_View());

    }

but its give me an error like

( ! ) Fatal error: Class 'Application_Controller_Plugin_View' not found in C:\wamp\www\saet_new\application\Bootstrap.php on line 42

Please help me.

Body:
Is the plugin here:

library/application/controller/plugin/view.php

?

Custom code belongs in the library folder in my opinion, and that path is already defined in index.php

I register my namespaces in the bootstrap as follows:

$autoLoader = Zend_Loader_Autoloader::getInstance();
$autoLoader->registerNamespace('Custom_');

Then library code can be put in the folder library/custom


问:
Constant global user type values in Go
I want to arrange to compute a value that will not change after initialization.

I'd use const, but Go restricts consts to built-in types, IIUC.

So I figured I'd use var, and compute their initial values in init()

```<code>var (
    // ScreenBounds is the visible screen
    ScreenBounds types.Rectangle

    // BoardBounds is the total board space
    BoardBounds  types.Rectangle
)

func init() {
    ScreenBounds := types.RectFromPointSize(
        types.Pt(-ScreenWidth/2, 0),
        types.Pt(ScreenWidth, ScreenHeight))

    BoardBounds := ScreenBounds
    BoardBounds.Max.Y += TankSpeed * TotalFrames
}
</code>```

Which is pretty good - but is there a way to "lock" the values once computed, other than to change the vars to unexported names, and then uses function-accessors to return their values?

答:
No, there is not. Variables are called that because their values can be changed. In Go there is no "final" or similar modifier. Simplicity of the language.

Only way to guard a variable from being changed from the outside is to make it unexported, and yes, then you need exported functions to get their values.

A workaround could be to not use variables but constants. Yes, you can't have struct constants, but if the structs are small, you may use its fields as separate constants, e.g.:

```<code>const (
    ScreenMinX = ScreenWidth / 2
    ScreenMinY = ScreenHeight / 2
    ScreenMaxX = ScreenWidth
    ScreenMaxY = ScreenHeight
)
</code>```

Title: Constant global user type values in Go

Body:
I want to arrange to compute a value that will not change after initialization.

I'd use const, but Go restricts consts to built-in types, IIUC.

So I figured I'd use var, and compute their initial values in init()

var (
    // ScreenBounds is the visible screen
    ScreenBounds types.Rectangle

    // BoardBounds is the total board space
    BoardBounds  types.Rectangle
)

func init() {
    ScreenBounds := types.RectFromPointSize(
        types.Pt(-ScreenWidth/2, 0),
        types.Pt(ScreenWidth, ScreenHeight))

    BoardBounds := ScreenBounds
    BoardBounds.Max.Y += TankSpeed * TotalFrames
}

Which is pretty good - but is there a way to "lock" the values once computed, other than to change the vars to unexported names, and then uses function-accessors to return their values?

Body:
No, there is not. Variables are called that because their values can be changed. In Go there is no "final" or similar modifier. Simplicity of the language.

Only way to guard a variable from being changed from the outside is to make it unexported, and yes, then you need exported functions to get their values.

A workaround could be to not use variables but constants. Yes, you can't have struct constants, but if the structs are small, you may use its fields as separate constants, e.g.:

const (
    ScreenMinX = ScreenWidth / 2
    ScreenMinY = ScreenHeight / 2
    ScreenMaxX = ScreenWidth
    ScreenMaxY = ScreenHeight
)


问:
How to write a string to a cmd prompt using ProcessBuilder in Java?
I have a batch (.bat) program that asks that user to supply a hostname and password. (Two fields) I am using a separate Java application to gather to automate this task and so I need it to enter multiple hostnames at once into the script. However, I am having a hard time accomplishing this goal using ProcessBuilder.
Please take a look at the below code:

This code I have only redirects the input and output to the java process. However, I would solely like to write to the cmd. Please let me know if there is any way. Thanks

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws InterruptedException,
            IOException {
        ProcessBuilder pb = new ProcessBuilder("cmd" ," /k d: && cd DATA\\Virtualization Scripts\\EMC ESXi Grab && Script_Run");
        //inherit IO
        pb.inheritIO();
        Process process = pb.start();
        process.waitFor();
    }
}
```

答:
@Tharriott, as per our discussion, first of all you have to modify a bit your batch script like this. I provide below the code.

```<code>@ECHO OFF
set host=%1
set password=%2

echo Host Name : %host%
echo Password : %password%

"D:\UPSDATA\Virtualization Scripts\EMC ESXi Grab\EMC-ESXi-GRAB-1.3.10\emcgrab.exe" -host %host% -vmsupport -user root -password %password% -case 00000000 -legal -customer UPS -party 00000 -contact user -phone NA -email NA

exit
</code>```

Imagine that the name of the batch script is emc-grab.bat.

Now you have to run the above batch file like this.

:/emc-grab.bat

one example is like this

D:/test/emc-grab.bat abcd.dellemc.com pa$$word99

Now what is next ?

In your java gui program, capture hostname and password, then in the processbuilder class, pass the complete command along with the file name, hostname and password.

I provide below the code snippet.

```<code>String hostNameAndPassword = "captured Host Name"+" "+"captured password";
ProcessBuilder pb = new ProcessBuilder("cmd" ,"some path:/emc-grab.bat "+hostNameAndPassword);
</code>```

Try it, it will solve your problem.

Body:
@Tharriott, as per our discussion, first of all you have to modify a bit your batch script like this. I provide below the code.

@ECHO OFF
set host=%1
set password=%2

echo Host Name : %host%
echo Password : %password%

"D:\UPSDATA\Virtualization Scripts\EMC ESXi Grab\EMC-ESXi-GRAB-1.3.10\emcgrab.exe" -host %host% -vmsupport -user root -password %password% -case 00000000 -legal -customer UPS -party 00000 -contact user -phone NA -email NA

exit

Imagine that the name of the batch script is emc-grab.bat.

Now you have to run the above batch file like this.

:/emc-grab.bat

one example is like this

D:/test/emc-grab.bat abcd.dellemc.com pa$$word99

Now what is next ?

In your java gui program, capture hostname and password, then in the processbuilder class, pass the complete command along with the file name, hostname and password.

I provide below the code snippet.

String hostNameAndPassword = "captured Host Name"+" "+"captured password";
ProcessBuilder pb = new ProcessBuilder("cmd" ,"some path:/emc-grab.bat "+hostNameAndPassword);

Try it, it will solve your problem.