问:
Conditionally extracting outer key-value in a JSON using JsonPath
Here's my JSON:

```<code>{
    "status": false,
    "responseData": [{
        "data": {
            "value": "value",
            "label": "label"
        },
        "type": "HEADING"
    }, {
        "data": {
            "section": "SECTION1",
            "post": {}
        },
        "type": "POST"
    }, {
        "data": {
            "section": "SECTION1",
            "post": {}
        },
        "type": "POST"
    }, {
        "data": {
            "section": "SECTION1",
            "post": {}
        },
        "type": "POST"
    }, {
        "data": {
            "section": "SECTION1",
            "value": "value",
            "label": "label",
            "type": "POSTS_LIST",
            "headerDetails": {
                "value": "value",
                "label": "label"
            },
            "metaData": {
                "params": {
                    "param1": "value1",
                    "param2": "value2"
                }
            }
        },
        "type": "CALL_TO_ACTION"
    }],
    "message": "OK"
}
</code>```

I'm using Jayway JsonPath for data extraction.

Problem: I would like to fetch all the type values (e.g. CALL_TO_ACTION) based on the section name (e.g. SECTION1).

What I tried at https://jsonpath.curiousconcept.com: $.responseData[*].[?(@.section=='SECTION1')].type, but that gives me POSTS_LIST (obviously!), which is the internal type and not the external type attribute I'm looking for.

答:
You want to filter on a child level attribute and then return a parent level attribute.

To be more specific, in the following example ...

```<code>{
    "data": {
        "section": "SECTION1",
        "value": "value",
        "label": "label",
        "type": "POSTS_LIST",
        "headerDetails": {
            "value": "value",
            "label": "label"
        },
        "metaData": {
            "params": {
                "param1": "value1",
                "param2": "value2"
            }
        }
    },
    "type": "CALL_TO_ACTION"
}
</code>```

... the child level attribute is "section": "SECTION1" and the parent level attribute is "type": "CALL_TO_ACTION".

This is not currently supported by JayWay JsonPath though there is an open issue relating to it. You could perhaps upvote the issue and/or consider raising a PR for it.

Alternatively, you'll have to use a JSON deserializer (such as Gson suggested by @Wayne) to deserialize your JSON to a Map (or similar) construct which you can then filter and having found your match walk back up the tree to find the data you wish to retrieve.

Body:
Here's my JSON:

{
    "status": false,
    "responseData": [{
        "data": {
            "value": "value",
            "label": "label"
        },
        "type": "HEADING"
    }, {
        "data": {
            "section": "SECTION1",
            "post": {}
        },
        "type": "POST"
    }, {
        "data": {
            "section": "SECTION1",
            "post": {}
        },
        "type": "POST"
    }, {
        "data": {
            "section": "SECTION1",
            "post": {}
        },
        "type": "POST"
    }, {
        "data": {
            "section": "SECTION1",
            "value": "value",
            "label": "label",
            "type": "POSTS_LIST",
            "headerDetails": {
                "value": "value",
                "label": "label"
            },
            "metaData": {
                "params": {
                    "param1": "value1",
                    "param2": "value2"
                }
            }
        },
        "type": "CALL_TO_ACTION"
    }],
    "message": "OK"
}

I'm using Jayway JsonPath for data extraction.

Problem: I would like to fetch all the type values (e.g. CALL_TO_ACTION) based on the section name (e.g. SECTION1).

What I tried at https://jsonpath.curiousconcept.com: $.responseData[*].[?(@.section=='SECTION1')].type, but that gives me POSTS_LIST (obviously!), which is the internal type and not the external type attribute I'm looking for.

Body:
You want to filter on a child level attribute and then return a parent level attribute.

To be more specific, in the following example ...

{
    "data": {
        "section": "SECTION1",
        "value": "value",
        "label": "label",
        "type": "POSTS_LIST",
        "headerDetails": {
            "value": "value",
            "label": "label"
        },
        "metaData": {
            "params": {
                "param1": "value1",
                "param2": "value2"
            }
        }
    },
    "type": "CALL_TO_ACTION"
}

... the child level attribute is "section": "SECTION1" and the parent level attribute is "type": "CALL_TO_ACTION".

This is not currently supported by JayWay JsonPath though there is an open issue relating to it. You could perhaps upvote the issue and/or consider raising a PR for it.

Alternatively, you'll have to use a JSON deserializer (such as Gson suggested by @Wayne) to deserialize your JSON to a Map (or similar) construct which you can then filter and having found your match walk back up the tree to find the data you wish to retrieve.


来源: stackexchange

问:
close current and open a new openCV window if file modified Python
I was wondering if anyone could help me out a bit with this problem I cannot solve. I am using Pafy to search Youtube from a text file that has a song name written in it and that gets a new song every few minutes.
I am using Watchdog to watch for file modification and when i first run the script, watchdog catches the file modification and runs the pafy and opencv script, but it won't do the same when the following modification occurs.

```<code>#watchdog file change monitoring
class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print ("Received modified event - %s." % event.src_path)
        cv2.destroyAllWindows()

if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='//PLAYING', recursive=False)
    observer.start()
    try:
        while True:
            #read PLAYING.txt
            PLAYING = open('//PLAYING.txt').readline()
            PLAYING = PLAYING[7:]
            print (PLAYING)
            #search youtube based on NowOnAir.txt
            query_string = urllib.parse.urlencode({"search_query" : PLAYING})
            html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
            search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
            link = ('http://www.youtube.com/watch?v=' + search_results[0])
            videoPafy = pafy.new(link)
            best = videoPafy.getbestvideo()
            videompv = best.url

            #opencv youtube video output
            video = cv2.VideoCapture(videompv)

            while(video.isOpened()):
                ret, frame = video.read()
                resize = cv2.resize(frame, (1680, 1050))
                gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)
                result = cv2.addWeighted(image, 0.2, resize, 0.8, 0)
                cv2.namedWindow('frame', 0)
                cv2.resizeWindow('frame', 1680, 1050)
                cv2.imshow('frame', result)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break

            time.sleep(1)

    except KeyboardInterrupt:
        observer.stop()
    observer.join()
</code>```

So, I what I want to happen is, when file gets modified, I want openCV to close the window and open a new one with the new youtube query result.

Any suggestions would be quite welcome, thank You in advance.

答:
If the file is just updated once per track change, then you could check the timestamp of the file for modification and use that to trigger your search.</p>

```<code>import os.path
import time

last_modified  = time.ctime(os.path.getmtime(file))

while True:
    time.sleep(1)
    if last_modified != time.ctime(os.path.getmtime(file)):
       # search for the track on youtube
       last_modified = time.ctime(os.path.getmtime(file))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was wondering if anyone could help me out a bit with this problem I cannot solve. I am using Pafy to search Youtube from a text file that has a song name written in it and that gets a new song every few minutes.
I am using Watchdog to watch for file modification and when i first run the script, watchdog catches the file modification and runs the pafy and opencv script, but it won't do the same when the following modification occurs.

#watchdog file change monitoring
class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print ("Received modified event - %s." % event.src_path)
        cv2.destroyAllWindows()

if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='//PLAYING', recursive=False)
    observer.start()
    try:
        while True:
            #read PLAYING.txt
            PLAYING = open('//PLAYING.txt').readline()
            PLAYING = PLAYING[7:]
            print (PLAYING)
            #search youtube based on NowOnAir.txt
            query_string = urllib.parse.urlencode({"search_query" : PLAYING})
            html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
            search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
            link = ('http://www.youtube.com/watch?v=' + search_results[0])
            videoPafy = pafy.new(link)
            best = videoPafy.getbestvideo()
            videompv = best.url

            #opencv youtube video output
            video = cv2.VideoCapture(videompv)

            while(video.isOpened()):
                ret, frame = video.read()
                resize = cv2.resize(frame, (1680, 1050))
                gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)
                result = cv2.addWeighted(image, 0.2, resize, 0.8, 0)
                cv2.namedWindow('frame', 0)
                cv2.resizeWindow('frame', 1680, 1050)
                cv2.imshow('frame', result)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break

            time.sleep(1)

    except KeyboardInterrupt:
        observer.stop()
    observer.join()

So, I what I want to happen is, when file gets modified, I want openCV to close the window and open a new one with the new youtube query result.

Any suggestions would be quite welcome, thank You in advance.

Body:
If the file is just updated once per track change, then you could check the timestamp of the file for modification and use that to trigger your search.

import os.path
import time

last_modified  = time.ctime(os.path.getmtime(file))

while True:
    time.sleep(1)
    if last_modified != time.ctime(os.path.getmtime(file)):
       # search for the track on youtube
       last_modified = time.ctime(os.path.getmtime(file))


问:
How to Check Whether an Array (or List) Contains Another an Array (List) Using LINQ
I am trying to get the list of files (file is an entity) which has the selected services (service is another entity). The file can have many services.

I tried the following statement, but it does not give the correct results:

```<code>var _serviceTypes = viewModel.SelectedServiceTypes;
// _serviceTypes is an array of integers

var resultsTemp = repository.Files.Where(f => f.Services.Select(s => s.ServiceTypeID).Intersect(_serviceTypes).Any());
</code>```

What am I missing?

EDIT:

_serviceTypes in an array of integers: {int[2]}

The files can have many services, each of which as one service type id (integer)

For instance, a file has two services in it: ambulance (service type id: 3) and hospitalization (service type id: 5). I want to get all the files which have both the services in it.

答:
Some of the following operations should answer your question:

```<code>// requested IDs
var requestedIDs = new List<int>();
// the IDs from one file
var IDsInFile = new List<int>();
if (requestedIDs.Except(IDsInFile).Any())
{
    // at least some requested IDs are not in the file
}
else
{
    // all requested IDs are in the file
}
if (requestedIDs.Intersect(IDsInFile).Any())
{
    // at least some requested IDs are in the file
}
else
{
    // not a single requested ID is in the file
}
</code>```

Since you want every file that contains all of the requested services, the correct query would be

```<code>var _serviceTypes = viewModel.SelectedServiceTypes;
// _serviceTypes is an array of integers

