问:
Check Username Using Ajax in Jquery Validation Engine
I am using query Validation Engine :

http://www.position-relative.net/creation/formValidator/demos/demoValidators.html

I want to validate the username field using ajax. If username already exisit in db.. It should validate.

Here is my code & something I have tried so far :

JS:

```<code>        "ajaxUserNameCheck": {
            "url": "phpajax/ajaxValidateFieldUser.php",
            // you may want to pass extra data on the ajax call
            "extraData": "name=eric",
            // if you provide an "alertTextOk", it will show as a green prompt when the field validates
            "alertTextOk": "* This username is available",
            "alertText": "* This user is already taken",
            "alertTextLoad": "* Validating, please wait"
        },
</code>```

HTML:

```<code><input class="validate[custom[ajaxUserNameCheck]" type="text" name="userName" id="userName" ></div>
</code>```

It returns an error in alert:

```<code>jqv:custom type not allowed ajaxUserNameCheck
</code>```

答:
Replace

```<code>validate[custom[ajaxUserNameCheck]
</code>```

with

```<code>validate[ajax[ajaxUserNameCheck]
</code>```

Body:
I am using query Validation Engine :

http://www.position-relative.net/creation/formValidator/demos/demoValidators.html

I want to validate the username field using ajax. If username already exisit in db.. It should validate.

Here is my code & something I have tried so far :

JS:

        "ajaxUserNameCheck": {
            "url": "phpajax/ajaxValidateFieldUser.php",
            // you may want to pass extra data on the ajax call
            "extraData": "name=eric",
            // if you provide an "alertTextOk", it will show as a green prompt when the field validates
            "alertTextOk": "* This username is available",
            "alertText": "* This user is already taken",
            "alertTextLoad": "* Validating, please wait"
        },

HTML:

<input class="validate[custom[ajaxUserNameCheck]" type="text" name="userName" id="userName" >

It returns an error in alert:

jqv:custom type not allowed ajaxUserNameCheck

Body:
Replace

validate[custom[ajaxUserNameCheck]

with

validate[ajax[ajaxUserNameCheck]


来源: stackexchange

问:
Unable to locate elements on webpage with headless chrome
I have a script that's accessing printers, and my code works totally fine when chrome is run normally, but when it's run headless, selenium can't seem to find elements on the webpage.

Here's the relevant code:

init method:

```<code>def __init__(self, ip_address):
    """ Initialize a new Printer_Webpage object."""
    self.ip_address = ip_address
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--window-size=1920x1080")
    self.browser = webdriver.Chrome(chrome_options=chrome_options)
    # Ignore lack of cert for each printer web page.
    # Otherwise, can't open page.
    self.browser.accept_untrusted_certs = True
</code>```

Login method:

```<code>def login(self):
    """Navigates through the login page for the printer."""
    # Open login page
    self.browser.get(f'https://{self.ip_address}/wcd/top.xml')
    # STEPS TO LOGIN:
    # 1) Select 'Administrator' radio button and click.
    self.browser.find_element_by_id('Admin').click()
    # 2) Select Login button and click.
    self.browser.find_element_by_xpath("//input[@type='submit' \
                                        and @value='Login']").click()
    # 3) Select admin (user mode)
    self.browser.find_element_by_id('R_ADM2').click()
    # 4) Select password field and input PASSWORD, then submit.
    password_field = self.browser.find_element_by_id('Admin_Pass')
    password_field.send_keys(PASSWORD)
    password_field.send_keys(Keys.RETURN)
</code>```

Full error message:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"Admin"}
</code>```

And here's some other info that might be of use:

```<code>(Session info: headless chrome=62.0.3202.94)

(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64)
</code>```

答: If it's an issue with SSL certs, you can start Chrome without certs using a command line flag (assuming that's how you're starting it). I believe the switch is --allow-running-insecure-content, and I located that from this list found here.

ContentLicense: CC BY-SA 3.0

Body:
I have a script that's accessing printers, and my code works totally fine when chrome is run normally, but when it's run headless, selenium can't seem to find elements on the webpage.

Here's the relevant code:

init method:

def __init__(self, ip_address):
    """ Initialize a new Printer_Webpage object."""
    self.ip_address = ip_address
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--window-size=1920x1080")
    self.browser = webdriver.Chrome(chrome_options=chrome_options)
    # Ignore lack of cert for each printer web page.
    # Otherwise, can't open page.
    self.browser.accept_untrusted_certs = True

Login method:

def login(self):
    """Navigates through the login page for the printer."""
    # Open login page
    self.browser.get(f'https://{self.ip_address}/wcd/top.xml')
    # STEPS TO LOGIN:
    # 1) Select 'Administrator' radio button and click.
    self.browser.find_element_by_id('Admin').click()
    # 2) Select Login button and click.
    self.browser.find_element_by_xpath("//input[@type='submit' \
                                        and @value='Login']").click()
    # 3) Select admin (user mode)
    self.browser.find_element_by_id('R_ADM2').click()
    # 4) Select password field and input PASSWORD, then submit.
    password_field = self.browser.find_element_by_id('Admin_Pass')
    password_field.send_keys(PASSWORD)
    password_field.send_keys(Keys.RETURN)

Full error message:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"Admin"}

And here's some other info that might be of use:

(Session info: headless chrome=62.0.3202.94)

(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64)


问:
in Linq: How to return a typed object with an overriden values
I have the following linq query which returns a Report Object; yet I need to explicitly set the value of one of its proprties from another column.

```<code>Dim results As IQueryable(Of Report)
results = From R In db.Reports _
       Join RS In db.ReportStatus On R.ReportID Equals RS.ReportID
       Where RS.ActiveIndicator And _
             RS.StatusID <> clsCnst.Enum_ReportStatus.COMPLETE
       Select R
</code>```

I want to override R.LatestReportStatusDate = RS.StatusDate. I tried explciitly setting the properties of a new Report object as follows:

```<code>Dim results As IQueryable(Of Report)
results = From R In db.Reports _
       Join RS In db.ReportStatus On R.ReportID Equals RS.ReportID
       Where RS.ActiveIndicator And _
             RS.StatusID <> clsCnst.Enum_ReportStatus.COMPLETE
       Select New Report With {.ReportID = R.ReportID, _
                               .ReportTypeID = R.ReportTypeID, _
                               .PatientID = R.PatientID, _
                               .Locked = R.Locked, _
                               .LockedDate = R.LockedDate, _
                               .LatestReportStatusDate = RS.StatusDate}
</code>```

However this will give me an error Unable to cast object of type 'System.Data.Linq.DataQuery1[VB$AnonymousType_614..... to type 'System.Linq.IQueryable`1[reportcirculation.Report]

How can I solve this?

答:
Ok found the solution if someone is interested </p>

```<code>Dim make As Func(Of Date, Report, Report) = Function(SD As Date, r As Report)
                                                r.LatestReportStatusDate = SD
                                                Return r
                                            End Function

results = From R In db.Reports _
            Join RS In db.ReportStatus On R.ReportID Equals RS.ReportID
             Where RS.ActiveIndicator And _
                RS.StatusID <> clsCnst.Enum_ReportStatus.COMPLETE
             Select make(RS.StatusDate, R)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following linq query which returns a Report Object; yet I need to explicitly set the value of one of its proprties from another column.

Dim results As IQueryable(Of Report)
results = From R In db.Reports _
       Join RS In db.ReportStatus On R.ReportID Equals RS.ReportID
       Where RS.ActiveIndicator And _
             RS.StatusID <> clsCnst.Enum_ReportStatus.COMPLETE
       Select R

I want to override R.LatestReportStatusDate = RS.StatusDate. I tried explciitly setting the properties of a new Report object as follows:

Dim results As IQueryable(Of Report)
results = From R In db.Reports _
       Join RS In db.ReportStatus On R.ReportID Equals RS.ReportID
       Where RS.ActiveIndicator And _
             RS.StatusID <> clsCnst.Enum_ReportStatus.COMPLETE
       Select New Report With {.ReportID = R.ReportID, _
                               .ReportTypeID = R.ReportTypeID, _
                               .PatientID = R.PatientID, _
                               .Locked = R.Locked, _
                               .LockedDate = R.LockedDate, _
                               .LatestReportStatusDate = RS.StatusDate}

However this will give me an error Unable to cast object of type 'System.Data.Linq.DataQuery1[VB$AnonymousType_614..... to type 'System.Linq.IQueryable`1[reportcirculation.Report]

How can I solve this?

Body:
Ok found the solution if someone is interested

Dim make As Func(Of Date, Report, Report) = Function(SD As Date, r As Report)
                                                r.LatestReportStatusDate = SD
                                                Return r
                                            End Function

results = From R In db.Reports _
            Join RS In db.ReportStatus On R.ReportID Equals RS.ReportID
             Where RS.ActiveIndicator And _
                RS.StatusID <> clsCnst.Enum_ReportStatus.COMPLETE
             Select make(RS.StatusDate, R)


问:
Java - method to lookup a specific ID from txt file and return that line details
I am writing a method to lookup a specific ID that is stored within a txt file.

These details are assigned to an arrayList titled list, if the lookup string matches the data stored in list then it reads the id,firstname,surname (IE the whole line of the txt file) and then creates an instance of another class profile.

I then want to add this lookup data to a new arrayList titled lookup then to output it. I have the below method however, it does not work and just jumps to my else clause.
Could anyone tell me where i'm going wrong and how to fix would be appreciated. Thanks.

答:
Could you instead use a TupleMap for the same effect?

// create our map Map peopleByForename
  = new HashMap>();

// populate it peopleByForename.put("Bob", new Tuple2(new Person("Bob
  Smith",
                                         new Person("Bob Jones"));

// read from it Tuple bobs = peopleByForename["Bob"];
  Person bob1 = bobs.Item1; Person bob2 = bobs.Item2;

Then an example of reading the key:value from the txt file can be found here : Java read txt file to hashmap, split by ":" using Buffered Reader.


问:
Is it advisable to call Web Services on cellForRowAtIndexPath for large datasets?
If the data set is too large and I want to show the data on a table View. What should be the best possible approach ?

First Approach-
I call the API in cellForRowAtIndexPath. This would make the request everytime I scroll which would mean hitting the service again and again. May be I can cache the data as well but still I think it is not the best possible approach.

Second Approach-
First, Save all the data locally and then show it. This would mean occupying more of the internal storage.

Which approach is better or is there any better approach available ?

答:
What approach will you take depends on whether your API supports pagination or not! If the API does not support pagination then you left with no other solution then to retrieve every thing in one shot and show it in tableView.