var resultsTemp = repository.Files.Where(f => !_serviceTypes.Except(f.Services.Select(s => s.ServiceTypeID)).Any());
</code>```

Body:
I am trying to get the list of files (file is an entity) which has the selected services (service is another entity). The file can have many services.

I tried the following statement, but it does not give the correct results:

var _serviceTypes = viewModel.SelectedServiceTypes;
// _serviceTypes is an array of integers

var resultsTemp = repository.Files.Where(f => f.Services.Select(s => s.ServiceTypeID).Intersect(_serviceTypes).Any());

What am I missing?

EDIT:

_serviceTypes in an array of integers: {int[2]}

The files can have many services, each of which as one service type id (integer)

For instance, a file has two services in it: ambulance (service type id: 3) and hospitalization (service type id: 5). I want to get all the files which have both the services in it.

Body:
Some of the following operations should answer your question:

// requested IDs
var requestedIDs = new List<int>();
// the IDs from one file
var IDsInFile = new List<int>();
if (requestedIDs.Except(IDsInFile).Any())
{
    // at least some requested IDs are not in the file
}
else
{
    // all requested IDs are in the file
}
if (requestedIDs.Intersect(IDsInFile).Any())
{
    // at least some requested IDs are in the file
}
else
{
    // not a single requested ID is in the file
}

Since you want every file that contains all of the requested services, the correct query would be

var _serviceTypes = viewModel.SelectedServiceTypes;
// _serviceTypes is an array of integers

var resultsTemp = repository.Files.Where(f => !_serviceTypes.Except(f.Services.Select(s => s.ServiceTypeID)).Any());


问:
mySQL DB Desgin
In my application I have different categories that users can post their transactions as.
Example: Food, Shopping, Movies, etc..
I want the user to be able to edit these categories and add/remove categories.
What is the best way to store this information in a database.

A categories table with the category and corresponding user? Then I can query the uid and get all of their categories.

User table w/ a category field and seperate the categories by comma. Then I can query user and seperate their categories into an array w/ explode or something along those lines.

OR an idea I have not even thought of.

答:
Don't separate entries by comma in a database field if you might use them as single values (e.g. just one category).

Read about database normalization. There are cases when you don't want to go all the way normalizing, but concatenating distinct values with comma doesn't belong into this category.

Don't fear long tables. Databases are usually optimized for this. If it gets slow, create an index or use another optimizing technique.

Option 1 is the answer.

ContentLicense: CC BY-SA 2.5

Title: mySQL DB Desgin

OwnerDisplayName: Olaf


问:
What are five things you hate about your favorite language?
There's been a cluster of Perl-hate on Stack Overflow lately, so I thought I'd bring my "Five things you hate about your favorite language" question to Stack Overflow. Take your favorite language and tell me five things you hate about it. Those might be things that just annoy you, admitted design flaws, recognized performance problems, or any other category. You just have to hate it, and it has to be your favorite language.

Don't compare it to another language, and don't talk about languages that you already hate. Don't talk about the things you like in your favorite language. I just want to hear the things that you hate but tolerate so you can use all of the other stuff, and I want to hear it about the language you wished other people would use.

I ask this whenever someone tries to push their favorite language on me, and sometimes as an interview question. If someone can't find five things to hate about his favorite tool, he doesn't know it well enough to either advocate it or pull in the big dollars using it. He hasn't used it in enough different situations to fully explore it. He's advocating it as a culture or religion, which means that if I don't choose his favorite technology, I'm wrong.

I don't care that much which language you use. Don't want to use a particular language? Then don't. You go through due diligence to make an informed choice and still don't use it? Fine. Sometimes the right answer is "You have a strong programming team with good practices and a lot of experience in Bar. Changing to Foo would be stupid."

This is a good question for code reviews too. People who really know a codebase will have all sorts of suggestions for it, and those who don't know it so well have non-specific complaints. I ask things like "If you could start over on this project, what would you do differently?" In this fantasy land, users and programmers get to complain about anything and everything they don't like. "I want a better interface", "I want to separate the model from the view", "I'd use this module instead of this other one", "I'd rename this set of methods", or whatever they really don't like about the current situation. That's how I get a handle on how much a particular developer knows about the codebase. It's also a clue about how much of the programmer's ego is tied up in what he's telling me.

Hate isn't the only dimension of figuring out how much people know, but I've found it to be a pretty good one. The things that they hate also give me a clue how well they are thinking about the subject.

答:
Lua:

The built-in error system is absolutely horrendous

You can implement a try-catch system by modifying the Lua interpreter; but it has no compatibility with the errors that are thrown by the built in functions.

The fact they have __newindex instead of __setindex as the setter

... and __newindex is only fired when the key doesn't already exist.  If it does, no metamethod is called at all.

No good type comparison system.

There's the type() function but it only handles the basic types (all tables are tables).  It really needs to have a metamethod for type comparisons.  I've implemented this before with an 'is' operator and a __type metamethod and it works really nicely.

It's a bitch to define new keywords.

You can do it, but the code inside Lua isn't well documented so it's kind of trial and error to find out how to get the result you want.  This is a major issue when you want to implement the things I mentioned above yourself (not so much __setindex though, that's an easy modification).

I can't use it in a web browser.

Yeah not really a problem with the language itself, but damn, would I love to be able to use Lua instead of Javascript... :)

OwnerDisplayName: brian d foy

LastEditorDisplayName: brian d foy


问:
Python: Best way to reference file one level up in directory?
I'm a Python newbie and I'm running into a problem that I feel like should have a relatively straight forward answer that I can't quite figure out.

I need to do it this way for an assignment as our teacher wants our GitHub folder to contain all the code in one folder and all of the images in another folder.

Since I will be in the Code folder when running the Python file, is there a way I can reference the Image Folder? Locally, I know I can just put the full path, but because this will be done through command line for GitHub, I wasn't sure what the full path even looked like to reference that folder.

```<code>+ Main GitHub Directory
    + Code Folder
       -My Python File
    + Image Folder
       -Images I want to use
</code>```

This is just a sample program of what I would like to do:

```<code>from PIL import Image
image = Image.open('WeatherIcons/Code32.PNG')
image.show()
</code>```

This will work if 'WeatherIcons' is a subfolder of the Code Folder, but not when it is at the same level. Any creative solutions to get around this?

Thank you!

答:
```<code>#get parent directory:
import os
parentDirectory = os.path.abspath(os.path.join(os.getcwd(), os.pardir))

#now open your image
from PIL import Image
image = Image.open(os.path.join(parentDirectory, 'Image_Folder', 'Code32.PNG'))
image.show()
</code>```

Body:
I'm a Python newbie and I'm running into a problem that I feel like should have a relatively straight forward answer that I can't quite figure out.

I need to do it this way for an assignment as our teacher wants our GitHub folder to contain all the code in one folder and all of the images in another folder.

Since I will be in the Code folder when running the Python file, is there a way I can reference the Image Folder? Locally, I know I can just put the full path, but because this will be done through command line for GitHub, I wasn't sure what the full path even looked like to reference that folder.

+ Main GitHub Directory
    + Code Folder
       -My Python File
    + Image Folder
       -Images I want to use

This is just a sample program of what I would like to do:

from PIL import Image
image = Image.open('WeatherIcons/Code32.PNG')
image.show()

This will work if 'WeatherIcons' is a subfolder of the Code Folder, but not when it is at the same level. Any creative solutions to get around this?

Thank you!


问:
Multiple rows out of a single record
lets say that e.g if i did SELECT * FROM X i'd get

```<code>A1, A2, A3, A4, A5, A6, A7
</code>```

is it possible to do a query that for each record returns

```<code>A1, A2, A3
A1, A2, A4
A1, A2, A5
A1, A2, A6
A1, A2, A7
</code>```

????

My actual problem ( and this is just additional information, not required to answer the question ) --> i have a db about football matches so i have players etc but the table matches are like this:

```<code>homeplayer1 (fk)
homeplayer2 (fk)
.
.
.
homeplayerN (fk)
</code>```

and same for away players but i'm working on a multidimiensional db implementation that requires to have only one player associated per match so it'd be 22 records per match to fit the 22 players.

I'm using postgresql.

答:
Let's assume that some column defines the ordering; I'll call it ord:

```<code>with t as (
      select x.*, row_number() over (order by ord) as seqnum
      from x
     )
select t1.col, t2.col, t3.col
from t t1 join
     t t2
     on t1.seqnum = 1 and t2.seqnum = 2 join
     t t3
     on t3.seqnum > 2;
</code>```

You may want to ask another question about your actual problem, which looks a bit different from what you asked in this question.

Title: Multiple rows out of a single record

Body:
lets say that e.g if i did SELECT * FROM X i'd get

A1, A2, A3, A4, A5, A6, A7

is it possible to do a query that for each record returns

A1, A2, A3
A1, A2, A4
A1, A2, A5
A1, A2, A6
A1, A2, A7

????

My actual problem ( and this is just additional information, not required to answer the question ) --> i have a db about football matches so i have players etc but the table matches are like this:

homeplayer1 (fk)
homeplayer2 (fk)
.
.
.
homeplayerN (fk)

and same for away players but i'm working on a multidimiensional db implementation that requires to have only one player associated per match so it'd be 22 records per match to fit the 22 players.

I'm using postgresql.

Body:
Let's assume that some column defines the ordering; I'll call it ord:

with t as (
      select x.*, row_number() over (order by ord) as seqnum
      from x
     )
select t1.col, t2.col, t3.col
from t t1 join
     t t2
     on t1.seqnum = 1 and t2.seqnum = 2 join
     t t3
     on t3.seqnum > 2;

You may want to ask another question about your actual problem, which looks a bit different from what you asked in this question.


问:
How to use a name field instead of id in attrs in Odoo 9?
Is it possible to use project name instead of id in my example?

<field name="my_field"
       attrs="{'invisible': [('project_id', '!=', 2)], 'required': [('project_id', '=', 2)]}"/>
```

I have tried with [('project_id.name', '!=', 'TEST PROJECT')] but it's not working.

答:
You can create a related field in order to use it in the attrs attribute

project_name = fields.Char(
    related='product_id.name',
)
```

<pre class="lang-xml prettyprint-override"><code><field name="project_name" invisible="1"/>
<field name="my_field"
       attrs="{'invisible': [('project_name', '!=', 'TEST PROJECT')], 'required': [('project_name', '=', 'TEST PROJECT')]}"/>
</code>```

Body:
Is it possible to use project name instead of id in my example?

<field name="my_field"
       attrs="{'invisible': [('project_id', '!=', 2)], 'required': [('project_id', '=', 2)]}"/>

I have tried with [('project_id.name', '!=', 'TEST PROJECT')] but it's not working.

Body:
You can create a related field in order to use it in the attrs attribute

project_name = fields.Char(
    related='product_id.name',
)