If your API supports pagination, then you can make a call to load the first page in ViewDidLoad and then implement scrollViewDidScroll delegate to check when user scrolled to Bottom of the table/collectionView and trigger the web service to fetch next page of response. This will continue till server responds with empty array.

Here is a simple scrollViewDidScroll override which you can make use of to decide if user reached end of tableView/collectionView

```<code>extension ViewController : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let bottomEdge = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.bounds.height
        if scrollView.contentOffset.y >= bottomEdge {
            //make a webservice call now
        }
    }
}
</code>```

Body:
What approach will you take depends on whether your API supports pagination or not! If the API does not support pagination then you left with no other solution then to retrieve every thing in one shot and show it in tableView.

If your API supports pagination, then you can make a call to load the first page in ViewDidLoad and then implement scrollViewDidScroll delegate to check when user scrolled to Bottom of the table/collectionView and trigger the web service to fetch next page of response. This will continue till server responds with empty array.

Here is a simple scrollViewDidScroll override which you can make use of to decide if user reached end of tableView/collectionView

extension ViewController : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let bottomEdge = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.bounds.height
        if scrollView.contentOffset.y >= bottomEdge {
            //make a webservice call now
        }
    }
}


问:
How to print word that you want inside a textfile?
I have this program which it prints the text file with numbers:

```<code>with open('addon/entertainment.txt')as f:
    lines = []
    for l_i, line in enumerate(f.read().split('\n'), 1):
        formatted_line = '%s. %s' % (l_i, line)
        print(formatted_line)
        lines.append(formatted_line)
</code>```

Output:

```<code>1. Synchronised Swimming Dance
2. Clown Performance
3. Magic Performance
4. House Dance Performance
5. Live Band Performance
</code>```

What should I do to the program so that I can get entertainment such as :

```<code>1. Magic Performance
2. Live Band Performance
</code>```

thanks

答:
Use readlines and output the lines according to their index.

```<code>with open('addon/entertainment.txt') as f:
    lines = f.readlines()
    for line in lines:
       print("{}. {}".format(lines.index(line) + 1, line))

    desired_lines = [3, 5]
    output = []
    for desired in desired_lines:
        output.append(lines[desired - 1])

    for o in output:
        print("{}. {}".format(output.index(o) + 1, o))
</code>```

Alternatively, if you want to select lines based on an input call, replaced desired_lines with:

```<code>desired_lines = input().split(", ")
# can choose one number or multiple numbers like this: "3, 5"
output = []
for desired in desired_lines:
    output.append(lines[int(desired) - 1])

for o in output:
    print("{}. {}".format(output.index(o) + 1, o))
</code>```

Note that if your input goes higher than number of lines in your text file, you'll raise a IndexError exception.

Body:
I have this program which it prints the text file with numbers:

with open('addon/entertainment.txt')as f:
    lines = []
    for l_i, line in enumerate(f.read().split('\n'), 1):
        formatted_line = '%s. %s' % (l_i, line)
        print(formatted_line)
        lines.append(formatted_line)

Output:

1. Synchronised Swimming Dance
2. Clown Performance
3. Magic Performance
4. House Dance Performance
5. Live Band Performance

What should I do to the program so that I can get entertainment such as :

1. Magic Performance
2. Live Band Performance

thanks

Body:
Use readlines and output the lines according to their index.

with open('addon/entertainment.txt') as f:
    lines = f.readlines()
    for line in lines:
       print("{}. {}".format(lines.index(line) + 1, line))

    desired_lines = [3, 5]
    output = []
    for desired in desired_lines:
        output.append(lines[desired - 1])

    for o in output:
        print("{}. {}".format(output.index(o) + 1, o))

Alternatively, if you want to select lines based on an input call, replaced desired_lines with:

desired_lines = input().split(", ")
# can choose one number or multiple numbers like this: "3, 5"
output = []
for desired in desired_lines:
    output.append(lines[int(desired) - 1])

for o in output:
    print("{}. {}".format(output.index(o) + 1, o))

Note that if your input goes higher than number of lines in your text file, you'll raise a IndexError exception.


问:
Create a BaseViewModel on a common library
I have a  common library that need to be shared among my main WPF app and its plugins...
In the common library I have a BaseViewModel with this code

```<code>    public Dispatcher RootDispatcher
    {
        get
        {
            _rootDispatcher = _rootDispatcher ??
                (App.Current != null
                    ? App.Current.Dispatcher
                    : Dispatcher.CurrentDispatcher);
            return _rootDispatcher;
        }
        // unit tests can get access to this via InternalsVisibleTo
        internal set
        {
            _rootDispatcher = value;
        }
    }

    protected void TriggerSafeEvent(EventHandler eve, EventArgs args)
    {
        if (RootDispatcher.CheckAccess())
        {
            if (eve != null)
                eve.Invoke(this, args);
        }
        else
        {
            RootDispatcher.Invoke((Action)delegate()
            {
                if (eve != null)
                    eve.Invoke(this, args);
            });
        }
    }
</code>```

So the consumer ViewModel could call an event in a way like this without to be worried wherever thread belongs from the main thread:

```<code>    MyViewModel : BaseViewModel {

    ..
            TriggerSafeEvent(MyEventHandler, MyEventArgs);

    }
</code>```

Since the common library is not a WPF application, the App object is not resolved.

I think that this approach could be wrong, however I feel that is not an uncommon practice to share often call methods within a base view model.

What is the best solution to handle with App object?

答:
Use dependency injection. This is off the top of my head but it'll work.

```<code>public interface IDispatcherProvider {
    Dispatcher Dispatcher { get; }
}
</code>```

BaseViewModel

```<code>public static IDispatcherProvider DispatcherProvider { get; set; }
</code>```

Interface implementation:

```<code>public class DispatcherProviderImplementation : IDispatcherProvider
{
    public DispatcherProviderImplementation(Func<Dispatcher> getDispatcher)
    {
        _getDispatcher = getDispatcher;
    }

    private Func<Dispatcher> _getDispatcher;

    public virtual Dispatcher Dispatcher => _getDispatcher?.Invoke();

    //  If your compiler won't accept the above, try this
    /*
    public virtual Dispatcher Dispatcher {
        get {
            return (_getDispatcher == null) ? null : _getDispatcher();
        }
    }
    */
}
</code>```

App

```<code>    static App()
    {
        BaseViewModel.DispatcherProvider
            = new DispatcherProviderImplementation(() => (App.Current != null
                ? App.Current.Dispatcher
                : Dispatcher.CurrentDispatcher));
    }
</code>```

Body:
I have a  common library that need to be shared among my main WPF app and its plugins...
In the common library I have a BaseViewModel with this code

    public Dispatcher RootDispatcher
    {
        get
        {
            _rootDispatcher = _rootDispatcher ??
                (App.Current != null
                    ? App.Current.Dispatcher
                    : Dispatcher.CurrentDispatcher);
            return _rootDispatcher;
        }
        // unit tests can get access to this via InternalsVisibleTo
        internal set
        {
            _rootDispatcher = value;
        }
    }

    protected void TriggerSafeEvent(EventHandler eve, EventArgs args)
    {
        if (RootDispatcher.CheckAccess())
        {
            if (eve != null)
                eve.Invoke(this, args);
        }
        else
        {
            RootDispatcher.Invoke((Action)delegate()
            {
                if (eve != null)
                    eve.Invoke(this, args);
            });
        }
    }

So the consumer ViewModel could call an event in a way like this without to be worried wherever thread belongs from the main thread:

    MyViewModel : BaseViewModel {

    ..
            TriggerSafeEvent(MyEventHandler, MyEventArgs);

    }

Since the common library is not a WPF application, the App object is not resolved.

I think that this approach could be wrong, however I feel that is not an uncommon practice to share often call methods within a base view model.

What is the best solution to handle with App object?

Body:
Use dependency injection. This is off the top of my head but it'll work.

public interface IDispatcherProvider {
    Dispatcher Dispatcher { get; }
}

BaseViewModel

public static IDispatcherProvider DispatcherProvider { get; set; }

Interface implementation:

public class DispatcherProviderImplementation : IDispatcherProvider
{
    public DispatcherProviderImplementation(Func<Dispatcher> getDispatcher)
    {
        _getDispatcher = getDispatcher;
    }

    private Func<Dispatcher> _getDispatcher;

    public virtual Dispatcher Dispatcher => _getDispatcher?.Invoke();

    //  If your compiler won't accept the above, try this
    /*
    public virtual Dispatcher Dispatcher {
        get {
            return (_getDispatcher == null) ? null : _getDispatcher();
        }
    }
    */
}

App

    static App()
    {
        BaseViewModel.DispatcherProvider
            = new DispatcherProviderImplementation(() => (App.Current != null
                ? App.Current.Dispatcher
                : Dispatcher.CurrentDispatcher));
    }


问:
Adding to a List/Array in a Loop
Beginner coder here! I am looking to make a loop that will check the list named "budget" to see if its negative, and if it is, it will use the "years" list to add the year to the list named "nodef". My end result is to have the list "nodef" to contain all the years that have no deficits.

```<code>budget = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

i = 0

if i <21:

 if budget[i]<0:

   nodef.append(years[i])
   i += 1
else:

print(nodef)
</code>```

This is what I have at the moment. Please let me know how I can approve upon this. This is purely for my own curiosity.

答:
If you want to restrict output to 21 this would do it:

```<code>nodef = [year for budget, year in zip(budgets, years) if budget < 0][:21]
</code>```

Leave out the [:21] if you don't really need it.

And another approach:

```<code>nodef = [years[i] for i, budget in enumerate(budgets) if budget < 0]
</code>```

Title: Adding to a List/Array in a Loop

Body:
Beginner coder here! I am looking to make a loop that will check the list named "budget" to see if its negative, and if it is, it will use the "years" list to add the year to the list named "nodef". My end result is to have the list "nodef" to contain all the years that have no deficits.

budget = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

i = 0

if i <21:

 if budget[i]<0:

   nodef.append(years[i])
   i += 1
else:

print(nodef)

This is what I have at the moment. Please let me know how I can approve upon this. This is purely for my own curiosity.

Body:
If you want to restrict output to 21 this would do it:

nodef = [year for budget, year in zip(budgets, years) if budget < 0][:21]

Leave out the [:21] if you don't really need it.

And another approach:

nodef = [years[i] for i, budget in enumerate(budgets) if budget < 0]


问:
Parsing string in multiline data with positive lookbehind
I am trying to parse data like:

```<code>header1
-------
var1 0
var2 5
var3 9
var6 1

header2
-------
var1 -3
var3 5
var5 0
</code>```

Now I want to get e.g. var3 for header2. Whats the best way to do this?

So far I was parsing my files line-by-line via

```<code>open(FILE,"< $file");
while (my $line = <FILE>){
    # do stuff
}
</code>```

but I guess it's not possible to handle multiline parsing properly.

Now I am thinking to parse the file at once but wasn't successful so far...

```<code>my @Input;
open(FILE,"< $file");
while (<FILE>){ @Input = <FILE>; }
if (@Input =~ /header2/){
    #...
}
</code>```

答:
The easier way to handle this is "paragraph mode".

```<code>local $/ = "";
while (<>) {
    my ($header, $body) =~ /^([^\n]*)\n-+\n(.*)/s
       or die("Bad data");

    my @data = map [ split ], split /\n/, $body;

    # ... Do something with $header and @data ...
}
</code>```

The same can be achieved without messing with $/ as follows:

```<code>my @buf;
while (1) {
    my $line = <>;
    $line =~ s/\s+\z// if !defined($line);
    if (!length($line)) {
       if (@buf) {
          my $header = shift(@buf);
          shift(@buf);
          my @data = map [ split ], splice(@buf);

          # ... Do something with $header and @data ...
       }

       last if !defined($line);
       next;
    }

    push @buf, $line;
}
</code>```

(In fact, the second snippet includes a couple of small improvements over the first.)

Quick comments on your attempt:

The while loop is useless because @Input = <FILE> places the remaining lines of the file in @Input.

@Input =~ /header2/ matches header2 against the stringification of the array, which is the stringification of the number of elements in @Input. If you want to check of an element of @Input contains header2, will you will need to loop over the elements of @Inputs and check them individually.

Body:
I am trying to parse data like:

header1
-------
var1 0
var2 5
var3 9
var6 1

header2
-------
var1 -3
var3 5
var5 0

Now I want to get e.g. var3 for header2. Whats the best way to do this?

So far I was parsing my files line-by-line via

open(FILE,"< $file");
while (my $line = <FILE>){
    # do stuff
}

but I guess it's not possible to handle multiline parsing properly.

Now I am thinking to parse the file at once but wasn't successful so far...

my @Input;
open(FILE,"< $file");
while (<FILE>){ @Input = <FILE>; }
if (@Input =~ /header2/){
    #...
}

Body:
The easier way to handle this is "paragraph mode".

local $/ = "";
while (<>) {
    my ($header, $body) =~ /^([^\n]*)\n-+\n(.*)/s
       or die("Bad data");

    my @data = map [ split ], split /\n/, $body;

    # ... Do something with $header and @data ...
}

The same can be achieved without messing with $/ as follows:

my @buf;
while (1) {
    my $line = <>;
    $line =~ s/\s+\z// if !defined($line);
    if (!length($line)) {
       if (@buf) {
          my $header = shift(@buf);
          shift(@buf);
          my @data = map [ split ], splice(@buf);

          # ... Do something with $header and @data ...
       }

       last if !defined($line);
       next;
    }

    push @buf, $line;
}

(In fact, the second snippet includes a couple of small improvements over the first.)

Quick comments on your attempt:

The while loop is useless because @Input = <FILE> places the remaining lines of the file in @Input.

@Input =~ /header2/ matches header2 against the stringification of the array, which is the stringification of the number of elements in @Input. If you want to check of an element of @Input contains header2, will you will need to loop over the elements of @Inputs and check them individually.


问:
OSGi Compendium (R6) Annotations + Felix SCR 2.0.0 + Karaf 3.0.6
I'm changing my code from Felix SCR annotations to OSGi Compendium R6.

When I want to start my Karaf container, my bundle needs the capability osgi.extender to start correctly.
I could see this is provided by org.apache.felix.scr >= 2.0.0 (https://mvnrepository.com/artifact/org.apache.felix/org.apache.felix.scr)

Now the problem:
I have the version 1.8.4 of org.apache.felix.scr in my Karaf container (this is a MUST as some bundle has a filter to this version), when I try to put the two versions, my container NEVER CAME UP.

How can I debug this kind of behaviour ? can I get the osgi.extender capability from another place ?

答:
Just a suggestion: It is know that Pax Runner doesn't work well with Felix.scr >= 2.0.0 and Karaf.

You should test updating your pax version to 4.11.0


问:
Is it possible to send TCP message using Webservices Asp.net or need WCF
I need to develop a WebSevice which takes its input and forwards this input using TCP.

Is it possible for Asp.net Webservices ? Or Should I use WCF etc..

I have to know if it is possible to create a web service that should be like a bridge between the two: it waits for an incoming request, forwards it to the required TCP port.

Simple samples are always welcome :)

答: I used the sample project and it worked.  </p>


问:
hidden random number confirms wrong result in java
I have a few issues with what I'm trying to do, but the most pressing is this:

I have a button that sets a hidden random digit, and the user has to attempt to figure out what that digit is. My current code is as follows:

//setting the variables

```<code>int max = 9;
int min = 0;
int diff = max-min;
int getNum1;
int a;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_guess);
</code>```

//assigning the Java to XML

```<code>final TextView urNum1 = findViewById(R.id.txtUrNum1);
final TextView myNum1 = findViewById(R.id.txtMyNum1);
ImageButton up1 = findViewById(R.id.btnUp1);
ImageButton dn1 = findViewById(R.id.btnDn1);
Button chk = findViewById(R.id.btnCheck);
ImageButton start = findViewById(R.id.btnStartGuess);
</code>```

//starting the randomizer

```<code>start.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Random rn = new Random();
        urNum1.setText("?");
        a = rn.nextInt(diff+1);
        a += min;
    }
});
</code>```

//checking for a match

```<code>chk.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (a == 0 && getNum1 == 9) {
            urNum1.setText("0"); }
        else if (a == 1 && getNum1 == 0) {
            urNum1.setText("1"); }
        else if (a == 2 && getNum1 == 1) {
            urNum1.setText("2"); }
        else if (a == 3 && getNum1 == 2) {
            urNum1.setText("3");  }
        else if (a == 4 && getNum1 == 3) {
            urNum1.setText("4"); }
        else if (a == 5 && getNum1 == 4) {
            urNum1.setText("5"); }
        else if (a == 6 && getNum1 == 5) {
            urNum1.setText("6"); }
        else if (a == 7 && getNum1 == 6) {
            urNum1.setText("7"); }
        else if (a == 8 && getNum1 == 7) {
            urNum1.setText("8"); }
        else if (a == 9 && getNum1 == 8) {
            urNum1.setText("9"); }
</code>```

//incrementing the guessed number

```<code>up1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getNum1 = Integer.parseInt(myNum1.getText().toString());
                if (getNum1 == 0) {
                    myNum1.setText("1"); }
                else if (getNum1 == 1 ) {
                    myNum1.setText("2"); }
                else if (getNum1 == 2) {
                    myNum1.setText("3"); }
                else if (getNum1 == 3) {
                    myNum1.setText("4"); }
                else if (getNum1 == 4) {
                    myNum1.setText("5"); }
                else if (getNum1 == 5) {
                    myNum1.setText("6"); }
                else if (getNum1 == 6) {
                    myNum1.setText("7"); }
                else if (getNum1 == 7) {
                    myNum1.setText("8"); }
                else if (getNum1 == 8) {
                    myNum1.setText("9"); }
                else if (getNum1 == 9) {
                    myNum1.setText("0"); }
                });
</code>```

//decrementing the guessed number

```<code>dn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getNum1 = Integer.parseInt(myNum1.getText().toString());
                if (getNum1 == 0) {
                    myNum1.setText("9"); }
                else if (getNum1 == 9 ) {
                    myNum1.setText("8"); }
                else if (getNum1 == 8) {
                    myNum1.setText("7"); }
                else if (getNum1 == 7) {
                    myNum1.setText("6"); }
                else if (getNum1 == 6) {
                    myNum1.setText("5"); }
                else if (getNum1 == 5) {
                    myNum1.setText("4"); }
                else if (getNum1 == 4) {
                    myNum1.setText("3"); }
                else if (getNum1 == 3) {
                    myNum1.setText("2"); }
                else if (getNum1 == 2) {
                    myNum1.setText("1"); }
                else if (getNum1 == 1) {
                    myNum1.setText("0"); }
            }
        });
</code>```

The problem I am running into is that when up1 is pressed, the numbers tend to match up when I check them, but when I press dn1 to get to the matched number, my chosen number is lower than the matched number by two. It may be because my coding is convoluted, and I could probably make it better with using ++ incrementing, but I can't seem to get that to work right either.

答:
I have figured out the solution on my own, if anyone has run into this issue as well. In the code where I change the myNum value by incrementing/decrementing the value, I'm only checking the current value for each condition of the 'if' statement without also changing the value within. So no matter how many times I check it, it will always be one off. My fix:

```<code>getNum1 = Integer.parseInt(myNum1.getText().toString());
    if (getNum1 == 0) {
        myNum1.setText("9");
        getNum1 = 9; }
    else if (getNum1 == 9 ) {
        myNum1.setText("8");
        getNum1 = 8; }
    else if (getNum1 == 8) {
        myNum1.setText("7");
        getNum1 = 7; }
</code>```

And so on from there.

Body:
I have a few issues with what I'm trying to do, but the most pressing is this:

I have a button that sets a hidden random digit, and the user has to attempt to figure out what that digit is. My current code is as follows:

//setting the variables

int max = 9;
int min = 0;
int diff = max-min;
int getNum1;
int a;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_guess);

//assigning the Java to XML

final TextView urNum1 = findViewById(R.id.txtUrNum1);
final TextView myNum1 = findViewById(R.id.txtMyNum1);
ImageButton up1 = findViewById(R.id.btnUp1);
ImageButton dn1 = findViewById(R.id.btnDn1);
Button chk = findViewById(R.id.btnCheck);
ImageButton start = findViewById(R.id.btnStartGuess);

//starting the randomizer

start.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Random rn = new Random();
        urNum1.setText("?");
        a = rn.nextInt(diff+1);
        a += min;
    }
});

//checking for a match

chk.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (a == 0 && getNum1 == 9) {
            urNum1.setText("0"); }
        else if (a == 1 && getNum1 == 0) {
            urNum1.setText("1"); }
        else if (a == 2 && getNum1 == 1) {
            urNum1.setText("2"); }
        else if (a == 3 && getNum1 == 2) {
            urNum1.setText("3");  }
        else if (a == 4 && getNum1 == 3) {
            urNum1.setText("4"); }
        else if (a == 5 && getNum1 == 4) {
            urNum1.setText("5"); }
        else if (a == 6 && getNum1 == 5) {
            urNum1.setText("6"); }
        else if (a == 7 && getNum1 == 6) {
            urNum1.setText("7"); }
        else if (a == 8 && getNum1 == 7) {
            urNum1.setText("8"); }
        else if (a == 9 && getNum1 == 8) {
            urNum1.setText("9"); }