<field name="project_name" invisible="1"/>
<field name="my_field"
       attrs="{'invisible': [('project_name', '!=', 'TEST PROJECT')], 'required': [('project_name', '=', 'TEST PROJECT')]}"/>


问:
How to use chai's expect in nightwatch.js tests
I do integration tests with nightwatch. Some UI automation, which works fine. In the end I want to check using a Rest API, if the results of the UI operations are right. I try to use chai there, as chai is inbuild into nightwatch. Out of the box nightwatch only supports expect.element('#element')..., but I need expect(true).to.be.true style.

This is (part) of my test file:

```<code>const { expect } = require('chai');

module.exports = {
    'Add Rules (Tester 1)' : browser => {
         ... some tests
    }
    after: browser => {
        let username = 'username';
        let password = 'xxxxxxxx';

        fetchRulesFromJira({ browser, username, password }).then(rules => {
            expect(rules.length).to.equal(2);
            browser.end();
        });
    }
};
</code>```

If the expect fails the output is

(node:3594) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): AssertionError: expected 3 to equal 2

Somehow useful but not nice. If the test succeeds then there is no output.

How can I make nightwatch.js print the results, or any other way to have a more standard output of test results?

答:
My current solution ist to encapsulate the expect in try/catch and invoke an error with nightwatch.

```<code>const { expect } = require('chai');

module.exports = {
    'Add Rules (Tester 1)' : browser => {
         ... some tests
    }
    after: browser => {
        let username = 'username';
        let password = 'xxxxxxxx';

        fetchRulesFromJira({ browser, username, password }).then(rules => {
            try {
                expect(rules.length).to.equal(2);
            } catch(error) {
                browser.assert.fail(error);
            }

            browser.end();
        });
    }
};
</code>```

That doesn't look perfect, but the output is quite ok.

Body:
I do integration tests with nightwatch. Some UI automation, which works fine. In the end I want to check using a Rest API, if the results of the UI operations are right. I try to use chai there, as chai is inbuild into nightwatch. Out of the box nightwatch only supports expect.element('#element')..., but I need expect(true).to.be.true style.

This is (part) of my test file:

const { expect } = require('chai');

module.exports = {
    'Add Rules (Tester 1)' : browser => {
         ... some tests
    }
    after: browser => {
        let username = 'username';
        let password = 'xxxxxxxx';

        fetchRulesFromJira({ browser, username, password }).then(rules => {
            expect(rules.length).to.equal(2);
            browser.end();
        });
    }
};

If the expect fails the output is

(node:3594) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): AssertionError: expected 3 to equal 2

Somehow useful but not nice. If the test succeeds then there is no output.

How can I make nightwatch.js print the results, or any other way to have a more standard output of test results?

Body:
My current solution ist to encapsulate the expect in try/catch and invoke an error with nightwatch.

const { expect } = require('chai');

module.exports = {
    'Add Rules (Tester 1)' : browser => {
         ... some tests
    }
    after: browser => {
        let username = 'username';
        let password = 'xxxxxxxx';

        fetchRulesFromJira({ browser, username, password }).then(rules => {
            try {
                expect(rules.length).to.equal(2);
            } catch(error) {
                browser.assert.fail(error);
            }

            browser.end();
        });
    }
};

That doesn't look perfect, but the output is quite ok.


问:
java Array maxSpan
Can anyone please explain the question and logic. I am not able to understand:

Consider the leftmost and righmost appearances of some value in an
  array. We'll say that the "span" is the number of elements between the
  two inclusive. A single value has a span of 1. Returns the largest
  span found in the given array. (Efficiency is not a priority.)

```<code>maxSpan([1, 2, 1, 1, 3]) → 4
maxSpan([1, 4, 2, 1, 4, 1, 4]) → 6
maxSpan([1, 4, 2, 1, 4, 4, 4]) → 6
</code>```

答:
https://github.com/mirandaio/codingbat/blob/master/java/array-3/maxSpan.java

If you refer to the code hosted on GitHub at the link above.
As you can read in the documentation, the maxSpan function returns the (max) numbers of elements between two occurrences of a number.

For example:

maxSpan([1, 2, 1, 1, 3]) → 4

the first '1' and the last '1' elements in the array generate the maxSpan value of 4.

Title: java Array maxSpan

Body:
Can anyone please explain the question and logic. I am not able to understand:

Consider the leftmost and righmost appearances of some value in an
  array. We'll say that the "span" is the number of elements between the
  two inclusive. A single value has a span of 1. Returns the largest
  span found in the given array. (Efficiency is not a priority.)

maxSpan([1, 2, 1, 1, 3]) → 4
maxSpan([1, 4, 2, 1, 4, 1, 4]) → 6
maxSpan([1, 4, 2, 1, 4, 4, 4]) → 6


问:
1C Bitrix: property custom type
We have "Date/Time" property type in Bitrix. But there is no "Time" type.

I tried to google it but I get a bunch of code without comments and there is no explanations where I need to put it.

I also tried to search in Bitrix Market place but without success too.

Please help me to understand how to implement "Time" type for infoblock properties.

答: If you need just time - fastest workaround is to save time as usual string property.</p>

Title: 1C Bitrix: property custom type


问:
telerik gridview in silverlight using mvvm
I am using teleriks gridview in an mvvm silverlight project. I am struggling to get the editing of a row working. If I double click a cell I am able to change the text of that row. I have a command for a save button. but when I look at my ObservableCollection prog I do not see the changes. so I went and changed everything from observableCollection to just a generic list and now im struggling binding the data to the grid. With the observable collection I am able to initially bind the data to the grid. </p>

```<code>    private ObservableCollection<Program> _programResults;
    public ObservableCollection<Program> ProgramResults
    {
        get { return _programResults; }
        set { SetObject(ref _programResults, value, "ProgramResults"); }
    }

<telerik:RadGridView Margin="5,5,5,5" ShowGroupPanel="False" Height="300" ItemsSource="{Binding ProgramResults, Mode=TwoWay}" SelectedItem="{Binding SelectedProgram, Mode=TwoWay}" AutoGenerateColumns="False" VerticalAlignment="Top">
                <telerik:RadGridView.Columns>
                    <telerik:GridViewDataColumn Header="Program ID" DataMemberBinding="{Binding ProgramResults.ProgramID}" MinWidth="300"></telerik:GridViewDataColumn>
                    <telerik:GridViewDataColumn Header="Program Name" DataMemberBinding="{Binding Name}" MinWidth="300"></telerik:GridViewDataColumn>
            </telerik:RadGridView>
</code>```

答: We have wound up using a dialog on a selected item and updating the data through another view. Getting the selected item through binding is easy enough and this seems to solve our problems</p>

Body:
I am using teleriks gridview in an mvvm silverlight project. I am struggling to get the editing of a row working. If I double click a cell I am able to change the text of that row. I have a command for a save button. but when I look at my ObservableCollection prog I do not see the changes. so I went and changed everything from observableCollection to just a generic list and now im struggling binding the data to the grid. With the observable collection I am able to initially bind the data to the grid.

    private ObservableCollection<Program> _programResults;
    public ObservableCollection<Program> ProgramResults
    {
        get { return _programResults; }
        set { SetObject(ref _programResults, value, "ProgramResults"); }
    }

<telerik:RadGridView Margin="5,5,5,5" ShowGroupPanel="False" Height="300" ItemsSource="{Binding ProgramResults, Mode=TwoWay}" SelectedItem="{Binding SelectedProgram, Mode=TwoWay}" AutoGenerateColumns="False" VerticalAlignment="Top">
                <telerik:RadGridView.Columns>
                    <telerik:GridViewDataColumn Header="Program ID" DataMemberBinding="{Binding ProgramResults.ProgramID}" MinWidth="300"></telerik:GridViewDataColumn>
                    <telerik:GridViewDataColumn Header="Program Name" DataMemberBinding="{Binding Name}" MinWidth="300"></telerik:GridViewDataColumn>
            </telerik:RadGridView>


问:
Mysql get row number
I've a table like this

```<code>+------+----------+------------+
|   id |  1_value |   2_value  |
+------+----------+------------+
|    3 |   foo1   |   other    |
|   10 |   fooX   |   stuff    |
|   13 |   fooJ   |   here     |
|   22 |   foo7   |   and      |
|   31 |   foou   |   here     |
+------+----------+------------+
</code>```

What I want to get is to have the row number

I've tried to do something like this

```<code>SELECT  id, @curRow := @curRow + 1 AS row_number
FROM    table
JOIN    (SELECT @curRow := 0) r
</code>```

and it work indeed...

```<code>+------+--------------+
|   id |  row_number  |
+------+--------------+
|    3 |   1          |
|   10 |   2          |
|   13 |   3          |
|   22 |   4          |
|   31 |   5          |
+------+--------------+
</code>```

but what if I try to select a specific row?

```<code>SELECT  id, @curRow := @curRow + 1 AS row_number
FROM    srwk_esp_registration
JOIN    (SELECT @curRow := 0) r
WHERE ID = 22
</code>```

In this case, row_number is 1, but it should be 4.

How can I acheive this?

答:
Try with Sub - query:</p>

```<code>SELECT *
FROM (
    SELECT id,
        @curRow := @curRow + 1 AS row_number
    FROM srwk_esp_registration
    JOIN (
        SELECT @curRow := 0
        ) r
    ) sub
WHERE sub.ID = 22
</code>```

Title: Mysql get row number

Body:
I've a table like this

+------+----------+------------+
|   id |  1_value |   2_value  |
+------+----------+------------+
|    3 |   foo1   |   other    |
|   10 |   fooX   |   stuff    |
|   13 |   fooJ   |   here     |
|   22 |   foo7   |   and      |
|   31 |   foou   |   here     |
+------+----------+------------+

What I want to get is to have the row number

I've tried to do something like this

SELECT  id, @curRow := @curRow + 1 AS row_number
FROM    table
JOIN    (SELECT @curRow := 0) r

and it work indeed...

+------+--------------+
|   id |  row_number  |
+------+--------------+
|    3 |   1          |
|   10 |   2          |
|   13 |   3          |
|   22 |   4          |
|   31 |   5          |
+------+--------------+

but what if I try to select a specific row?

SELECT  id, @curRow := @curRow + 1 AS row_number
FROM    srwk_esp_registration
JOIN    (SELECT @curRow := 0) r
WHERE ID = 22

In this case, row_number is 1, but it should be 4.

How can I acheive this?

Body:
Try with Sub - query:

SELECT *
FROM (
    SELECT id,
        @curRow := @curRow + 1 AS row_number
    FROM srwk_esp_registration
    JOIN (
        SELECT @curRow := 0
        ) r
    ) sub
WHERE sub.ID = 22

ContentLicense: CC BY-SA 4.0


问:
How to send data to node js server with ajax
I'm trying to read data sent to node.js server.

Client side:

```<code>const sendToDB =(date)=> {
  var xhttp = new XMLHttpRequest();
  var d = JSON.stringify(date);
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(d);
    }
  };
  xhttp.open("POST", "api/info", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(d);
}
</code>```

and the server:

```<code>var http = require('http');
var server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  req.on('data', function (chunk) {
    console.log(req.body.date);
  });
  res.end();
});
server.listen(3001);
</code>```

how to receive data sent with xhttp.send(d) in node js server ?

答:
you should use the header "Content-Type", "application/json" as you send some json data.
make sure you send a such an object :

```<code>{
  date: {
    foo: bar
  }
}
</code>```

as your server is expecting it in the body req.body.date

Body:
I'm trying to read data sent to node.js server.

Client side:

const sendToDB =(date)=> {
  var xhttp = new XMLHttpRequest();
  var d = JSON.stringify(date);
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(d);
    }
  };
  xhttp.open("POST", "api/info", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(d);
}

and the server:

var http = require('http');
var server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  req.on('data', function (chunk) {
    console.log(req.body.date);
  });
  res.end();
});
server.listen(3001);

how to receive data sent with xhttp.send(d) in node js server ?

Body:
you should use the header "Content-Type", "application/json" as you send some json data.
make sure you send a such an object :

{
  date: {
    foo: bar
  }
}

as your server is expecting it in the body req.body.date


问:
JavaFx buttons click in order then play
I am looking to have buttons play in the order in which they are clicked. For example, if I click buttons 3, 4, and 6 I would like to then click a "play" button and this button then clicks the same pattern I clicked.</p>

答:
Here is a crude example of how to implement this. TimeLine and SequentialTransitions are the key. Comments are in the code.

```<code>import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.SequentialTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication57 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        List<ToggleButton> order = new ArrayList();//The buttons will be added to see ArrayList as they are pressed. ArrayList maintains order

        ToggleButton btn4 = new ToggleButton();
        btn4.setText("btn4");
        btn4.setOnAction(actionEvent ->
        {
            btn4.setSelected(false);//When you selected a ToggleButton it stays pressed until it is pressed again. So we use code to unpress it.
            order.add(btn4);
        });

        ToggleButton btn3 = new ToggleButton();
        btn3.setText("btn3'");
        btn3.setOnAction(actionEvent ->
        {
            btn3.setSelected(false);//When you selected a ToggleButton it stays pressed until it is pressed again. So we use code to unpress it.
            order.add(btn3);
        });

        ToggleButton btn2 = new ToggleButton();
        btn2.setText("btn2");
        btn2.setOnAction(actionEvent ->
        {
            btn2.setSelected(false);//When you selected a ToggleButton it stays pressed until it is pressed again. So we use code to unpress it.
            order.add(btn2);
        });

        ToggleButton btn1 = new ToggleButton();
        btn1.setText("btn1");
        btn1.setOnAction(actionEvent ->
        {
            btn1.setSelected(false);//When you selected a ToggleButton it stays pressed until it is pressed again. So we use code to unpress it.
            order.add(btn1);
        });

        Button btnPlay = new Button("play");
        btnPlay.setOnAction(actionEvent ->
        {
            List<Timeline> timeLines = new ArrayList();//This List will hold the TimeLines so that it can be used later to play the animation in order.

            for (ToggleButton tempToggleButton : order)//Create a press animation and a release animation for each ToggleButton in the List order
            {
                KeyFrame pressButton = new KeyFrame(Duration.seconds(1),
                        (kfActionEvent) ->
                {
                    System.out.println(tempToggleButton.getText() + "Selected!");
                    tempToggleButton.setSelected(true);
                });
                Timeline pressTimeline = new Timeline();
                pressTimeline.getKeyFrames().addAll(pressButton);
                timeLines.add(pressTimeline);

                KeyFrame releaseButton = new KeyFrame(Duration.seconds(1),
                        (kfActionEvent) ->
                {
                    System.out.println(tempToggleButton.getText() + "Unselected!");
                    tempToggleButton.setSelected(false);
                });
                Timeline releaseTimeline = new Timeline();
                releaseTimeline.getKeyFrames().addAll(releaseButton);
                timeLines.add(releaseTimeline);
            }

            SequentialTransition sequentialTransition = new SequentialTransition();
            sequentialTransition.getChildren().addAll(timeLines);//Add all the Timelines created to a SequentialTransition
            sequentialTransition.play();
            sequentialTransition.setOnFinished(stActionEvent -> {
                timeLines.clear();//Once done, clear the animations
            });

        });

        VBox root = new VBox();
        root.getChildren().addAll(btn1, btn2, btn3, btn4, btnPlay);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}
</code>```

Title: JavaFx buttons click in order then play

Body:
Here is a crude example of how to implement this. TimeLine and SequentialTransitions are the key. Comments are in the code.

import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.SequentialTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication57 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        List<ToggleButton> order = new ArrayList();//The buttons will be added to see ArrayList as they are pressed. ArrayList maintains order

        ToggleButton btn4 = new ToggleButton();
        btn4.setText("btn4");
        btn4.setOnAction(actionEvent ->
        {
            btn4.setSelected(false);//When you selected a ToggleButton it stays pressed until it is pressed again. So we use code to unpress it.
            order.add(btn4);
        });

        ToggleButton btn3 = new ToggleButton();
        btn3.setText("btn3'");
        btn3.setOnAction(actionEvent ->
        {
            btn3.setSelected(false);//When you selected a ToggleButton it stays pressed until it is pressed again. So we use code to unpress it.
            order.add(btn3);
        });

        ToggleButton btn2 = new ToggleButton();
        btn2.setText("btn2");
        btn2.setOnAction(actionEvent ->
        {
            btn2.setSelected(false);//When you selected a ToggleButton it stays pressed until it is pressed again. So we use code to unpress it.
            order.add(btn2);
        });

        ToggleButton btn1 = new ToggleButton();
        btn1.setText("btn1");
        btn1.setOnAction(actionEvent ->
        {
            btn1.setSelected(false);//When you selected a ToggleButton it stays pressed until it is pressed again. So we use code to unpress it.
            order.add(btn1);
        });

        Button btnPlay = new Button("play");
        btnPlay.setOnAction(actionEvent ->
        {
            List<Timeline> timeLines = new ArrayList();//This List will hold the TimeLines so that it can be used later to play the animation in order.

            for (ToggleButton tempToggleButton : order)//Create a press animation and a release animation for each ToggleButton in the List order
            {
                KeyFrame pressButton = new KeyFrame(Duration.seconds(1),
                        (kfActionEvent) ->
                {
                    System.out.println(tempToggleButton.getText() + "Selected!");
                    tempToggleButton.setSelected(true);
                });
                Timeline pressTimeline = new Timeline();
                pressTimeline.getKeyFrames().addAll(pressButton);
                timeLines.add(pressTimeline);

                KeyFrame releaseButton = new KeyFrame(Duration.seconds(1),
                        (kfActionEvent) ->
                {
                    System.out.println(tempToggleButton.getText() + "Unselected!");
                    tempToggleButton.setSelected(false);
                });
                Timeline releaseTimeline = new Timeline();
                releaseTimeline.getKeyFrames().addAll(releaseButton);
                timeLines.add(releaseTimeline);
            }

            SequentialTransition sequentialTransition = new SequentialTransition();
            sequentialTransition.getChildren().addAll(timeLines);//Add all the Timelines created to a SequentialTransition
            sequentialTransition.play();
            sequentialTransition.setOnFinished(stActionEvent -> {
                timeLines.clear();//Once done, clear the animations
            });

        });

        VBox root = new VBox();
        root.getChildren().addAll(btn1, btn2, btn3, btn4, btnPlay);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}


问:
Running time of querying a particular document from a collection in Firebase Cloud Firestore
I am using Google Cloud Firestore for storing the Data. Assume I have a simple collection of cities.

Assume I have 10,000 City Documents stored in my cities Collection. What is the Running time for querying a document with a particular Id (Ex : "city_123"). Is it constant in time or it is comparable to the size of the Documents ?

答:
The time for querying a Collection that contains 10,000 documents is constant but the transfer time can never be constant. It depends on the size of the document that is queried. Another important factor is the bandwidth that the user has on his device. Both are contributing to the time that will take to query that document.

To reduce the time, i suggest you reduce the amount of data by filtering using one of the filtering methods. Here is the official documentation.


问:
Execute Docker Run and check parameter is not empty
How do I check if the parameter ENV  was passed while executing the docker run.

I want to display an error message if the paramenter is not passed.

Thanks

答:
if its to inspect env on running container you can use docker inspect --format '{{ index (index .Config.Env) 0 }}' $CONTAINER_ID
 the 0 number is represent the number of how many env the container is using.. in this case it would print the first env . .


问:
Fast binary parser algorithm

I'm writing a parser for binary files. The data is stored in consecutive 32 bit records. The files only have to be read once and as this is done it is fed into the analysis algorithm.

Now I am reading the file in chunks of 1024 records to avoid as much of the overhead from calling fread more frequently than necessary as possible. In the example below I use oflcorrection, timetag and channel as outputs for the algorithms and use the bool return value to check if the algorithm should stop. Also note that not all the records contain photons just those with positive values.

With this approach I can process  at up to 0.5GBps or 1.5 GBps  if I use the threaded version of the algorithms which break the file into pieces. I know my SSD can read at least a 40% faster. I was thinking of using SIMD to parse several records in parallel but I don't know how to do it with the conditional return clauses.

Do you know any other approach that would allow me to combine chunked reading and SIMD? Is there in general a better way of doing it?

Thanks

P.S. The records correspond to either photons arriving to detectors after going through a beam splitter or a special record that indicates an overflow condition. The latter is needed because Timetags are stored with picosecond resolution in uint64_t.