//incrementing the guessed number

up1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getNum1 = Integer.parseInt(myNum1.getText().toString());
                if (getNum1 == 0) {
                    myNum1.setText("1"); }
                else if (getNum1 == 1 ) {
                    myNum1.setText("2"); }
                else if (getNum1 == 2) {
                    myNum1.setText("3"); }
                else if (getNum1 == 3) {
                    myNum1.setText("4"); }
                else if (getNum1 == 4) {
                    myNum1.setText("5"); }
                else if (getNum1 == 5) {
                    myNum1.setText("6"); }
                else if (getNum1 == 6) {
                    myNum1.setText("7"); }
                else if (getNum1 == 7) {
                    myNum1.setText("8"); }
                else if (getNum1 == 8) {
                    myNum1.setText("9"); }
                else if (getNum1 == 9) {
                    myNum1.setText("0"); }
                });

//decrementing the guessed number

dn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getNum1 = Integer.parseInt(myNum1.getText().toString());
                if (getNum1 == 0) {
                    myNum1.setText("9"); }
                else if (getNum1 == 9 ) {
                    myNum1.setText("8"); }
                else if (getNum1 == 8) {
                    myNum1.setText("7"); }
                else if (getNum1 == 7) {
                    myNum1.setText("6"); }
                else if (getNum1 == 6) {
                    myNum1.setText("5"); }
                else if (getNum1 == 5) {
                    myNum1.setText("4"); }
                else if (getNum1 == 4) {
                    myNum1.setText("3"); }
                else if (getNum1 == 3) {
                    myNum1.setText("2"); }
                else if (getNum1 == 2) {
                    myNum1.setText("1"); }
                else if (getNum1 == 1) {
                    myNum1.setText("0"); }
            }
        });

The problem I am running into is that when up1 is pressed, the numbers tend to match up when I check them, but when I press dn1 to get to the matched number, my chosen number is lower than the matched number by two. It may be because my coding is convoluted, and I could probably make it better with using ++ incrementing, but I can't seem to get that to work right either.

Body:
I have figured out the solution on my own, if anyone has run into this issue as well. In the code where I change the myNum value by incrementing/decrementing the value, I'm only checking the current value for each condition of the 'if' statement without also changing the value within. So no matter how many times I check it, it will always be one off. My fix:

getNum1 = Integer.parseInt(myNum1.getText().toString());
    if (getNum1 == 0) {
        myNum1.setText("9");
        getNum1 = 9; }
    else if (getNum1 == 9 ) {
        myNum1.setText("8");
        getNum1 = 8; }
    else if (getNum1 == 8) {
        myNum1.setText("7");
        getNum1 = 7; }

And so on from there.


问:
Read file in document library : "The label that's applied to this item..." C#
I'm trying to read content of a file as stream in document library on sharepoint online site.
I'm using AppOnlyAccessToken. Source code work fine before today. And I have no idea for this problem.
My source code:

```<code>string realm = TokenHelper.GetRealmFromTargetUrl(SiteUrl);
var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, SiteUrl.Authority, realm);

var context = TokenHelper.GetClientContextWithAccessToken(SiteUrl.ToString(), token.AccessToken);

//Initial
Stream stream = null;

var list = context.Web.GetList("/sites/mysites/mydoclib");

var document = list.GetItemById(fileId);
context.Load(document.File);
context.ExecuteQuery();

////Read File and return stream content of file
var streamX = document.File.OpenBinaryStream();

context.ExecuteQuery();
stream = streamX.Value;
return stream;
</code>```

Error when ExecuteQuery() to get BinaryStream.
Error Message:

The label that's applied to this item prevents it from being edited or deleted. Check the item's label for more details.

It work with txt file and get error with csv and excel (xlsx) file.

答:
The issue is resolved with recreating (revert to full access and then adjust what you need) SharePoint Online Access Policies for Azure Active Directory - Conditional Access.

Ref:
https://TENANT-admin.sharepoint.com/_layouts/15/online/TenantAccessPolicies.aspx
https://portal.azure.com/#blade/Microsoft_AAD_IAM/ConditionalAccessBlade/Policies

Error message is wrong and it does not have nothing with labels on https://protection.office.com

Body:
I'm trying to read content of a file as stream in document library on sharepoint online site.
I'm using AppOnlyAccessToken. Source code work fine before today. And I have no idea for this problem.
My source code:

string realm = TokenHelper.GetRealmFromTargetUrl(SiteUrl);
var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, SiteUrl.Authority, realm);

var context = TokenHelper.GetClientContextWithAccessToken(SiteUrl.ToString(), token.AccessToken);

//Initial
Stream stream = null;

var list = context.Web.GetList("/sites/mysites/mydoclib");

var document = list.GetItemById(fileId);
context.Load(document.File);
context.ExecuteQuery();

////Read File and return stream content of file
var streamX = document.File.OpenBinaryStream();

context.ExecuteQuery();
stream = streamX.Value;
return stream;

Error when ExecuteQuery() to get BinaryStream.
Error Message:

The label that's applied to this item prevents it from being edited or deleted. Check the item's label for more details.

It work with txt file and get error with csv and excel (xlsx) file.


问:
How to remove duplicate values of only one column element based on another column
I have data where I have one element of interest (111) in a column. My data looks something like this:

```<code>pcp2 <- data.frame(A = c(rep(111, 4), rep(222, 5), rep(111,5),
        rep(222,5)),B= c(rep(1,9), rep(2,10)))

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   222 1
7   222 1
8   222 1
9   222 1
10  111 2
11  111 2
12  111 2
13  111 2
14  111 2
15  222 2
16  222 2
17  222 2
18  222 2
19  222 2
</code>```

I want to collapse all of only variable 222 and leave all 111 untouched throughout my data based upon the IDs in column B like so:

```<code>     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   111 2
7   111 2
8   111 2
9   111 2
10  111 2
11  222 2
</code>```

All I have been able to find that is close reduces all the variables (both 111 and 222).

```<code>library(data.table)
dat <- as.data.table(pcp2, key = "B")
data <- dat[, by = key(dat)][!duplicated(A == "222")]
</code>```

as follows:

```<code>   A    B
1 111   1
2 222   2
</code>```

I've played around with various iterations of this code and others, but other things I've tried as well have just gotten my data down to two rows or collapsed both 111 and 222. I.e. this wouldn't be sufficient:

```<code>   A  B
1 111 1
2 222 2
3 111 2
4 222 2
</code>```

Does anyone have any guidance for how you would maintain the 111 and collapse the 222 within one column based on another column like the example (B in this case)? I know other examples are similar but none seem to give the option to specify not collapsing a particular variable within one column while collapsing the other(s).

答:
I would phrase your goal as "keep rows that are not duplicated or where A is 111", with the understanding that duplicated is FALSE for the first occurrence.

duplicated(pcp2) looks at all columns, so we don't need to worry about the "within each B group" stuff. If you have other columns hanging around, only give duplicated the relevant columns, something like duplicated(pcp2[c("A", "B")]).

```<code>pcp2[!duplicated(pcp2) | pcp2$A == 111, ]
#      A B
# 1  111 1
# 2  111 1
# 3  111 1
# 4  111 1
# 5  222 1
# 10 111 2
# 11 111 2
# 12 111 2
# 13 111 2
# 14 111 2
# 15 222 2
</code>```

Body:
I have data where I have one element of interest (111) in a column. My data looks something like this:

pcp2 <- data.frame(A = c(rep(111, 4), rep(222, 5), rep(111,5),
        rep(222,5)),B= c(rep(1,9), rep(2,10)))

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   222 1
7   222 1
8   222 1
9   222 1
10  111 2
11  111 2
12  111 2
13  111 2
14  111 2
15  222 2
16  222 2
17  222 2
18  222 2
19  222 2

I want to collapse all of only variable 222 and leave all 111 untouched throughout my data based upon the IDs in column B like so:

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   111 2
7   111 2
8   111 2
9   111 2
10  111 2
11  222 2

All I have been able to find that is close reduces all the variables (both 111 and 222).

library(data.table)
dat <- as.data.table(pcp2, key = "B")
data <- dat[, by = key(dat)][!duplicated(A == "222")]

as follows:

   A    B
1 111   1
2 222   2

I've played around with various iterations of this code and others, but other things I've tried as well have just gotten my data down to two rows or collapsed both 111 and 222. I.e. this wouldn't be sufficient:

   A  B
1 111 1
2 222 2
3 111 2
4 222 2

Does anyone have any guidance for how you would maintain the 111 and collapse the 222 within one column based on another column like the example (B in this case)? I know other examples are similar but none seem to give the option to specify not collapsing a particular variable within one column while collapsing the other(s).

Body:
I would phrase your goal as "keep rows that are not duplicated or where A is 111", with the understanding that duplicated is FALSE for the first occurrence.

duplicated(pcp2) looks at all columns, so we don't need to worry about the "within each B group" stuff. If you have other columns hanging around, only give duplicated the relevant columns, something like duplicated(pcp2[c("A", "B")]).

pcp2[!duplicated(pcp2) | pcp2$A == 111, ]
#      A B
# 1  111 1
# 2  111 1
# 3  111 1
# 4  111 1
# 5  222 1
# 10 111 2
# 11 111 2
# 12 111 2
# 13 111 2
# 14 111 2
# 15 222 2


问:
Progressbar foreground color
Does anybody know how to change the foreground color of a WPF-Progressbar. It always seems to be merged with green.</p>

答:
Unfortunately, it is hard coded in default style:

```<code><Trigger Property="IsIndeterminate"
     Value="false">
<Setter TargetName="Animation"
    Property="Background"
    Value="#80B5FFA9"/>
</code>```

You can create your own style from original XAML or try to override background in the Loaded event for example:

```<code>private void ProgressBar_Loaded(object sender, RoutedEventArgs e)
{
    var p = (ProgressBar)sender;
    p.ApplyTemplate();

    ((Panel)p.Template.FindName("Animation", p)).Background = Brushes.Red;
}
</code>```

but it's unreliable

Title: Progressbar foreground color

Body:
Unfortunately, it is hard coded in default style:

<Trigger Property="IsIndeterminate"
     Value="false">
<Setter TargetName="Animation"
    Property="Background"
    Value="#80B5FFA9"/>

You can create your own style from original XAML or try to override background in the Loaded event for example:

private void ProgressBar_Loaded(object sender, RoutedEventArgs e)
{
    var p = (ProgressBar)sender;
    p.ApplyTemplate();

    ((Panel)p.Template.FindName("Animation", p)).Background = Brushes.Red;
}

but it's unreliable


问:
HDP 2.6.1.0 - Error Finalizing HDP upgrade Failed on: Save Cluster State
I'm trying to upgrade from hdp-2.4.0 to hdp-2.6.1
Updated ambari to 2.5 and all went ok, all services are green and all service checks run smoothly .
When I do the express upgrade to hdp-2.6.1 it gives error in the last part .
I've followed this article but when I restart the server it gives this error:

Error

Is there any workaround for this?

Many thanks in advance.

Best regards

答:
I had the same issue - both on the upgrade direction from 2.5.0.0 to 2.6.2 and on the downgrade back to 2.5.0.0. Tried lots of stuff both via ambari-server and database surgery and eventually what did the trick was to nullify the reference to upgrade (downgrade) in the clusters table followed by ambari-server restart

psql -U ambari ambari

default password is bigdata

ambari=> select * from clusters;

cluster_id | resource_id | cluster_info | cluster_name | provisioning_state | s
ecurity_type | desired_cluster_state | desired_stack_id | upgrade_id
------------+-------------+--------------+--------------+--------------------+--
-------------+-----------------------+------------------+------------
          2 |           4 |              | myclus       | INSTALLED          | N
ONE          |                       |               51 |         52
(1 row)

ambari=> update clusters set upgrade_id = null where cluster_id = 2;
UPDATE 1

ambari=> select * from clusters;
 cluster_id | resource_id | cluster_info | cluster_name | provisioning_state | s
ecurity_type | desired_cluster_state | desired_stack_id | upgrade_id
------------+-------------+--------------+--------------+--------------------+--
-------------+-----------------------+------------------+------------
          2 |           4 |              | myclus       | INSTALLED          | N
ONE          |                       |               51 |
(1 row)


问:
Manually change colour of one factor level in ggplot2 stacked barplot
I'm giving a presentation, and would like to highlight the rate of occurrence of one of my factor levels on a slide by retaining the colour of this particular factor level, whilst greying out the other factor levels across other variables.

Using the Arthritis data set in the vcd library as an example:

```<code>library(vcd)
ggplot(Arthritis, aes(x = Sex, fill = Improved)) + geom_bar(position = "fill")
</code>```

When, for example, I’m telling the audience about the marked improvement in the males, can I have a version of the plot which retains the colour of marked improvement in males, but greys out everything else? Preferably by using different shades of grey to keep the boundaries?

答:
Add

scale_fill_manual(values=c("Marked" = "RoyalBlue", "Some" = "DarkGrey", "None"="LightGrey"))

Full ggplot call:

```<code>ggplot(Arthritis, aes(x = Sex, fill = Improved)) +
  geom_bar(position = "fill")+
  scale_fill_manual(values=c("Marked" = "RoyalBlue", "Some" = "DarkGrey", "None"="LightGrey"))
</code>```

Body:
I'm giving a presentation, and would like to highlight the rate of occurrence of one of my factor levels on a slide by retaining the colour of this particular factor level, whilst greying out the other factor levels across other variables.

Using the Arthritis data set in the vcd library as an example:

library(vcd)
ggplot(Arthritis, aes(x = Sex, fill = Improved)) + geom_bar(position = "fill")

When, for example, I’m telling the audience about the marked improvement in the males, can I have a version of the plot which retains the colour of marked improvement in males, but greys out everything else? Preferably by using different shades of grey to keep the boundaries?

Body:
Add

scale_fill_manual(values=c("Marked" = "RoyalBlue", "Some" = "DarkGrey", "None"="LightGrey"))

Full ggplot call:

ggplot(Arthritis, aes(x = Sex, fill = Improved)) +
  geom_bar(position = "fill")+
  scale_fill_manual(values=c("Marked" = "RoyalBlue", "Some" = "DarkGrey", "None"="LightGrey"))


问:
Can't Solve google scholar search picture CAPTCHA
I am using a script called Google Scholar Citation Explorer, its a nice script that allows one to search for scientific articles. However the newer versions of Google Chrome or Firefox does not work with it. I've resorted to using firefox version 3.6 which works.

However on firefox version 3.6 the reCAPTCHA does not work, so i am blocked from using google scholar.

Does anyone know a workaround? is there any way to use the keyboard to solve the reCAPTCHA?.

答:
I found that Google Scholar Citation Explorer works on firefox version 15.0
where the reCAPTCHA also works. Which I have detailed in this youtube video: </p>


问:
How to secure .env file in laravel using file permission?
My env file which has all the credentials is accessible through URL.
I found a few questions like How to secure .env file in laravel 5.4? which says to use htaccess to prevent users from accessing the file.

But I prefer using file permission so I changed permission to 0111 which is execute only but I found that the file is not accessible by the internal files as well so my question is what is the right permission.

And is it fine to depend on file permission for security purpose.

答:
I had to call my hosting provider to know the permission so that my website is working fine and the permission are also fine so that my file not accessible directly.

So the necessary permission is 0600 which makes it accessible on the website but not through URL.

For .htaccess the solution I was not comfortable with follow:
How protect .env file laravel

Here's the script as per the top rated answer in above :

```<code>#Disable index view
options -Indexes

#hide a Specifuc File

<Files .env>
order allow,deny
Deny from all
</Files>
</code>```

Body:
I had to call my hosting provider to know the permission so that my website is working fine and the permission are also fine so that my file not accessible directly.

So the necessary permission is 0600 which makes it accessible on the website but not through URL.

For .htaccess the solution I was not comfortable with follow:
How protect .env file laravel

Here's the script as per the top rated answer in above :

#Disable index view
options -Indexes

#hide a Specifuc File

<Files .env>
order allow,deny
Deny from all
</Files>

ContentLicense: CC BY-SA 4.0


问:
Mock_open CSV file not getting any data
I am trying to unit test a piece of code:

```<code>def _parse_results(self, file_name):
    results_file = open(file_name)
    results_data = list(csv.reader(results_file))
    index = len(results_data[1])-1
    results_file.close()
    return float(results_data[1][index])
</code>```

by using mock_open like so:

```<code>@mock.patch('path.open', mock.mock_open(read_data='test, test2, test3, test4'))
def test_parse_results(self):
    cut = my_class(emulate=True)
    self.assertEqual(VAL, cut._parse_results('file'))
</code>```

The problem I am running into is that I do not get any data when running csv.reader. If I run results_file.readlines() I get 'test, test2, test3, test4' which means that mock_open is working properly. But when I run csv.reader(results_file) I lose all the data.

答:
This is because mock_open doesn't implement every feature that a file has, and notably not some of the ones that csv needs.