```<code> static inline bool next_photon(FILE* filehandle, uint64_t * RecNum,
                               uint64_t StopRecord, record_buf_t *buffer,
                               uint64_t *oflcorrection, uint64_t *timetag, int *channel)
{
    pop_record:
    while (__builtin_unpredictable(buffer->head < RECORD_CHUNK)) { // still have records on buffer
        ParseHHT2_HH2(buffer->records[buffer->head], channel, timetag, oflcorrection);
        buffer->head++;
        (*RecNum)++;

        if (*RecNum >= StopRecord) { // run out of records
            return false;
        }

        if (*channel >= 0) { // found a photon
            return true;
        }
    }
    // run out of buffer
    buffer->head = 0;
    fread(buffer->records, RECORD_CHUNK, sizeof(uint32_t), filehandle);
    goto pop_record;
}
</code>```

Please find below the parsing function. Keep in mind that I can't do anything about the file format. Thanks again, Guillem.

```<code>static inline void ParseHHT2_HH2(uint32_t record, int *channel,
                                 uint64_t *timetag, uint64_t *oflcorrection)
{
    const uint64_t T2WRAPAROUND_V2 = 33554432;
    union{
        uint32_t   allbits;
        struct{ unsigned timetag  :25;
            unsigned channel  :6;
            unsigned special  :1;
        } bits;
    } T2Rec;

    T2Rec.allbits = record;

    if(T2Rec.bits.special) {
        if(T2Rec.bits.channel==0x3F) {  //an overflow record
            if(T2Rec.bits.timetag!=0) {
                *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
            }
            else {  // if it is zero it is an old style single overflow
                *oflcorrection += T2WRAPAROUND_V2;  //should never happen with new Firmware!
            }
            *channel = -1;
        } else if(T2Rec.bits.channel == 0) {  //sync
            *channel = 0;
        } else if(T2Rec.bits.channel<=15) {  //markers
            *channel = -2;
        }
    } else {//regular input channel
        *channel = T2Rec.bits.channel + 1;
    }
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}
</code>```

I came up with an almost branchless parsing function, but it doesn't produce any speed up.

```<code>if(T2Rec.bits.channel==0x3F) {  //an overflow record
        *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
    }
    *channel = (!T2Rec.bits.special) * (T2Rec.bits.channel + 1) - T2Rec.bits.special * T2Rec.bits.channel;
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}
</code>```

答:
That speeding the data analysis by parallelizing it has such a dramatic effect on your program's throughput shows that the data analysis cost is of the same order of magnitude as the I/O cost.  Therefore, if you want to improve its throughput to be closer to the limit imposed by your available I/O bandwidth, the best course of action would probably be to perform analysis and I/O in parallel.

You can do that by maintaining two separate I/O buffers, processing one while you read into the other, and then flipping.

Title: Fast binary parser algorithm

Body:
I'm writing a parser for binary files. The data is stored in consecutive 32 bit records. The files only have to be read once and as this is done it is fed into the analysis algorithm.

Now I am reading the file in chunks of 1024 records to avoid as much of the overhead from calling fread more frequently than necessary as possible. In the example below I use oflcorrection, timetag and channel as outputs for the algorithms and use the bool return value to check if the algorithm should stop. Also note that not all the records contain photons just those with positive values.

With this approach I can process  at up to 0.5GBps or 1.5 GBps  if I use the threaded version of the algorithms which break the file into pieces. I know my SSD can read at least a 40% faster. I was thinking of using SIMD to parse several records in parallel but I don't know how to do it with the conditional return clauses.

Do you know any other approach that would allow me to combine chunked reading and SIMD? Is there in general a better way of doing it?

Thanks

P.S. The records correspond to either photons arriving to detectors after going through a beam splitter or a special record that indicates an overflow condition. The latter is needed because Timetags are stored with picosecond resolution in uint64_t.

 static inline bool next_photon(FILE* filehandle, uint64_t * RecNum,
                               uint64_t StopRecord, record_buf_t *buffer,
                               uint64_t *oflcorrection, uint64_t *timetag, int *channel)
{
    pop_record:
    while (__builtin_unpredictable(buffer->head < RECORD_CHUNK)) { // still have records on buffer
        ParseHHT2_HH2(buffer->records[buffer->head], channel, timetag, oflcorrection);
        buffer->head++;
        (*RecNum)++;

        if (*RecNum >= StopRecord) { // run out of records
            return false;
        }

        if (*channel >= 0) { // found a photon
            return true;
        }
    }
    // run out of buffer
    buffer->head = 0;
    fread(buffer->records, RECORD_CHUNK, sizeof(uint32_t), filehandle);
    goto pop_record;
}

Please find below the parsing function. Keep in mind that I can't do anything about the file format. Thanks again, Guillem.

static inline void ParseHHT2_HH2(uint32_t record, int *channel,
                                 uint64_t *timetag, uint64_t *oflcorrection)
{
    const uint64_t T2WRAPAROUND_V2 = 33554432;
    union{
        uint32_t   allbits;
        struct{ unsigned timetag  :25;
            unsigned channel  :6;
            unsigned special  :1;
        } bits;
    } T2Rec;

    T2Rec.allbits = record;

    if(T2Rec.bits.special) {
        if(T2Rec.bits.channel==0x3F) {  //an overflow record
            if(T2Rec.bits.timetag!=0) {
                *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
            }
            else {  // if it is zero it is an old style single overflow
                *oflcorrection += T2WRAPAROUND_V2;  //should never happen with new Firmware!
            }
            *channel = -1;
        } else if(T2Rec.bits.channel == 0) {  //sync
            *channel = 0;
        } else if(T2Rec.bits.channel<=15) {  //markers
            *channel = -2;
        }
    } else {//regular input channel
        *channel = T2Rec.bits.channel + 1;
    }
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}

I came up with an almost branchless parsing function, but it doesn't produce any speed up.

if(T2Rec.bits.channel==0x3F) {  //an overflow record
        *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
    }
    *channel = (!T2Rec.bits.special) * (T2Rec.bits.channel + 1) - T2Rec.bits.special * T2Rec.bits.channel;
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}


问:
How to edit the existing excel sheet using groovy, without creating a copy of the same excel
Want To edit the existing excel sheet using groovy, without creating a copy of the same excel
Want to  Update the Results in the same excel from which the data is fetched only the output  should be  written in different cells.

I m  new to Soap UI.

kindly find the below code

```<code>import java.io.*
import jxl.*
import jxl.write.*
// Read data from excel

def f=new File("D:\\Soap.xls");
def wk= Workbook.getWorkbook(f)
def ws=wk.getSheet("Sheet1")

def count = ws.getRows()
for (int i=1;i<count;i++) {

      Cell c1=ws.getCell(0,i)

      A=Integer.parseInt(c1.getContents())

      Cell c2=ws.getCell(1,i)

      B=Integer.parseInt(c2.getContents())
      sum = A+B

      log.info sum

 //---------For Writing the data--------------

    WritableWorkbook workbook1 = Workbook.getWorkbook(f)
    WritableSheet sheet1 = workbook1.getSheet("Sheet1")
    log.info(sheet1.isHidden())
    Label label = new Label(3,i,"Addition")
    sheet1.addCell(label)
    log.info label
    workbook1.write()
    }
</code>```

答:
You can do that with reading data from excel workbook first and then doing the write related tasks after you complete reading operations like below :</p>

```<code>import com.eviware.soapui.support.XmlHolder
import java.io.File
import java.io.IOException
import jxl.*
import jxl.read.biff.BiffException
import jxl.write.*
import jxl.write.Label

log.info("Testing Started")
def reqOperationName = "someservice"
def inputDataFileName = "D:/sample/temp6.xls"

def inputDataSheetName = "Sheet1"
Workbook workbook = Workbook.getWorkbook(new File(inputDataFileName))
Sheet  sheet1 = workbook.getSheet(inputDataSheetName)
def responsesCount = 0
String[] Responses = null

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def reqholder = groovyUtils.getXmlHolder(reqOperationName+"#Request")
try{
    rowcount = sheet1.getRows()
    colcount = sheet1.getColumns()
     Responses = new String[rowcount-1]
    responsesCount = rowcount-1
    for(Row in 1..rowcount-1){

    String reqTagName = sheet1.getCell(0,0).getContents()
        log.info reqTagName
        def TagCount = reqholder["count(//*:"+reqTagName+")"]
        if(TagCount!=0){
            String reqTagValue = sheet1.getCell(0,Row).getContents()
            reqholder.setNodeValue("//*:"+reqTagName, reqTagValue)
            reqholder.updateProperty()
        }

    //test the request
    testRunner.runTestStepByName(reqOperationName)

    reqholder = groovyUtils.getXmlHolder(reqOperationName+"#Response")
    Responses[Row-1] = reqholder.getPrettyXml().toString()
    log.info Responses[Row-1]

    }

}
catch (Exception e) {log.info(e)}
finally{
    workbook.close()
}

Workbook existingWorkbook = Workbook.getWorkbook(new File(inputDataFileName));
WritableWorkbook workbookCopy = Workbook.createWorkbook(new File(inputDataFileName), existingWorkbook);

try
{

    WritableSheet sheetToEdit = workbookCopy.getSheet("Sheet1");
    WritableCell cell;
    for (int i =0;i<Responses.size();i++)
    {
    def resholder = groovyUtils.getXmlHolder(Responses[i])
    resTagValue1= resholder.getNodeValue("//*:phoneNumber")
    Label l = new Label(3, i, resTagValue1.toString());
    cell = (WritableCell) l;
    sheetToEdit.addCell(cell);
    }

}
catch (Exception e) {log.info(e)}
finally{
     workbookCopy.write();
 workbookCopy.close();
 existingWorkbook.close();

}

log.info("Testing Over")
</code>```

Body:
Want To edit the existing excel sheet using groovy, without creating a copy of the same excel
Want to  Update the Results in the same excel from which the data is fetched only the output  should be  written in different cells.

I m  new to Soap UI.

kindly find the below code

import java.io.*
import jxl.*
import jxl.write.*
// Read data from excel

def f=new File("D:\\Soap.xls");
def wk= Workbook.getWorkbook(f)
def ws=wk.getSheet("Sheet1")

def count = ws.getRows()
for (int i=1;i<count;i++) {

      Cell c1=ws.getCell(0,i)

      A=Integer.parseInt(c1.getContents())

      Cell c2=ws.getCell(1,i)

      B=Integer.parseInt(c2.getContents())
      sum = A+B

      log.info sum

 //---------For Writing the data--------------

    WritableWorkbook workbook1 = Workbook.getWorkbook(f)
    WritableSheet sheet1 = workbook1.getSheet("Sheet1")
    log.info(sheet1.isHidden())
    Label label = new Label(3,i,"Addition")
    sheet1.addCell(label)
    log.info label
    workbook1.write()
    }

Body:
You can do that with reading data from excel workbook first and then doing the write related tasks after you complete reading operations like below :

import com.eviware.soapui.support.XmlHolder
import java.io.File
import java.io.IOException
import jxl.*
import jxl.read.biff.BiffException
import jxl.write.*
import jxl.write.Label

log.info("Testing Started")
def reqOperationName = "someservice"
def inputDataFileName = "D:/sample/temp6.xls"

def inputDataSheetName = "Sheet1"
Workbook workbook = Workbook.getWorkbook(new File(inputDataFileName))
Sheet  sheet1 = workbook.getSheet(inputDataSheetName)
def responsesCount = 0
String[] Responses = null

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def reqholder = groovyUtils.getXmlHolder(reqOperationName+"#Request")
try{
    rowcount = sheet1.getRows()
    colcount = sheet1.getColumns()
     Responses = new String[rowcount-1]
    responsesCount = rowcount-1
    for(Row in 1..rowcount-1){

    String reqTagName = sheet1.getCell(0,0).getContents()
        log.info reqTagName
        def TagCount = reqholder["count(//*:"+reqTagName+")"]
        if(TagCount!=0){
            String reqTagValue = sheet1.getCell(0,Row).getContents()
            reqholder.setNodeValue("//*:"+reqTagName, reqTagValue)
            reqholder.updateProperty()
        }

    //test the request
    testRunner.runTestStepByName(reqOperationName)

    reqholder = groovyUtils.getXmlHolder(reqOperationName+"#Response")
    Responses[Row-1] = reqholder.getPrettyXml().toString()
    log.info Responses[Row-1]

    }

}
catch (Exception e) {log.info(e)}
finally{
    workbook.close()
}

Workbook existingWorkbook = Workbook.getWorkbook(new File(inputDataFileName));
WritableWorkbook workbookCopy = Workbook.createWorkbook(new File(inputDataFileName), existingWorkbook);

try
{

    WritableSheet sheetToEdit = workbookCopy.getSheet("Sheet1");
    WritableCell cell;
    for (int i =0;i<Responses.size();i++)
    {
    def resholder = groovyUtils.getXmlHolder(Responses[i])
    resTagValue1= resholder.getNodeValue("//*:phoneNumber")
    Label l = new Label(3, i, resTagValue1.toString());
    cell = (WritableCell) l;
    sheetToEdit.addCell(cell);
    }

}
catch (Exception e) {log.info(e)}
finally{
     workbookCopy.write();
 workbookCopy.close();
 existingWorkbook.close();

}

log.info("Testing Over")


问:
AWS Lambda Java return string with slashes
I have problem with returning string from Lambda after

```<code>JSONObject.toString
</code>```

in return i have

```<code>"{\"Key2\":\"Value2\",\"Key1\":\"Value1\"}"
</code>```

instead of

```<code>"{"Key2":"Value2","Key1":"Value1"}"
</code>```

Can somebody explain how to exclude these slashes?

答:
I've done similar to this before in JavaScript. If you don't serialize the object at all, then AWS API Gateway should take care of it for you. If your Lambda returns something like this:

```<code>// ...
context.done(null, {
    id: i.id,
    last_name: i.last_name,
    gender: i.gender
});
</code>```

...then your API response will look something like this:

```<code>{
    "id": 1,
    "first_name": "Chris",
    "gender": "male"
}
</code>```

Body:
I have problem with returning string from Lambda after

JSONObject.toString

in return i have

"{\"Key2\":\"Value2\",\"Key1\":\"Value1\"}"

instead of

"{"Key2":"Value2","Key1":"Value1"}"

Can somebody explain how to exclude these slashes?

Body:
I've done similar to this before in JavaScript. If you don't serialize the object at all, then AWS API Gateway should take care of it for you. If your Lambda returns something like this:

// ...
context.done(null, {
    id: i.id,
    last_name: i.last_name,
    gender: i.gender
});

...then your API response will look something like this:

{
    "id": 1,
    "first_name": "Chris",
    "gender": "male"
}


问:
How to Check Whether an Array (or List) Contains Another an Array (List) Using LINQ
I am trying to get the list of files (file is an entity) which has the selected services (service is another entity). The file can have many services.

I tried the following statement, but it does not give the correct results:

```<code>var _serviceTypes = viewModel.SelectedServiceTypes;
// _serviceTypes is an array of integers

var resultsTemp = repository.Files.Where(f => f.Services.Select(s => s.ServiceTypeID).Intersect(_serviceTypes).Any());
</code>```

What am I missing?

EDIT:

_serviceTypes in an array of integers: {int[2]}

The files can have many services, each of which as one service type id (integer)

For instance, a file has two services in it: ambulance (service type id: 3) and hospitalization (service type id: 5). I want to get all the files which have both the services in it.

答:
You're checking if a single element exists in both lists, which is probably not what you had in mind. Try to check if the intersection is equal to the smaller list (assuming it's _serviceTypes, as that's not evident from your code):

```<code>var resultsTemp = repository.Files
                            .Where(f => f.Services.Select(s => s.ServiceTypeID)
                            .Intersect(_serviceTypes)
                            .OrderBy(x => x)
                            .SequenceEqual(_serviceTypes.OrderBy(x => x));
</code>```

Body:
I am trying to get the list of files (file is an entity) which has the selected services (service is another entity). The file can have many services.

I tried the following statement, but it does not give the correct results:

var _serviceTypes = viewModel.SelectedServiceTypes;
// _serviceTypes is an array of integers

var resultsTemp = repository.Files.Where(f => f.Services.Select(s => s.ServiceTypeID).Intersect(_serviceTypes).Any());

What am I missing?

EDIT:

_serviceTypes in an array of integers: {int[2]}

The files can have many services, each of which as one service type id (integer)

For instance, a file has two services in it: ambulance (service type id: 3) and hospitalization (service type id: 5). I want to get all the files which have both the services in it.

Body:
You're checking if a single element exists in both lists, which is probably not what you had in mind. Try to check if the intersection is equal to the smaller list (assuming it's _serviceTypes, as that's not evident from your code):