mock_open implements the methods read(), readline() and readlines(), and works both as a function and when called as a context manager (https://docs.python.org/3/library/unittest.mock.html#mock-open), whereas csv.reader works with…

any object which supports the iterator protocol and returns a string each time its __next__() method is called — file objects and list objects are both suitable

— https://docs.python.org/3/library/csv.html#csv.reader

Note that mock_open doesn't implement the __next__() method, and doesn't raise StopIteration when the end is reached, so it won't work with csv.reader.

The solution, as @Emily points out in her answer, is to turn the file into a list of its lines. This is possible because mock_open implements readlines(), and the resulting list is suitable for reading into csv.reader as the documentation says.

Title: Mock_open CSV file not getting any data

Body:
I am trying to unit test a piece of code:

def _parse_results(self, file_name):
    results_file = open(file_name)
    results_data = list(csv.reader(results_file))
    index = len(results_data[1])-1
    results_file.close()
    return float(results_data[1][index])

by using mock_open like so:

@mock.patch('path.open', mock.mock_open(read_data='test, test2, test3, test4'))
def test_parse_results(self):
    cut = my_class(emulate=True)
    self.assertEqual(VAL, cut._parse_results('file'))

The problem I am running into is that I do not get any data when running csv.reader. If I run results_file.readlines() I get 'test, test2, test3, test4' which means that mock_open is working properly. But when I run csv.reader(results_file) I lose all the data.


问:
* gather argument in plt.scatter?
I am reading this website and found this line of code:

```<code>for i in centroids.keys():
    plt.scatter(*centroids[i], color=colmap[i])
</code>```

I understand * is used to gather an arbitrary length of arguments so we don't have to explicitly specify all the arguments, right?

But why does this person write the * here?

Especially since after removing the *, the line seem to produce the same result.

The complete code:

```<code>## Initialisation

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame({
    'x': [12, 20, 28, 18, 29, 33, 24, 45, 45, 52, 51, 52, 55, 53, 55,         61, 64, 69, 72],
    'y': [39, 36, 30, 52, 54, 46, 55, 59, 63, 70, 66, 63, 58, 23, 14,     8, 19, 7, 24]
})

np.random.seed(200)
k = 3
# centroids[i] = [x, y]
centroids = {
    i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
    for i in range(k)
}

fig = plt.figure(figsize=(5, 5))
plt.scatter(df['x'], df['y'], color='k')
colmap = {1: 'r', 2: 'g', 3: 'b'}
for i in centroids.keys():
    plt.scatter(*centroids[i], color=colmap[i])
plt.xlim(0, 80)
plt.ylim(0, 80)
plt.show()
</code>```

答:
Axes.scatter(x, y, ...) takes two arguments x and y.

When removing the asterix you have one single argument only, hence plt.scatter(centroids[i], color=colmap[i]) should throw a TypeError: scatter() takes at least 2 arguments (1 given).

The alternative would be to split the argument beforehands,

```<code>x,y = centroids[i]
plt.scatter(x,y, color=colmap[i])
</code>```

Title: * gather argument in plt.scatter?

Body:
I am reading this website and found this line of code:

for i in centroids.keys():
    plt.scatter(*centroids[i], color=colmap[i])

I understand * is used to gather an arbitrary length of arguments so we don't have to explicitly specify all the arguments, right?

But why does this person write the * here?

Especially since after removing the *, the line seem to produce the same result.

The complete code:

## Initialisation

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame({
    'x': [12, 20, 28, 18, 29, 33, 24, 45, 45, 52, 51, 52, 55, 53, 55,         61, 64, 69, 72],
    'y': [39, 36, 30, 52, 54, 46, 55, 59, 63, 70, 66, 63, 58, 23, 14,     8, 19, 7, 24]
})

np.random.seed(200)
k = 3
# centroids[i] = [x, y]
centroids = {
    i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
    for i in range(k)
}

fig = plt.figure(figsize=(5, 5))
plt.scatter(df['x'], df['y'], color='k')
colmap = {1: 'r', 2: 'g', 3: 'b'}
for i in centroids.keys():
    plt.scatter(*centroids[i], color=colmap[i])
plt.xlim(0, 80)
plt.ylim(0, 80)
plt.show()

Body:
Axes.scatter(x, y, ...) takes two arguments x and y.

When removing the asterix you have one single argument only, hence plt.scatter(centroids[i], color=colmap[i]) should throw a TypeError: scatter() takes at least 2 arguments (1 given).

The alternative would be to split the argument beforehands,

x,y = centroids[i]
plt.scatter(x,y, color=colmap[i])


问:
Angular Show Password after click
I have an inventory page that also contains a password field.
I would like to hide the password when the page is loaded, best would be to have points displayed **** and after click password is shown or a pop up.

JS

```<code>   var get_cert = function () {
        $http.get($scope.url.cert_list).then(
            function (response) {
                $scope.certs = response.data;
            }
        );
    }
    // execute get function
    get_cert();
</code>```

HTML

```<code><div class="panel panel-default">
    <table class="table table-striped valign_middle">
        <tr class="table_header">
            <td>Name</td>
            <td>Pass</td>
        </tr>
        <tr ng-repeat="cert in certs | filter:search | orderBy:['name']">
            <td>{{cert.name}}</td>
            <td>
                <button class="w3-btn w3-black w3-hover-green w3-ripple" ng-click="get_cert()">Show</button>
                 <span ng-show="get_cert()">{{cert.password}}</span>
            </td>

        </tr>
    </table>
</code>```

答:
```<code><button ng-show="!cert.showPw" class="w3-btn w3-black w3-hover-green w3-ripple" ng-click="cert.showPw = true">Show</button>
<span ng-show="cert.showPw">{{cert.password}}</span>
</code>```

You can use ng-click to do cert.showPw = true, which will append a property called showPw (a boolean) to the object. Combined with ng-show, you can easily switch between the two.

This way you'll keep your controller free of any additional logic needed. You may include ng-click on the span which holds the password which will set showPw = false to switch it back to a button.

See my JSFiddle for full example.

Title: Angular Show Password after click

Body:
I have an inventory page that also contains a password field.
I would like to hide the password when the page is loaded, best would be to have points displayed **** and after click password is shown or a pop up.

JS

   var get_cert = function () {
        $http.get($scope.url.cert_list).then(
            function (response) {
                $scope.certs = response.data;
            }
        );
    }
    // execute get function
    get_cert();

HTML

            Name
            Pass

            {{cert.name}}

                <button class="w3-btn w3-black w3-hover-green w3-ripple" ng-click="get_cert()">Show</button>
                 {{cert.password}}

Body:
<button ng-show="!cert.showPw" class="w3-btn w3-black w3-hover-green w3-ripple" ng-click="cert.showPw = true">Show</button>
<span ng-show="cert.showPw">{{cert.password}}</span>

You can use ng-click to do cert.showPw = true, which will append a property called showPw (a boolean) to the object. Combined with ng-show, you can easily switch between the two.

This way you'll keep your controller free of any additional logic needed. You may include ng-click on the span which holds the password which will set showPw = false to switch it back to a button.

See my JSFiddle for full example.


问:
Strange geom_vline() behavior in ggplot when using coord_trans() with custom transformation
I am trying to use a log-modulus transformation in my plot. It was working fine...

```<code>library(tidyverse)
library(scales)

log_modulus_trans <- function()
  trans_new(name = "log_modulus",
            transform = function(x) sign(x) * log(abs(x) + 1),
            inverse = function(x) sign(x) * ( exp(abs(x)) - 1 ))

# fake data
set.seed(1)
d <- data_frame(
  tt = rep(1:10, 3),
  cc = rep(LETTERS[1:3], each = 10),
  xx = c(rnorm(10, mean = 100, sd = 10),
         rnorm(10, mean = 0, sd = 10),
         rnorm(10, mean = -100, sd = 10)))

ggplot(data = d,
       mapping = aes(x = tt, y = xx, group = cc)) +
  geom_line() +
  coord_trans(y = "log_modulus")
</code>```

When I tried to add a geom_vline() things got weird...

```<code>ggplot(data = d,
       mapping = aes(x = tt, y = xx, group = cc)) +
  geom_line() +
  coord_trans(y = "log_modulus") +
  geom_vline(xintercept = 5)
</code>```

Any idea how to get geom_vline() to go from the top to the bottom of the plot window... or a work around hack?

答:
Here is a solution using geom_segment

```<code>ggplot(data = d,
       mapping = aes(x = tt, y = xx, group = cc)) +
  geom_line() +
  geom_segment(x = 5, xend = 5, y = -150, yend = 150) +
  coord_trans(y = "log_modulus")
</code>```

Body:
I am trying to use a log-modulus transformation in my plot. It was working fine...

library(tidyverse)
library(scales)

log_modulus_trans <- function()
  trans_new(name = "log_modulus",
            transform = function(x) sign(x) * log(abs(x) + 1),
            inverse = function(x) sign(x) * ( exp(abs(x)) - 1 ))

# fake data
set.seed(1)
d <- data_frame(
  tt = rep(1:10, 3),
  cc = rep(LETTERS[1:3], each = 10),
  xx = c(rnorm(10, mean = 100, sd = 10),
         rnorm(10, mean = 0, sd = 10),
         rnorm(10, mean = -100, sd = 10)))

ggplot(data = d,
       mapping = aes(x = tt, y = xx, group = cc)) +
  geom_line() +
  coord_trans(y = "log_modulus")

When I tried to add a geom_vline() things got weird...

ggplot(data = d,
       mapping = aes(x = tt, y = xx, group = cc)) +
  geom_line() +
  coord_trans(y = "log_modulus") +
  geom_vline(xintercept = 5)

Any idea how to get geom_vline() to go from the top to the bottom of the plot window... or a work around hack?

Body:
Here is a solution using geom_segment

ggplot(data = d,
       mapping = aes(x = tt, y = xx, group = cc)) +
  geom_line() +
  geom_segment(x = 5, xend = 5, y = -150, yend = 150) +
  coord_trans(y = "log_modulus")


问:
Haskell binary search tree with custom data
I want to create a binary search tree of custom data type Book. Book has two attributes, name and page. I want to use attribute page as the node of the tree. I've stuck at defining the tree. Can anyone help me with any resource? Here is the code I've tried (it's not working)</p>

```<code>import System.IO
import Data.List

data Book = Book{
    name:: String,
    page::Int
}deriving (Show)

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

singleton :: (Book _ x) -> Tree x
singleton (Book _ x) = Node x EmptyTree EmptyTree

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert (Book _ x) EmptyTree = singleton (Book _ x)
treeInsert (Book _ x) (Node a left right)
    | x == a = Node x left right
    | x < a  = Node a (treeInsert (Book _ x) left) right
    | x > a  = Node a left (treeInsert (Book _ x) right)
</code>```

答:
I recommend to you to use all the book entity and make and Ord instance for Book.

```<code>instance Eq Book where
    (Book _ n1) == (Book _ n2) = n1 == n2

instance Ord Book where
    (Book _ n1) > (Book _ n2) = n1 > n2
</code>```

And change your code to this:

```<code>data Book = Book {
    name :: String,
    page :: Int
} deriving (Show)

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
    | x == a = Node x left right
    | x < a  = Node a (treeInsert x left) right
    | x > a  = Node a left (treeInsert x right)
</code>```

You will see that (Book _ n) is not a correct type, Book is.

And a will use values of any type to treeInsert since Book implements Ord.

Body:
I want to create a binary search tree of custom data type Book. Book has two attributes, name and page. I want to use attribute page as the node of the tree. I've stuck at defining the tree. Can anyone help me with any resource? Here is the code I've tried (it's not working)

import System.IO
import Data.List

data Book = Book{
    name:: String,
    page::Int
}deriving (Show)

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

singleton :: (Book _ x) -> Tree x
singleton (Book _ x) = Node x EmptyTree EmptyTree

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert (Book _ x) EmptyTree = singleton (Book _ x)
treeInsert (Book _ x) (Node a left right)
    | x == a = Node x left right
    | x  a  = Node a left (treeInsert (Book _ x) right)

Body:
I recommend to you to use all the book entity and make and Ord instance for Book.

instance Eq Book where
    (Book _ n1) == (Book _ n2) = n1 == n2

instance Ord Book where
    (Book _ n1) > (Book _ n2) = n1 > n2

And change your code to this:

data Book = Book {
    name :: String,
    page :: Int
} deriving (Show)

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
    | x == a = Node x left right
    | x < a  = Node a (treeInsert x left) right
    | x > a  = Node a left (treeInsert x right)

You will see that (Book _ n) is not a correct type, Book is.

And a will use values of any type to treeInsert since Book implements Ord.


问:
nodejs prioritise function execution
I've edited a library (ddp-client) to make use of a heartbeat timer, which sends out a ping every X seconds. However, I'm also doing some work with the bluetooth hardware, which I believe is responsible for pings sometimes not returning in time (because the bluetooth seems to block the event loop temporarily). Is there a way to prioritise a certain function on the event loop, so it will always be executed before others? I don't think setImmediate would be suitable here, since I don't know exactly when the response message from the server would arrive.

The implementation of the timer is roughly as follows:

```<code>every X seconds
if(ping outstanding) {
  //Did not resolve in time
  closeConnection()
} else {
  ping outstanding = true
  sendPing()
}
</code>```

This works perfectly fine if I run it without the bluetooth module. When I enable the bluetooth module, pings sometimes do not get resolved because the time taken to scan for bluetooth is sometimes longer than the interval of the timer, leading to a disconnect, while it's actually still connected.

答:
Is there a way to prioritise a certain function on the event loop, so it will always be executed before others?

No.  node.js does not have a way for one piece of code to pre-empt another and always have priority.  Any code that "hogs" the CPU a bit or otherwise blocks the event loop a bit should either be fixed to not do that or it can be moved into it's own child process and you can communicate with it via any one of the many interprocess communication schemes.

Or, alternatively, if the ping timer is really, really important to run on time, then maybe it should be in its own child process where it can always just run as scheduled with no chance of something else interrupting it.

Implementing precise timers like this is one thing that node.js is just not good at.  Because it runs all your Javascript in a single thread, keeping a server instantly responsive or keeping timers running precisely on time requires that nobody ever blocks the event loop or hogs the CPU for longer than your timing threshold.  The usual work-around is to move things into their own child process where they get their own priority with the CPU.

Title: nodejs prioritise function execution

Body:
I've edited a library (ddp-client) to make use of a heartbeat timer, which sends out a ping every X seconds. However, I'm also doing some work with the bluetooth hardware, which I believe is responsible for pings sometimes not returning in time (because the bluetooth seems to block the event loop temporarily). Is there a way to prioritise a certain function on the event loop, so it will always be executed before others? I don't think setImmediate would be suitable here, since I don't know exactly when the response message from the server would arrive.

The implementation of the timer is roughly as follows:

every X seconds
if(ping outstanding) {
  //Did not resolve in time
  closeConnection()
} else {
  ping outstanding = true
  sendPing()
}

This works perfectly fine if I run it without the bluetooth module. When I enable the bluetooth module, pings sometimes do not get resolved because the time taken to scan for bluetooth is sometimes longer than the interval of the timer, leading to a disconnect, while it's actually still connected.


问:
Add a tooltip to a div
I have a div tag like this:

  Name
  <input type="text"/>

```

How can I displaying a tooltip on :hover of the div, preferably with a fade in/out effect.

答:
And my version

```<code>.tooltip{
display: inline;
position: relative; /** very important set to relative*/
}

.tooltip:hover:after{
background: #333;
background: rgba(0,0,0,.8);
border-radius: 5px;
bottom: 26px;
color: #fff;
content: attr(title); /**extract the content from the title */
left: 20%;
padding: 5px 15px;
position: absolute;
z-index: 98;
width: 220px;
}

.tooltip:hover:before{
border: solid;
border-color: #333 transparent;
border-width: 6px 6px 0 6px;
bottom: 20px;
content: "";
left: 50%;
position: absolute;
z-index: 99;
}
</code>```

Then the HTML

```<code><div title="This is some information for our tooltip." class="tooltip">bar </div>
</code>```

Title: Add a tooltip to a div

Body:
I have a div tag like this:

  Name
  <input type="text"/>

How can I displaying a tooltip on :hover of the div, preferably with a fade in/out effect.

Body:
And my version

.tooltip{
display: inline;
position: relative; /** very important set to relative*/
}

.tooltip:hover:after{
background: #333;
background: rgba(0,0,0,.8);
border-radius: 5px;
bottom: 26px;
color: #fff;
content: attr(title); /**extract the content from the title */
left: 20%;
padding: 5px 15px;
position: absolute;
z-index: 98;
width: 220px;
}

.tooltip:hover:before{
border: solid;
border-color: #333 transparent;
border-width: 6px 6px 0 6px;
bottom: 20px;
content: "";
left: 50%;
position: absolute;
z-index: 99;
}

Then the HTML

<div title="This is some information for our tooltip." class="tooltip">bar </div>


问:
Returning JSON object as response in Spring Boot
I have a sample RestController in Spring Boot:

```<code>@RestController
@RequestMapping("/api")
class MyRestController
{
    @GetMapping(path = "/hello")
    public JSONObject sayHello()
    {
        return new JSONObject("{'aa':'bb'}");
    }
}
</code>```

I am using the JSON library org.json

When I hit API /hello, I get an exception saying :

Servlet.service() for servlet [dispatcherServlet] in context with path
  [] threw exception [Request processing failed; nested exception is
  java.lang.IllegalArgumentException: No converter found for return
  value of type: class org.json.JSONObject] with root cause

java.lang.IllegalArgumentException: No converter found for return
  value of type: class org.json.JSONObject

What is the issue? Can someone explain what exactly is happening?

答:
```<code>@RequestMapping("/api/status")
public Map doSomething()
{
    return Collections.singletonMap("status", myService.doSomething());
}
</code>```

PS. Works only for 1 value

Body:
I have a sample RestController in Spring Boot:

@RestController
@RequestMapping("/api")
class MyRestController
{
    @GetMapping(path = "/hello")
    public JSONObject sayHello()
    {
        return new JSONObject("{'aa':'bb'}");
    }
}

I am using the JSON library org.json

When I hit API /hello, I get an exception saying :

Servlet.service() for servlet [dispatcherServlet] in context with path
  [] threw exception [Request processing failed; nested exception is
  java.lang.IllegalArgumentException: No converter found for return
  value of type: class org.json.JSONObject] with root cause

java.lang.IllegalArgumentException: No converter found for return
  value of type: class org.json.JSONObject

What is the issue? Can someone explain what exactly is happening?

Body:
@RequestMapping("/api/status")
public Map doSomething()
{
    return Collections.singletonMap("status", myService.doSomething());
}

PS. Works only for 1 value


问:
Datasource Dicitionary Combobox get value selected combobox c#
my problem i that i cant read the value of the selected dictionary pair of the combobox

I have used binding for the combobox

```<code>comboBoxNutzungsart.DataSource = new BindingSource(Zordnung.dieListe, null);
comboBoxNutzungsart.DisplayMember = "Key";
comboBoxNutzungsart.ValueMember = "Value";
</code>```

Here is my Dictionary "dieListe"

```<code>public static class Zordnung
{
    public static Dictionary<String, Double> dieListe = new Dictionary<String, double>()
    {
        {"Bitte auswählen", 0},
        {"Wohnung", 50},
        {"Büro",
    }
}
</code>```

Now i want the value of the chosen Key, but nothin i try success

I tried this:

```<code>private void comboBoxNutzungsart_SelectedIndexChanged(object sender, EventArgs e)
{
    double BerechneterWert;
    string text = comboBoxNutzungsart.Text;
    double zahl = Zordnung.dieListe[text]
}
</code>```

but with this the whole element in the dictionary will appear  text ="[Bitte auswählen, 0]"

and with something like this

```<code>Dictionary<string, double> selectes =
    (Dictionary<string, double>)comboBoxNutzungsart.SelectedItem;
</code>```

i get a Dictionary with the selected Item how do i get the value?

答:
It looks like the problem you're running into is that the comboBox items are all objects of type KeyValuePair<string, double>, but you're just accessing the ToString() implementation of that type when you get the .Text property.

What you can do is cast the item to the actual type, and then you can access the Value (or the Key):

```<code>private void comboBoxNutzungsart_SelectedIndexChanged(object sender, EventArgs e)
{
    var selectedItem = (KeyValuePair<string, double>) comboBoxNutzungsart.SelectedItem;
    string text = selectedItem.Key;
    double zahl = selectedItem.Value;
}
</code>```

Edit

Another thought is that if you just need the Value, then you could access it from Zordnung.dieListe by getting the Values as a list and accessing the item at the same index as comboBoxNutzungsart.SelectedIndex:

```<code>double zahl2 = Zordnung.dieListe.Values.ToList()[comboBoxNutzungsart.SelectedIndex];
</code>```

Body:
my problem i that i cant read the value of the selected dictionary pair of the combobox

I have used binding for the combobox

comboBoxNutzungsart.DataSource = new BindingSource(Zordnung.dieListe, null);
comboBoxNutzungsart.DisplayMember = "Key";
comboBoxNutzungsart.ValueMember = "Value";

Here is my Dictionary "dieListe"

public static class Zordnung
{
    public static Dictionary<String, Double> dieListe = new Dictionary<String, double>()
    {
        {"Bitte auswählen", 0},
        {"Wohnung", 50},
        {"Büro",
    }
}

Now i want the value of the chosen Key, but nothin i try success

I tried this:

private void comboBoxNutzungsart_SelectedIndexChanged(object sender, EventArgs e)
{
    double BerechneterWert;
    string text = comboBoxNutzungsart.Text;
    double zahl = Zordnung.dieListe[text]
}

but with this the whole element in the dictionary will appear  text ="[Bitte auswählen, 0]"

and with something like this

Dictionary<string, double> selectes =
    (Dictionary<string, double>)comboBoxNutzungsart.SelectedItem;

i get a Dictionary with the selected Item how do i get the value?

Body:
It looks like the problem you're running into is that the comboBox items are all objects of type KeyValuePair<string, double>, but you're just accessing the ToString() implementation of that type when you get the .Text property.

What you can do is cast the item to the actual type, and then you can access the Value (or the Key):

private void comboBoxNutzungsart_SelectedIndexChanged(object sender, EventArgs e)
{
    var selectedItem = (KeyValuePair<string, double>) comboBoxNutzungsart.SelectedItem;
    string text = selectedItem.Key;
    double zahl = selectedItem.Value;
}

Edit

Another thought is that if you just need the Value, then you could access it from Zordnung.dieListe by getting the Values as a list and accessing the item at the same index as comboBoxNutzungsart.SelectedIndex:

double zahl2 = Zordnung.dieListe.Values.ToList()[comboBoxNutzungsart.SelectedIndex];


问:
20 bytes are reserved on the stack for no apparent reason when C code is compiled into machine code
I'm following section 5.1.3 at OS development by Nick Blundell. I'm investigating how the following C code is compiled into machine code:

```<code>void caller_fun(){
        callee_fun(0xdede);
}

int callee_fun(int arg){
        return arg;
}
</code>```

My final dis-assembled machine code by ndisasm is this:

```<code>00000000  55                push ebp
00000001  89E5              mov ebp,esp
00000003  83EC08            sub esp,byte +0x8
00000006  83EC0C            sub esp,byte +0xc
00000009  68DEDE0000        push dword 0xdede
0000000E  E806000000        call dword 0x19
00000013  83C410            add esp,byte +0x10
00000016  90                nop
00000017  C9                leave
00000018  C3                ret
00000019  55                push ebp
0000001A  89E5              mov ebp,esp
0000001C  8B4508            mov eax,[ebp+0x8]
0000001F  5D                pop ebp
00000020  C3                ret
</code>```

Studying on how the stack pointer and base pointer work, I made the following diagram which shows stack situation when the opcode at offset 0x1C is being run by the processor:

```
                 Stack situation when processor is
             running `mov eax,[ebp+0x8]` at offset 0x1C

    +---------------------------------+
    |           4 bytes for           |
    |    `push ebp` at offset 0x00    |
    +---------------------------------+
    |        20 (8+12) bytes for      |
    |        `sub esp,byte +0x8`      |
    |    and `sub esp,byte +0xc`      |
    |    at offsets 0x03 and 0x06     |
    +---------------------------------+
    | 4 bytes for `push dword 0xdede` |
    |         at offset 0x09          |
    +---------------------------------+
    | 4 bytes for instruction pointer |
    |      by `call dword 0x19`       |
    |        at offset 0x0E           |
    +---------------------------------+
    |     4 bytes for `push ebp`      |
    |        at offset 0x19           |
    +---------------------------------+ --> ebp & esp are both here by
                                               `mov ebp,esp`
                                              at offset 0x1A
```

Now, I have questions which I couldn't figure out by researching and studying:

Is my diagram of stack situation correct?

Why are 20 bytes pushed into the stack by sub esp,byte +0x8 and sub esp,byte +0xc at offsets 0x03 and 0x06?

Even if 20 bytes of stack memory is needed, why is it not assigned by a single instruction like sub esp,byte +0x14, i.e. 0x14=0x8+0xc

I'm compiling the C code with this make-file:

```<code>all: call_fun.o call_fun.bin call_fun.dis

call_fun.o: call_fun.c
    gcc -ffreestanding -c call_fun.c -o call_fun.o

call_fun.bin: call_fun.o
    ld -o call_fun.bin -Ttext 0x0 --oformat binary call_fun.o

call_fun.dis: call_fun.bin
    ndisasm -b 32 call_fun.bin > call_fun.dis
</code>```

答:
Without the optimizations, stack is going to be used to preserve and restore base pointers. In x86_64 calling conventions (https://en.wikipedia.org/wiki/X86_calling_conventions) stack must be aligned by 16 byte boundaries when calling functions, so this is most likely what happens in your case. At least, this is what happens in my case, when I compile your code on my system. Here is the ASM for this:

```<code>callee_fun(int): # @callee_fun(int)
  pushq %rbp
  movq %rsp, %rbp
  movl %edi, -4(%rbp)
  movl -4(%rbp), %eax
  popq %rbp
  retq
caller_fun(): # @caller_fun()
  pushq %rbp
  movq %rsp, %rbp
  subq $16, %rsp
  movl $57054, %edi # imm = 0xDEDE
  callq callee_fun(int)
  movl %eax, -4(%rbp) # 4-byte Spill
  addq $16, %rsp
  popq %rbp
  retq
</code>```

It is worth noting, that when optimizations are turned on, there is no stack usage or modifications at all:

```<code>callee_fun(int): # @callee_fun(int)
  movl %edi, %eax
  retq
caller_fun(): # @caller_fun()
  retq
</code>```

Last, but not least, when playing with ASM listing, do not disassemble object file or executable file. Instead, direct your compiler to generate assembly listing. This will give you much more context.

If you are using gcc, a good command to do this would be

```<code>gcc -fverbose-asm -S -O
</code>```

Body:
I'm following section 5.1.3 at OS development by Nick Blundell. I'm investigating how the following C code is compiled into machine code:

void caller_fun(){
        callee_fun(0xdede);
}

int callee_fun(int arg){
        return arg;
}

My final dis-assembled machine code by ndisasm is this:

00000000  55                push ebp
00000001  89E5              mov ebp,esp
00000003  83EC08            sub esp,byte +0x8
00000006  83EC0C            sub esp,byte +0xc
00000009  68DEDE0000        push dword 0xdede
0000000E  E806000000        call dword 0x19
00000013  83C410            add esp,byte +0x10
00000016  90                nop
00000017  C9                leave
00000018  C3                ret
00000019  55                push ebp
0000001A  89E5              mov ebp,esp
0000001C  8B4508            mov eax,[ebp+0x8]
0000001F  5D                pop ebp
00000020  C3                ret

Studying on how the stack pointer and base pointer work, I made the following diagram which shows stack situation when the opcode at offset 0x1C is being run by the processor:

                 Stack situation when processor is
             running `mov eax,[ebp+0x8]` at offset 0x1C

    +---------------------------------+
    |           4 bytes for           |
    |    `push ebp` at offset 0x00    |
    +---------------------------------+
    |        20 (8+12) bytes for      |
    |        `sub esp,byte +0x8`      |
    |    and `sub esp,byte +0xc`      |
    |    at offsets 0x03 and 0x06     |
    +---------------------------------+
    | 4 bytes for `push dword 0xdede` |
    |         at offset 0x09          |
    +---------------------------------+
    | 4 bytes for instruction pointer |
    |      by `call dword 0x19`       |
    |        at offset 0x0E           |
    +---------------------------------+
    |     4 bytes for `push ebp`      |
    |        at offset 0x19           |
    +---------------------------------+ --> ebp & esp are both here by
                                               `mov ebp,esp`
                                              at offset 0x1A

Now, I have questions which I couldn't figure out by researching and studying:

Is my diagram of stack situation correct?

Why are 20 bytes pushed into the stack by sub esp,byte +0x8 and sub esp,byte +0xc at offsets 0x03 and 0x06?

Even if 20 bytes of stack memory is needed, why is it not assigned by a single instruction like sub esp,byte +0x14, i.e. 0x14=0x8+0xc

I'm compiling the C code with this make-file:

all: call_fun.o call_fun.bin call_fun.dis

call_fun.o: call_fun.c
    gcc -ffreestanding -c call_fun.c -o call_fun.o

call_fun.bin: call_fun.o
    ld -o call_fun.bin -Ttext 0x0 --oformat binary call_fun.o

call_fun.dis: call_fun.bin
    ndisasm -b 32 call_fun.bin > call_fun.dis

Body:
Without the optimizations, stack is going to be used to preserve and restore base pointers. In x86_64 calling conventions (https://en.wikipedia.org/wiki/X86_calling_conventions) stack must be aligned by 16 byte boundaries when calling functions, so this is most likely what happens in your case. At least, this is what happens in my case, when I compile your code on my system. Here is the ASM for this:

callee_fun(int): # @callee_fun(int)
  pushq %rbp
  movq %rsp, %rbp
  movl %edi, -4(%rbp)
  movl -4(%rbp), %eax
  popq %rbp
  retq
caller_fun(): # @caller_fun()
  pushq %rbp
  movq %rsp, %rbp
  subq $16, %rsp
  movl $57054, %edi # imm = 0xDEDE
  callq callee_fun(int)
  movl %eax, -4(%rbp) # 4-byte Spill
  addq $16, %rsp
  popq %rbp
  retq

It is worth noting, that when optimizations are turned on, there is no stack usage or modifications at all:

callee_fun(int): # @callee_fun(int)
  movl %edi, %eax
  retq
caller_fun(): # @caller_fun()
  retq

Last, but not least, when playing with ASM listing, do not disassemble object file or executable file. Instead, direct your compiler to generate assembly listing. This will give you much more context.

If you are using gcc, a good command to do this would be

gcc -fverbose-asm -S -O


问:
Automate SAS program for different sites using %include
The problem I have is, I use the same program for reports on multiple sites. I have to run the code for each of them individually. I'm looking to automate my process to call the code and run for all sites in a go. This is the code I tried using but it is not working.

```<code>data _null_;
array sites {2} _temporary_ (SiteA SiteB);

do k = 1 to dim(sites);
    %let site = sites(k);

    %include '...path\SitesWait.sas';

end; run;
</code>```

The code in SiteWait works perfectly on its own. I defined a macro variable called site, which sets the site for the code to run.

The error I keep getting is 'ERROR 117-185: There was 1 unclosed DO block.'

Thanks

答:
If the sites don't change often, and if there are not too many of them, this may be the simplest approach:

```<code>%let site=siteA;
%include '...path\SitesWait.sas';

%let site=siteB;
%include '...path\SitesWait.sas';

%let site=siteC;
%include '...path\SitesWait.sas';
</code>```

Be careful though.  You may want to include code at the top of SitesWait.sas that 'resets' you SAS session.  ie. clears any macro values you plan on using, deletes any datasets in your work folder etc.  Otherwise the second call to SitesWait.sas may be affected by the prior run.

Body:
The problem I have is, I use the same program for reports on multiple sites. I have to run the code for each of them individually. I'm looking to automate my process to call the code and run for all sites in a go. This is the code I tried using but it is not working.

data _null_;
array sites {2} _temporary_ (SiteA SiteB);

do k = 1 to dim(sites);
    %let site = sites(k);

    %include '...path\SitesWait.sas';

end; run;

The code in SiteWait works perfectly on its own. I defined a macro variable called site, which sets the site for the code to run.

The error I keep getting is 'ERROR 117-185: There was 1 unclosed DO block.'

Thanks

Body:
If the sites don't change often, and if there are not too many of them, this may be the simplest approach:

%let site=siteA;
%include '...path\SitesWait.sas';

%let site=siteB;
%include '...path\SitesWait.sas';

%let site=siteC;
%include '...path\SitesWait.sas';

Be careful though.  You may want to include code at the top of SitesWait.sas that 'resets' you SAS session.  ie. clears any macro values you plan on using, deletes any datasets in your work folder etc.  Otherwise the second call to SitesWait.sas may be affected by the prior run.


问:
VueJS + AT UIKIT: Failed to compile
I scaffolded a project using vue init webpack-simple. I am hoping to use the AT-UIKIT component library but I was met with the following compile error from webpack:

```<code>Failed to compile.

./node_modules/at-ui-style/css/fonts/feather.ttf?t=1501829003743
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
 @ ./node_modules/css-loader!./node_modules/at-ui-style/css/at.css 6:71718-71764
 @ ./node_modules/at-ui-style/css/at.css
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js
</code>```

Here is my main.js:

```<code>import Vue from 'vue'
import App from './App.vue'

import AtComponents from 'at-ui'
import 'at-ui-style'    // Import CSS

new Vue({
  el: '#app',
  render: h => h(App)
})
</code>```

I am new to VueJS and webpack. Am I to install a certain loader to fix this? Thank you for your assistance.

答:
you forget install plugin.

add code in you main.js:

```<code>Vue.use(AtComponents)
</code>```

Title: VueJS + AT UIKIT: Failed to compile

Body:
I scaffolded a project using vue init webpack-simple. I am hoping to use the AT-UIKIT component library but I was met with the following compile error from webpack:

Failed to compile.

./node_modules/at-ui-style/css/fonts/feather.ttf?t=1501829003743
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
 @ ./node_modules/css-loader!./node_modules/at-ui-style/css/at.css 6:71718-71764
 @ ./node_modules/at-ui-style/css/at.css
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js

Here is my main.js:

import Vue from 'vue'
import App from './App.vue'

import AtComponents from 'at-ui'
import 'at-ui-style'    // Import CSS

new Vue({
  el: '#app',
  render: h => h(App)
})

I am new to VueJS and webpack. Am I to install a certain loader to fix this? Thank you for your assistance.

Body:
you forget install plugin.

add code in you main.js:

Vue.use(AtComponents)