var resultsTemp = repository.Files
                            .Where(f => f.Services.Select(s => s.ServiceTypeID)
                            .Intersect(_serviceTypes)
                            .OrderBy(x => x)
                            .SequenceEqual(_serviceTypes.OrderBy(x => x));


问:
Liquibase disable columnOrder diff
How can I disable the columnOrder from liquibase diff report? I looked into Liquibase source code and I can see diffColumnOrder property in the GlobalConfigurations file but I am not sure how to set this value when running the diff report. </p>

答:
In general, any of these kinds of configuration properties can be set in one of several ways, some of which depend on how you are running liquibase.

One way is to set a system property - so if you are using the liquibase.bat/liquibase shell script from the command line, you can add -Dliquibase.diffColumnOrder=false to the command line.

You could also set the environment variable JAVA_OPTS to have that property set.

A second way is to include the property name and value in a liquibase.properties file. In that case you can leave off the liquibase prefix - so your liquibase.properties file might look like this:

```<code>url: jdbc:oracle:thin:@10.0.2.7:1521/orcl
username: someuser
password: somepassword
classpath: drivers/ojdbc6-11.2.0.3.0.jar
diffColumnOrder: false
</code>```

If you are running liquibase with maven, then you could do the same sort of thing by setting a property in the POM. If you are running liquibase programatically from your own code, you could set the property programatically.

Title: Liquibase disable columnOrder diff

Body:
In general, any of these kinds of configuration properties can be set in one of several ways, some of which depend on how you are running liquibase.

One way is to set a system property - so if you are using the liquibase.bat/liquibase shell script from the command line, you can add -Dliquibase.diffColumnOrder=false to the command line.

You could also set the environment variable JAVA_OPTS to have that property set.

A second way is to include the property name and value in a liquibase.properties file. In that case you can leave off the liquibase prefix - so your liquibase.properties file might look like this:

url: jdbc:oracle:thin:@10.0.2.7:1521/orcl
username: someuser
password: somepassword
classpath: drivers/ojdbc6-11.2.0.3.0.jar
diffColumnOrder: false

If you are running liquibase with maven, then you could do the same sort of thing by setting a property in the POM. If you are running liquibase programatically from your own code, you could set the property programatically.


问:
custom string sort comparison function weird behavior
I need to sort a vector of strings, however its not a strait forward sorting. I wrote a custom sort function which works perfectly for smaller vector sizes (<100 element), however I get really weird behavior with larger sizes. Note: the values input are all numbers.

I added some debug printf statements to see what was happening internally which is where I found that empty strings and other strange strings are being passed into the function to be sorted.

My expectation is that only the values in the vector will be passed into the function. I verified that vector is filled with known values.

Sorting function:

```<code>bool sortFunc( string a, string b ){
    printf( "a: %s,\tb: %s  \t", a.c_str(), b.c_str() );

    //sorting magic defining 'bool retVal'

    printf( "%s goes before %s\n", retVal?a.c_str():b.c_str(), retVal?b.c_str():a.c_str() );

    return retVal;
}
</code>```

Main function:

```<code>vector<string> a(n);
for( int i=0; i<n; ++i ){
    cin >> a[i];
}

sort(a.begin(),a.end(),sortFunc);
</code>```

Sample of weird output:

```<code>a: 2,   b: 10   2 goes before 10
a: 10,  b: 10   10 goes before 10
a: ,    b: 10    goes before 10
a: ,    b: 10    goes before 10
a: \240E,   b: 10   \240E goes before 10
a: ,    b: 10    goes before 10
a: {@,  b: 10   {@ goes before 10
a: ,    b: 10    goes before 10
a: ,    b: 10    goes before 10
a: ,    b: 10    goes before 10
a: \225E,   b: 10   10 goes before \225E
a: 2,   b: 10   2 goes before 10
a: 10,  b: \225E    10 goes before \225E
a: ,    b:       goes before
a: ,    b:       goes before
a: \245E,   b:       goes before \245E
a: \236E,   b: \245E    \245E goes before \236E
a: 0G\260\377, b: \236E    0G\260\377 goes before \236E
a: 0G\260\377, b: \245E    0G\260\377 goes before \245E
a: 0G\260\377, b:      0G\260\377 goes before
</code>```

答:
When std::sort acts funny, it's almost always because of an invalid comparison function. The comparison function that you pass to std::sort must provide a strict weak ordering. The usual failure is that the comparison function is defined such that for two objects a and b, compare(a,b) returns true and compare(b,a) returns true, i.e., a comes before b and b comes before a. When that happens, the sort algorithm may well run off the end of your data and do all sorts of wild and crazy things.

The actual answer to this question lies somewhere inside this:

```<code>//sorting magic defining 'bool retVal'
</code>```

Body:
I need to sort a vector of strings, however its not a strait forward sorting. I wrote a custom sort function which works perfectly for smaller vector sizes (<100 element), however I get really weird behavior with larger sizes. Note: the values input are all numbers.

I added some debug printf statements to see what was happening internally which is where I found that empty strings and other strange strings are being passed into the function to be sorted.

My expectation is that only the values in the vector will be passed into the function. I verified that vector is filled with known values.

Sorting function:

bool sortFunc( string a, string b ){
    printf( "a: %s,\tb: %s  \t", a.c_str(), b.c_str() );

    //sorting magic defining 'bool retVal'

    printf( "%s goes before %s\n", retVal?a.c_str():b.c_str(), retVal?b.c_str():a.c_str() );

    return retVal;
}

Main function:

vector<string> a(n);
for( int i=0; i<n; ++i ){
    cin >> a[i];
}

sort(a.begin(),a.end(),sortFunc);

Sample of weird output:

a: 2,   b: 10   2 goes before 10
a: 10,  b: 10   10 goes before 10
a: ,    b: 10    goes before 10
a: ,    b: 10    goes before 10
a: \240E,   b: 10   \240E goes before 10
a: ,    b: 10    goes before 10
a: {@,  b: 10   {@ goes before 10
a: ,    b: 10    goes before 10
a: ,    b: 10    goes before 10
a: ,    b: 10    goes before 10
a: \225E,   b: 10   10 goes before \225E
a: 2,   b: 10   2 goes before 10
a: 10,  b: \225E    10 goes before \225E
a: ,    b:       goes before
a: ,    b:       goes before
a: \245E,   b:       goes before \245E
a: \236E,   b: \245E    \245E goes before \236E
a: 0G\260\377, b: \236E    0G\260\377 goes before \236E
a: 0G\260\377, b: \245E    0G\260\377 goes before \245E
a: 0G\260\377, b:      0G\260\377 goes before

Body:
When std::sort acts funny, it's almost always because of an invalid comparison function. The comparison function that you pass to std::sort must provide a strict weak ordering. The usual failure is that the comparison function is defined such that for two objects a and b, compare(a,b) returns true and compare(b,a) returns true, i.e., a comes before b and b comes before a. When that happens, the sort algorithm may well run off the end of your data and do all sorts of wild and crazy things.

The actual answer to this question lies somewhere inside this:

//sorting magic defining 'bool retVal'


问:
Run pip in (conda) virtualenv without activating it first
As in the title, I've created some env in conda like so

```<code>conda create -n myenv python=2.7
</code>```

I'd like a command to run pip install inside the env without doing source activate myenv first.  Is this possible?  I believe whatever method I use would have to work out the PATH etc.

答:
Assuming you are using Anaconda in a Bash shell environment, one option would be to add the Anaconda bin path for your created virtual environment to your PATH variable in such an order that the pip binary in your virtual environment comes before the system pip.

If your Anaconda virtual environment is located in the default .conda directory in your home directory you could do this as follows:

```<code>export PATH=~/.conda/envs/myenv/bin:$PATH
</code>```

If you wanted this to be the default behavior for your shell environment you could add the above command to your ~/.bashrc file.

This method is similar to the approach reccomended for setting the PATH variable to enable you to use the Anaconda binaries for the "root" environment, detailed in the Anaconda documentation.

Body:
As in the title, I've created some env in conda like so

conda create -n myenv python=2.7

I'd like a command to run pip install inside the env without doing source activate myenv first.  Is this possible?  I believe whatever method I use would have to work out the PATH etc.

Body:
Assuming you are using Anaconda in a Bash shell environment, one option would be to add the Anaconda bin path for your created virtual environment to your PATH variable in such an order that the pip binary in your virtual environment comes before the system pip.

If your Anaconda virtual environment is located in the default .conda directory in your home directory you could do this as follows:

export PATH=~/.conda/envs/myenv/bin:$PATH

If you wanted this to be the default behavior for your shell environment you could add the above command to your ~/.bashrc file.

This method is similar to the approach reccomended for setting the PATH variable to enable you to use the Anaconda binaries for the "root" environment, detailed in the Anaconda documentation.


问:
What happens when a child of an NSArray is retained and the array is deallocated?
Say I read an object from an NSArray and retain that object. I am then done with the NSArray and release it. That NSArray now has a retain count of zero. Is it deallocated or will it be forced to stick around until the child object is deallocated as well?

Basically what I am asking if I need to copy the child instead of retaining it when the child will be kept for a while but the array isn't needed?

I am thinking that a retain is fine and the NSArray will be deallocated, but I want to make sure.

答:
Because you've retained the object within the NSArray it (in comparison with the other objects in the array) will have a retain count of two. (One from the NSArray, and one from you.)

As such, when the NSArray is released your object will still have a retain count of one and will therefore still be around after the autorelease pool is emptied. (Until of course you release it.)


问:
Test used bean instead mock object
I start work with Spring and Mockito.
I use JUnit, Mockito, Spring boot.
I have test for controller, and try to make it work.

```<code>@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = CommonConfiguration.class)
@ActiveProfiles(profiles = "embedded")
public class UserController_IntegrationWContainer_Tests {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext wac;

@MockBean(name = "SignatureValidator")
private SignatureValidator signatureValidator;

private ObjectMapper objectMapper;
...

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    this.objectMapper = new ObjectMapper();
}

@Test
public void createConfirmation() throws Exception {

    ...

    ConfirmationDetails signature = new ConfirmationDetails("signature");
    when(this.signatureValidator.validateAndEnforceSignature(signature))
            .thenReturn("advanced");

    mockMvc.perform(post("/distributions/1/receive")
            .content(this.objectMapper.writeValueAsBytes(signature))
            .contentType(MediaType.APPLICATION_JSON)
    .andExpect(status().is(201));
}
</code>```

This test class used for test UserController.

```<code>@RestController
@Validated
@Transactional
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    private UserService userService;
    private SignatureValidator signatureValidator;
    ...

    @Autowired
    public UserController(UserService userService, SignatureValidator signatureValidator, ...) {
        this.userService = userService;
        this.signatureValidator = signatureValidator;
        ...
    }
    @RequestMapping(
            value = "/distributions/{distributionId}/receive",
            method = RequestMethod.POST,
            produces = "application/json")
    public ResponseEntity<Object> confirmReceipt(
            @RequestBody ConfirmationDetails signature,
            @Context HttpServletRequest request,
            @Digits(fraction = 0, integer = 19, message = "ID cannot exceed 19 digits")
            @Min(value = 1, message = "ID must be > 0")
            @PathVariable("distributionId") Long distributionId) {

        logger.info("Processing request confirmReceipt");

        /*for this string I want to use stub. but stub doesn't work*/
        String advancedSignature = signatureValidator.validateAndEnforceSignature(signature);

        ...

        Map<String, String> resultsMap = new HashMap<>();
        resultsMap.put("code", "RECEIPT_SIGNED");
        resultsMap.put("message", "Distribution download confirmed");

        return new ResponseEntity<>(resultsMap, HttpStatus.CREATED);
    }
}
</code>```

SignatureValidator interface:

```<code>public interface SignatureValidator {

    @SuppressWarnings("unchecked")
    String validateAndEnforceSignature(ConfirmationDetails signature);
}
</code>```

Two implementations of SignatureValidator:

```<code>@Component
public class SignatureValidatorIml extends WebServiceGatewaySupport implements SignatureValidator {
...
}

@Component
public class SignatureValidatorJinn extends WebServiceGatewaySupport implements SignatureValidator {
...
}
</code>```

Spring decide what implementation of bean need to inject using JinnServerConfiguration:

```<code>@Configuration
public class JinnServerConfiguration {

    final Environment env;

    @Autowired
    public JinnServerConfiguration(Environment env) {
        this.env = env;
    }

    @Bean
    public Jaxb2Marshaller marshaller() {
        ...
        return marshaller;
    }

    @Bean
    public HttpComponentsMessageSender messageSender() {
        ...
        return messageSender;
    }

    @Bean
    @Profile("!local")
    public SignatureValidator signatureValidator(Jaxb2Marshaller marshaller,
                                                 HttpComponentsMessageSender messageSender) {
        SignatureValidatorJinn signatureValidatorJinn = new SignatureValidatorJinn(env);
        signatureValidatorJinn.setDefaultUri("http://.../SignatureValidationService");
        signatureValidatorJinn.setMarshaller(marshaller);
        signatureValidatorJinn.setUnmarshaller(marshaller);
        signatureValidatorJinn.setMessageSender(messageSender);
        return signatureValidatorJinn;
    }

    @Bean
    @Profile("local")
    public SignatureValidator signatureValidatorLocal(){
        return new SignatureValidatorIml();
    }

}
</code>```

For all services in UserController mock works fine.
But when I want to mock SignatureValidator, it is not work.
In debug mode I see, that in test it used mocked bean, but then UserController runs it used Spring bean (SignatureValidatorJinn) instead mocked bean.

Why it used SignatureValidatorJinn? I think it so because test class has annotation: @ActiveProfiles(profiles = "embedded"). And according to JinnServerConfiguration "@Profile("!local")" spring made this decision.

This test worked fine, until annotation @Component has been added to SignatureValidatorIml class and to SignatureValidatorJinn class.

I can't understand, why it used Spring bean. Because other service mock work fine. I found many information about mock, but can't find a solution of this problem.

I try to do next thing, but they didn't help:

don't use MockitoAnnotations.initMocks(this);

qualify current bean for SignatureValidator: Jinn or Iml;

use @InjectMocks UserController userController;

EDIT

If I delete @Component annotation in SignatureValidatorJinn and SignatureValidatorIml, it works nice. But I can't understand why is it so.

For example, class UserService annotated with "@Service". And it is successfully mocking.

So, maybe somebody can explain, why "@Component" doesn't allow to create mock object in this case?

EDIT2

The problem was solved

I can't delete annotation component, because without this annotation, DI in my application will not work.
I find decision. Bean is called signatureValidator. And I use name SignatureValidator to specificate bean to mock. That was mistake ) So with follow construction it works fine:

```<code>@MockBean(name = "signatureValidator")
private SignatureValidator signatureValidator;
</code>```

Thanks everyone for replies :)

答:
You try to mock SignatureValidator bean. But you have and use two beans SignatureValidatorJinn and SignatureValidatorIml. And your controllers use the two beans.
Try to mock one of SignatureValidatorJinn and SignatureValidatorIml.

```<code>@MockBean(name = "SignatureValidatorJinn")
private SignatureValidator signatureValidatorJinn;
</code>```

or

```<code>@MockBean(name = "SignatureValidatorIml")
private SignatureValidator signatureValidatorIml;
</code>```

that is used in your post("/distributions/1/receive") request.

Title: Test used bean instead mock object

Body:
I start work with Spring and Mockito.
I use JUnit, Mockito, Spring boot.
I have test for controller, and try to make it work.

@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = CommonConfiguration.class)
@ActiveProfiles(profiles = "embedded")
public class UserController_IntegrationWContainer_Tests {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext wac;

@MockBean(name = "SignatureValidator")
private SignatureValidator signatureValidator;

private ObjectMapper objectMapper;
...

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    this.objectMapper = new ObjectMapper();
}

@Test
public void createConfirmation() throws Exception {

    ...

    ConfirmationDetails signature = new ConfirmationDetails("signature");
    when(this.signatureValidator.validateAndEnforceSignature(signature))
            .thenReturn("advanced");

    mockMvc.perform(post("/distributions/1/receive")
            .content(this.objectMapper.writeValueAsBytes(signature))
            .contentType(MediaType.APPLICATION_JSON)
    .andExpect(status().is(201));
}

This test class used for test UserController.

@RestController
@Validated
@Transactional
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    private UserService userService;
    private SignatureValidator signatureValidator;
    ...

    @Autowired
    public UserController(UserService userService, SignatureValidator signatureValidator, ...) {
        this.userService = userService;
        this.signatureValidator = signatureValidator;
        ...
    }
    @RequestMapping(
            value = "/distributions/{distributionId}/receive",
            method = RequestMethod.POST,
            produces = "application/json")
    public ResponseEntity<Object> confirmReceipt(
            @RequestBody ConfirmationDetails signature,
            @Context HttpServletRequest request,
            @Digits(fraction = 0, integer = 19, message = "ID cannot exceed 19 digits")
            @Min(value = 1, message = "ID must be > 0")
            @PathVariable("distributionId") Long distributionId) {

        logger.info("Processing request confirmReceipt");

        /*for this string I want to use stub. but stub doesn't work*/
        String advancedSignature = signatureValidator.validateAndEnforceSignature(signature);

        ...

        Map<String, String> resultsMap = new HashMap<>();
        resultsMap.put("code", "RECEIPT_SIGNED");
        resultsMap.put("message", "Distribution download confirmed");

        return new ResponseEntity<>(resultsMap, HttpStatus.CREATED);
    }
}

SignatureValidator interface:

public interface SignatureValidator {

    @SuppressWarnings("unchecked")
    String validateAndEnforceSignature(ConfirmationDetails signature);
}

Two implementations of SignatureValidator:

@Component
public class SignatureValidatorIml extends WebServiceGatewaySupport implements SignatureValidator {
...
}

@Component
public class SignatureValidatorJinn extends WebServiceGatewaySupport implements SignatureValidator {
...
}

Spring decide what implementation of bean need to inject using JinnServerConfiguration:

@Configuration
public class JinnServerConfiguration {

    final Environment env;

    @Autowired
    public JinnServerConfiguration(Environment env) {
        this.env = env;
    }

    @Bean
    public Jaxb2Marshaller marshaller() {
        ...
        return marshaller;
    }

    @Bean
    public HttpComponentsMessageSender messageSender() {
        ...
        return messageSender;
    }

    @Bean
    @Profile("!local")
    public SignatureValidator signatureValidator(Jaxb2Marshaller marshaller,
                                                 HttpComponentsMessageSender messageSender) {
        SignatureValidatorJinn signatureValidatorJinn = new SignatureValidatorJinn(env);
        signatureValidatorJinn.setDefaultUri("http://.../SignatureValidationService");
        signatureValidatorJinn.setMarshaller(marshaller);
        signatureValidatorJinn.setUnmarshaller(marshaller);
        signatureValidatorJinn.setMessageSender(messageSender);
        return signatureValidatorJinn;
    }

    @Bean
    @Profile("local")
    public SignatureValidator signatureValidatorLocal(){
        return new SignatureValidatorIml();
    }

}

For all services in UserController mock works fine.
But when I want to mock SignatureValidator, it is not work.
In debug mode I see, that in test it used mocked bean, but then UserController runs it used Spring bean (SignatureValidatorJinn) instead mocked bean.

Why it used SignatureValidatorJinn? I think it so because test class has annotation: @ActiveProfiles(profiles = "embedded"). And according to JinnServerConfiguration "@Profile("!local")" spring made this decision.

This test worked fine, until annotation @Component has been added to SignatureValidatorIml class and to SignatureValidatorJinn class.

I can't understand, why it used Spring bean. Because other service mock work fine. I found many information about mock, but can't find a solution of this problem.

I try to do next thing, but they didn't help:

don't use MockitoAnnotations.initMocks(this);

qualify current bean for SignatureValidator: Jinn or Iml;

use @InjectMocks UserController userController;

EDIT

If I delete @Component annotation in SignatureValidatorJinn and SignatureValidatorIml, it works nice. But I can't understand why is it so.

For example, class UserService annotated with "@Service". And it is successfully mocking.

So, maybe somebody can explain, why "@Component" doesn't allow to create mock object in this case?

EDIT2

The problem was solved

I can't delete annotation component, because without this annotation, DI in my application will not work.
I find decision. Bean is called signatureValidator. And I use name SignatureValidator to specificate bean to mock. That was mistake ) So with follow construction it works fine:

@MockBean(name = "signatureValidator")
private SignatureValidator signatureValidator;

Thanks everyone for replies :)

Body:
You try to mock SignatureValidator bean. But you have and use two beans SignatureValidatorJinn and SignatureValidatorIml. And your controllers use the two beans.
Try to mock one of SignatureValidatorJinn and SignatureValidatorIml.

@MockBean(name = "SignatureValidatorJinn")
private SignatureValidator signatureValidatorJinn;

or

@MockBean(name = "SignatureValidatorIml")
private SignatureValidator signatureValidatorIml;

that is used in your post("/distributions/1/receive") request.


问:
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other.

Here is the result I would like

Here is what I am getting (fail)

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="primary-content">
  <p class="intro">
  Austin, Texas is not only the capital.<br>It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.
  </p>
  <div id="container2">
    <div id="container1">
      <div id="About">
        <h2>About</h2>
        <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.
        </p>
      <!-- Column one end -->
      </div>
      <div id="Capitalbuilding">
      <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
      <!-- Column two end -->
      </div>
    </div>
  </div>
</div><!-- End .primary-content --></code>```

答:
Here you go. Tested and works perfect:</p>

```<code><div class="primary-content">
        <p class="intro">
            Austin, Texas is not only the capital.<br>It's a hub for
            awesome live music, out of this world art, a booming tech
             scene as well as a favorite foodie destination.
        </p>
<div id="container2">
  <div style="display: flex" id="container1">
    <div style="flex: 1" id="About">
        <h2>About</h2>
        <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed
         id ante pellentesque, ullamcorper sapien vel, sagittis tellus.
         Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id
         nunc laoreet eleifend. Integer aliquet massa vitae auctor
         rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean
         sit amet orci fringilla, egestas eros ornare, dignissim magna.
         Duis commodo felis sit amet lacus congue fermentum.
         Pellentesque tincidunt semper nibh vel posuere. Integer tempus
         leo ut diam scelerisque fermentum in id tortor. Vestibulum et
         condimentum arcu. Morbi vitae sem nec lectus egestas
         tristique. Cras hendrerit maximus purus eu tempus. Suspendisse
         nec nisi ipsum.  .
        </p>
        <!-- Column one end -->
    </div>

    <div style="flex: 1" id="Capitalbuilding">
        <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
        <!-- Column two end -->
    </div>
</div>
</code>```

Body:
Having trouble with columns. Trying to get an column with an image and a column with text and background next to each other.

Here is the result I would like

Here is what I am getting (fail)

.primary-content,
.main-header,
.main-footer {
  text-align: center;
}

.primary-content {
  padding-top: 25px;
  padding-bottom: 95px;
}

  Austin, Texas is not only the capital.
It's a hub for awesome live music, out of this world art, a booming tech scene as well as a favorite foodie destination.

About

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id ante pellentesque, ullamcorper sapien vel, sagittis tellus. Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id nunc laoreet eleifend. Integer aliquet massa vitae auctor rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean sit amet orci fringilla, egestas eros ornare, dignissim magna. Duis commodo felis sit amet lacus congue fermentum. Pellentesque tincidunt semper nibh vel posuere. Integer tempus leo ut diam scelerisque fermentum in id tortor. Vestibulum et condimentum arcu. Morbi vitae sem nec lectus egestas tristique. Cras hendrerit maximus purus eu tempus. Suspendisse nec nisi ipsum.

Body:
Here you go. Tested and works perfect:

<div class="primary-content">
        <p class="intro">
            Austin, Texas is not only the capital.<br>It's a hub for
            awesome live music, out of this world art, a booming tech
             scene as well as a favorite foodie destination.
        </p>
<div id="container2">
  <div style="display: flex" id="container1">
    <div style="flex: 1" id="About">
        <h2>About</h2>
        <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed
         id ante pellentesque, ullamcorper sapien vel, sagittis tellus.
         Aenean vulputate nisl eu eros blandit euismod. Sed sagittis id
         nunc laoreet eleifend. Integer aliquet massa vitae auctor
         rhoncus. Etiam vel diam euismod elit varius faucibus. Aenean
         sit amet orci fringilla, egestas eros ornare, dignissim magna.
         Duis commodo felis sit amet lacus congue fermentum.
         Pellentesque tincidunt semper nibh vel posuere. Integer tempus
         leo ut diam scelerisque fermentum in id tortor. Vestibulum et
         condimentum arcu. Morbi vitae sem nec lectus egestas
         tristique. Cras hendrerit maximus purus eu tempus. Suspendisse
         nec nisi ipsum.  .
        </p>
        <!-- Column one end -->
    </div>

    <div style="flex: 1" id="Capitalbuilding">
        <!-- Column two start -->
        <img src="https://image.ibb.co/e90Vhw/419796506_db7f02aedd_b.jpg" alt="picture of the Capital Building">
        <!-- Column two end -->
    </div>
</div>