问:
current-group() except for one element in xslt
The below is my input xml. I'm trying group by using current-group() function but it is not meeting my requirement, below I have provided the details.

```<code>        <UsrTimeCardEntry>
            <Code>1<Code>
            <Name>TC1</Name>
            <Person>
                <Code>074</Code>
            </Person>
        </UsrTimeCardEntry>
        <UsrTimeCardEntry>
            <Code>2<Code>
            <Name>TC2</Name>
            <Person>
                <Code>074</Code>
            </Person>
        </UsrTimeCardEntry>
</code>```

I want to group it by Person/Code so that it looks like this

```<code>   <Person Code="074">
       <UsrTimeCardEntry>
              <Code>1</Code>
              <Name>TC1</Name>
       </UsrTimeCardEntry>
       <UsrTimeCardEntry>
              <Code>2</Code>
              <Name>TC2</Name>
       </UsrTimeCardEntry>
</Person>
</code>```

For which I'm using the below xslt, but it is again copying the Person which I don't want, what it that I'm missing here, I tried using current-group() except  and not[child::Person] but that too did not work.

```<code><xsl:template match="businessobjects">
    <xsl:for-each-group select="UsrTimeCardEntry" group-by="Person/Code">
        <Person Code="{current-grouping-key()}">
            <xsl:copy-of select="current-group()"></xsl:copy-of>
        </Person>
    </xsl:for-each-group>
</xsl:template>
</code>```

答:
Instead of using xsl:copy-of here, use xsl:apply-templates, then you can add a template to ignore the Person node

```<code><xsl:template match="Person" />
</code>```

This assumes you are also using the identity template to copy all other nodes normally.

```<code><xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
</code>```

Try this XSLT

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes" />

    <xsl:strip-space elements="*" />

    <xsl:template match="businessobjects">
        <xsl:for-each-group select="UsrTimeCardEntry" group-by="Person/Code">
            <Person Code="{current-grouping-key()}">
                <xsl:apply-templates select="current-group()" />
            </Person>
        </xsl:for-each-group>
    </xsl:template>

    <xsl:template match="Person" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
The below is my input xml. I'm trying group by using current-group() function but it is not meeting my requirement, below I have provided the details.

        <UsrTimeCardEntry>
            1
            <Name>TC1</Name>
            <Person>
                074
            </Person>
        </UsrTimeCardEntry>
        <UsrTimeCardEntry>
            2
            <Name>TC2</Name>
            <Person>
                074
            </Person>
        </UsrTimeCardEntry>

I want to group it by Person/Code so that it looks like this

   <Person Code="074">
       <UsrTimeCardEntry>
              1
              <Name>TC1</Name>
       </UsrTimeCardEntry>
       <UsrTimeCardEntry>
              2
              <Name>TC2</Name>
       </UsrTimeCardEntry>
</Person>

For which I'm using the below xslt, but it is again copying the Person which I don't want, what it that I'm missing here, I tried using current-group() except  and not[child::Person] but that too did not work.

<xsl:template match="businessobjects">
    <xsl:for-each-group select="UsrTimeCardEntry" group-by="Person/Code">
        <Person Code="{current-grouping-key()}">
            <xsl:copy-of select="current-group()"></xsl:copy-of>
        </Person>
    </xsl:for-each-group>
</xsl:template>

Body:
Instead of using xsl:copy-of here, use xsl:apply-templates, then you can add a template to ignore the Person node

<xsl:template match="Person" />

This assumes you are also using the identity template to copy all other nodes normally.

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

Try this XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes" />

    <xsl:strip-space elements="*" />

    <xsl:template match="businessobjects">
        <xsl:for-each-group select="UsrTimeCardEntry" group-by="Person/Code">
            <Person Code="{current-grouping-key()}">
                <xsl:apply-templates select="current-group()" />
            </Person>
        </xsl:for-each-group>
    </xsl:template>

    <xsl:template match="Person" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>


来源: stackexchange

问:
Ruby on Rails using existing database ID not working
I have a Ruby on Rails app that uses an existing database. The existing database has a field of id which is an auto increment primary key in the DB but Ruby on Rails does not seem to use this as I get an error of First argument in form cannot contain nil or be empty

My edit.html.erb is:

```<code><%= form_for (@activevulnerabilities) do |f| %>
  <div class="row">
    <div class="col-xs-12">
      <div class="box">

        <div class="box-header">
          <h3 class="box-title">Edit Vulnerability Type</h3>
        </div>

        <div class="box-body">
          <%= render partial: 'admin/active_vulnerabilities/form', locals: { f: f } %>
        </div>

        <div class="box-footer">
          <%= link_to 'Cancel', active_vulnerabilities_path, class: 'btn btn-danger' %>
          <%= f.submit 'Submit', class: "btn btn-success" %>
        </div>

      </div>
    </div>
  </div>
<% end %>
</code>```

My controller is:

```<code>class Admin::ActiveVulnerabilitiesController < ApplicationController
  layout :layout_by_resource
  def index
    @activevulnerabilities = ActiveVulnerability.all
  end

  def edit
    @activevulnerability = ActiveVulnerability.find(params[:id])
  end

  private def layout_by_resource
    if devise_controller?
      'layouts/devise'
    else
      'admin/layouts/admin'
    end
  end
  private def set_active_vulnerability
    @activevulnerability = ActiveVulnerability.find(params[:id])
  end
end
</code>```

答: In your edit action you are setting @activevulnerability variable and in view you are trying to access @activevulnerabilities variable which is nil. Fix variable naming and it should be okay.

ContentLicense: CC BY-SA 3.0

Body:
I have a Ruby on Rails app that uses an existing database. The existing database has a field of id which is an auto increment primary key in the DB but Ruby on Rails does not seem to use this as I get an error of First argument in form cannot contain nil or be empty

My edit.html.erb is:

<%= form_for (@activevulnerabilities) do |f| %>

Edit Vulnerability Type

          <%= render partial: 'admin/active_vulnerabilities/form', locals: { f: f } %>

          <%= link_to 'Cancel', active_vulnerabilities_path, class: 'btn btn-danger' %>
          <%= f.submit 'Submit', class: "btn btn-success" %>

<% end %>

My controller is:

class Admin::ActiveVulnerabilitiesController < ApplicationController
  layout :layout_by_resource
  def index
    @activevulnerabilities = ActiveVulnerability.all
  end

  def edit
    @activevulnerability = ActiveVulnerability.find(params[:id])
  end

  private def layout_by_resource
    if devise_controller?
      'layouts/devise'
    else
      'admin/layouts/admin'
    end
  end
  private def set_active_vulnerability
    @activevulnerability = ActiveVulnerability.find(params[:id])
  end
end


问:
Facebook Messenger Platform API Live Person
Is there a way to delegate the current conversation that a Messenger Platform bot is having to another person through the API? I could not find anything in the documentation.

If no, what's the best way to handle the use case where a person asks the bot to talk to a live person?

答:
If you'd like to send message from one user to another, both user needs to be signed in to your bot, then User A needs to specify to which user he'd like to send a message, after that bot can send message to User B, because you know User A and User B Messenger IDs.

Sending messages to not signed in users is not possible.


问:
When to use re.compile
Bear with me, I can't include my 1,000+ line program, and there are a couple of questions in the description.

So I have a couple types of patterns I am searching for:

```<code>#literally just a regular word
re.search("Word", arg)

#Varying complex pattern
re.search("[0-9]{2,6}-[0-9]{2}-[0-9]{1}", arg)

#Words with varying cases and the possibility of ending special characters
re.search("Supplier [Aa]ddress:?|Supplier [Ii]dentification:?|Supplier [Nn]ame:?", arg)

#I also use re.findall for the above patterns as well
re.findall("uses patterns above", arg
</code>```

I have about 75 of these in total, and some need to be moved to deeply nested functions

When and where should I compile the patterns?

Right now I am trying to improve my program by compiling everything in main, then pass the correct list of compiled RegexObjects to the function that uses it. Would this increase my performance?

Would doing something like the following increase the speed of my program?

```<code>re.compile("pattern").search(arg)
</code>```

Does the compiled patterns stay in memory so if a function is called multiple times with this in it would it skip the compiling part? So I wouldn't have to move data from function to function.

Is it even worth compiling all of the patterns if I move the data so much?

Is there a better way to match regular words without regex?

Short example of my code:

```<code>import re

def foo(arg, allWords):
   #Does some things with arg, then puts the result into a variable,
   # this function does not use allWords

   data = arg #This is the manipulated version of arg

   return(bar(data, allWords))

def bar(data, allWords):
   if allWords[0].search(data) != None:
      temp = data.split("word1", 1)[1]
      return(temp)

   elif allWords[1].search(data) != None:
      temp = data.split("word2", 1)[1]
      return(temp)

def main():

   allWords = [re.compile(m) for m in ["word1", "word2", "word3"]]

   arg = "This is a very long string from a text document input, the provided patterns might not be word1 in this string but I need to check for them, and if they are there do some cool things word3"

   #This loop runs a couple million times
   # because it loops through a couple million text documents
   while True:
      data = foo(arg, allWords)
</code>```

答:
Let's say that word1, word2 ... are regexes:

let's rewrite those parts:

```<code>allWords = [re.compile(m) for m in ["word1", "word2", "word3"]]
</code>```

I would create one single regex for all patterns:

```<code>allWords = re.compile("|".join(["word1", "word2", "word3"])
</code>```

To support regexes with | in them, you would have to parenthesize the expressions:

```<code>allWords = re.compile("|".join("({})".format(x) for x in ["word1", "word2", "word3"])
</code>```

(that also works with standard words of course, and it's still worth using regexes because of the | part)

now this is a disguised loop with each term hardcoded:

```<code>def bar(data, allWords):
   if allWords[0].search(data):
      temp = data.split("word1", 1)[1]  # that works only on non-regexes BTW
      return(temp)

   elif allWords[1].search(data):
      temp = data.split("word2", 1)[1]
      return(temp)
</code>```

can be rewritten simply as

```<code>def bar(data, allWords):
   return allWords.split(data,maxsplit=1)[1]
</code>```

in terms of performance:

regular expression is compiled at start, so it's as fast as it can be

there's no loop or pasted expressions, the "or" part is done by the regex engine, which is most of the time some compiled code: can't beat that in pure python.

the match & the split are done in one operation

The last hiccup is that internally the regex engine searches for all expressions in a loop, which makes that a O(n) algorithm. To make it faster, you would have to predict which pattern is the most frequent, and put it first (my hypothesis is that regexes are "disjoint", which means that a text cannot be matched by several ones, else the longest would have to come before the shorter one)

ContentLicense: CC BY-SA 4.0

Title: When to use re.compile

Body:
Bear with me, I can't include my 1,000+ line program, and there are a couple of questions in the description.

So I have a couple types of patterns I am searching for:

#literally just a regular word
re.search("Word", arg)

#Varying complex pattern
re.search("[0-9]{2,6}-[0-9]{2}-[0-9]{1}", arg)

#Words with varying cases and the possibility of ending special characters
re.search("Supplier [Aa]ddress:?|Supplier [Ii]dentification:?|Supplier [Nn]ame:?", arg)

#I also use re.findall for the above patterns as well
re.findall("uses patterns above", arg

I have about 75 of these in total, and some need to be moved to deeply nested functions

When and where should I compile the patterns?

Right now I am trying to improve my program by compiling everything in main, then pass the correct list of compiled RegexObjects to the function that uses it. Would this increase my performance?

Would doing something like the following increase the speed of my program?

re.compile("pattern").search(arg)

Does the compiled patterns stay in memory so if a function is called multiple times with this in it would it skip the compiling part? So I wouldn't have to move data from function to function.

Is it even worth compiling all of the patterns if I move the data so much?

Is there a better way to match regular words without regex?

Short example of my code:

import re

def foo(arg, allWords):
   #Does some things with arg, then puts the result into a variable,
   # this function does not use allWords

   data = arg #This is the manipulated version of arg

   return(bar(data, allWords))

def bar(data, allWords):
   if allWords[0].search(data) != None:
      temp = data.split("word1", 1)[1]
      return(temp)

   elif allWords[1].search(data) != None:
      temp = data.split("word2", 1)[1]
      return(temp)

def main():

   allWords = [re.compile(m) for m in ["word1", "word2", "word3"]]

   arg = "This is a very long string from a text document input, the provided patterns might not be word1 in this string but I need to check for them, and if they are there do some cool things word3"

   #This loop runs a couple million times
   # because it loops through a couple million text documents
   while True:
      data = foo(arg, allWords)

Body:
Let's say that word1, word2 ... are regexes:

let's rewrite those parts:

allWords = [re.compile(m) for m in ["word1", "word2", "word3"]]

I would create one single regex for all patterns:

allWords = re.compile("|".join(["word1", "word2", "word3"])

To support regexes with | in them, you would have to parenthesize the expressions:

allWords = re.compile("|".join("({})".format(x) for x in ["word1", "word2", "word3"])

(that also works with standard words of course, and it's still worth using regexes because of the | part)

now this is a disguised loop with each term hardcoded:

def bar(data, allWords):
   if allWords[0].search(data):
      temp = data.split("word1", 1)[1]  # that works only on non-regexes BTW
      return(temp)

   elif allWords[1].search(data):
      temp = data.split("word2", 1)[1]
      return(temp)

can be rewritten simply as

def bar(data, allWords):
   return allWords.split(data,maxsplit=1)[1]

in terms of performance:

regular expression is compiled at start, so it's as fast as it can be

there's no loop or pasted expressions, the "or" part is done by the regex engine, which is most of the time some compiled code: can't beat that in pure python.

the match & the split are done in one operation

The last hiccup is that internally the regex engine searches for all expressions in a loop, which makes that a O(n) algorithm. To make it faster, you would have to predict which pattern is the most frequent, and put it first (my hypothesis is that regexes are "disjoint", which means that a text cannot be matched by several ones, else the longest would have to come before the shorter one)


问:
How to handle a day light saving issue properly in ASP.net?
I have gone through many answers and articles but I havent got the better solution.
I have to set a reminder for daily, weekly or monthly from different regions.
Even if I convert the time into UTC also there will be issues when the region is prone to Daylight saving.</p>

答:
I have solved this problem by using this code.
We will get the TimeZoneInfo from TimezoneId

```<code>var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(TimezoneId);
</code>```

convert the DateTime into a timestamp

```<code>   private DateTime ComputeNextUtcTimeToRun(long dateTimeStamp, TimeZoneInfo timeZoneInfo)
        {
            try
            {
                // Get the current time in the target time zone
                DateTime now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZoneInfo);

                // Compute the next local time
                DateTime scheduledLocalTime = (new DateTime(1970, 1, 1, 0, 0, 0)).AddMilliseconds(dateTimeStamp).ToLocalTime();

                if (scheduledLocalTime < now)
                {
                    scheduledLocalTime = scheduledLocalTime.AddDays(1);
                }
                // If it's invalid, advance.  The clocks shifted forward!
                if (timeZoneInfo.IsInvalidTime(scheduledLocalTime))
                {
                    return TimeZoneInfo.ConvertTimeToUtc(scheduledLocalTime.AddHours(1), timeZoneInfo);
                }
                // If it's ambiguous, pick the first instance
                if (timeZoneInfo.IsAmbiguousTime(scheduledLocalTime))
                {
                    TimeSpan offset = timeZoneInfo.GetAmbiguousTimeOffsets(scheduledLocalTime).Max();
                    DateTimeOffset dto = new DateTimeOffset(scheduledLocalTime, offset);
                    return dto.UtcDateTime;
                }
                return TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(scheduledLocalTime, DateTimeKind.Unspecified), timeZoneInfo);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
</code>```

Please refer this link for more information

please correct me if it can be made better.

Body:
I have solved this problem by using this code.
We will get the TimeZoneInfo from TimezoneId

var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(TimezoneId);

convert the DateTime into a timestamp

   private DateTime ComputeNextUtcTimeToRun(long dateTimeStamp, TimeZoneInfo timeZoneInfo)
        {
            try
            {
                // Get the current time in the target time zone
                DateTime now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZoneInfo);

                // Compute the next local time
                DateTime scheduledLocalTime = (new DateTime(1970, 1, 1, 0, 0, 0)).AddMilliseconds(dateTimeStamp).ToLocalTime();

                if (scheduledLocalTime < now)
                {
                    scheduledLocalTime = scheduledLocalTime.AddDays(1);
                }
                // If it's invalid, advance.  The clocks shifted forward!
                if (timeZoneInfo.IsInvalidTime(scheduledLocalTime))
                {
                    return TimeZoneInfo.ConvertTimeToUtc(scheduledLocalTime.AddHours(1), timeZoneInfo);
                }
                // If it's ambiguous, pick the first instance
                if (timeZoneInfo.IsAmbiguousTime(scheduledLocalTime))
                {
                    TimeSpan offset = timeZoneInfo.GetAmbiguousTimeOffsets(scheduledLocalTime).Max();
                    DateTimeOffset dto = new DateTimeOffset(scheduledLocalTime, offset);
                    return dto.UtcDateTime;
                }
                return TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(scheduledLocalTime, DateTimeKind.Unspecified), timeZoneInfo);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Please refer this link for more information

please correct me if it can be made better.


问:
Adobe Analytics | Merge data from multiple report suites
We are capturing information for consumer sites in multiple different report suites.
Is it possible to merge all these data to a parent report suite without adding that parent report suite's account id in s_account variable?

For example

Site 1 uses report-suite1

```<code>s_account  = "report-suite1";
</code>```

Site 2 uses report-suite2

```<code>s_account = "report-suite2"
</code>```

Instead of using

```<code>s_account = "report-suite1,report-suite2"
</code>```

is it possible to merge the data to a 3rd virtual account from the Reports console itself?

答:
The only way you can route data to a separate fully fledged report suite is either via javascript (e.g. setting s_account as you have shown in your post), or to ask Adobe To create a VISTA rule.

You didn't state your reasons for not wanting to throw a "global" rsid into your js code. Is it because you don't have the technical resources/ability to do it? If so, and if you want a full 3rd rsid for all the data to go to, then you can ask Adobe to create a VISTA rule. It should be fairly easy for them to setup, but they will charge you for it. And I think they will create one for each report suite. I don't generally recommend going this route unless you really have to, though. Mostly because the cost, but also because you don't have personal visibility into it.

Alternatively, if you do have the tech resources to update the js code, but the cost of throwing another rsid into the mix is an issue (from extra server hits), then you may want to consider replacing all of your report suites with a single global report suite, e.g.

s_account='report-global';

Then, create a Virtual Report Suite for each site. You can go to Components > Virtual Report Suites to set them up. The TL;DR is you create them by pointing at your report-global rsid as the source and then creating a segment based off something unique to the site (e.g. the domain, or maybe some eVar with a site-specific value).

The major downside to going the virtual report suite route is historical data from your previous report suites will not be available in the same place as this new global report suite and its virtual report suites. But it's a "one time migration" thing, and the historical data won't be lost; you'll just have some extra work on your end referencing it in the old rsids, esp if you want to compare historical to current in the new (virtual) risds.

The 2nd major thing to consider is unique limits. Not sure how much traffic / unique values vars get on your sites, but there is a monthly unique value limit you may have to consider with all of the sites going to the same report suite.  Beyond looking at tricks to make values less unique on a case by case basis (e.g. removing query param string from URLs), there isn't a good way to solve for this except to stick with separate rsids.  Well.. Adobe will increase unique limit on certain vars if you ask them, but it will cost you..

Another alternative to consider is a Rollup report suite. If you go to Admin > Report Suites, where your current report suites are listed.  To the left you should see Rollups and an Add link next to it. This will create a Rollup report suite made up of data from one or more report suites.

Note though that a Rollup report suite is not the same as full fledged report suite. Please refer to the link above for full details/limitations, but the main benefit is it won't cost you anything except the couple of minutes to set it up in the interface. But the limitations of it.. the main points of note are you only get aggregated data, data is not deduped between the rsids, and many reports are limited or not available. In practice, I rarely ever see anybody actually go this route because it's too limited. But hey, maybe it's good enough for you.

Body:
We are capturing information for consumer sites in multiple different report suites.
Is it possible to merge all these data to a parent report suite without adding that parent report suite's account id in s_account variable?

For example

Site 1 uses report-suite1

s_account  = "report-suite1";

Site 2 uses report-suite2

s_account = "report-suite2"

Instead of using

s_account = "report-suite1,report-suite2"

is it possible to merge the data to a 3rd virtual account from the Reports console itself?


问:
Run a build after creating it with DSL Job Plugin
I have successfully programatically created a job with DSL Job Plugin

I trigger the "job creator" job from gitlab, hitting a post with:

https://37.35.xxx.xxx/jenkins/project/job-creator

So, it create the job, but it is not triggering it... Any idea how to do it ?

答:
After a while, I found out you can use upstream trigger:

```<code>pipelineJob("myJob") {
  parameters {
    stringParam('param1', 'value1') // this will define params for the project build
}

triggers {
    gitlabPush {
        buildOnMergeRequestEvents()
        buildOnPushEvents()
        commentTrigger('Jenkins please retry a build')
        upstream("${JOB_NAME}", 'SUCCESS') // Trigger job after this job ends

    }
}
</code>```

Body:
After a while, I found out you can use upstream trigger:

pipelineJob("myJob") {
  parameters {
    stringParam('param1', 'value1') // this will define params for the project build
}

triggers {
    gitlabPush {
        buildOnMergeRequestEvents()
        buildOnPushEvents()
        commentTrigger('Jenkins please retry a build')
        upstream("${JOB_NAME}", 'SUCCESS') // Trigger job after this job ends

    }
}


问:
Performance point not working correctly in a SharePoint site
After running a script from the security team that changes files permissions and also isntalls some hotfixes, performance point stopped working on my SHarePoint site. The Dashboard Viewer web part does not show the background of a graph we use, and when adding a new web part of this kind into the page the image icon of it does not appear in the web part list.

Any idea of what folder I should give access to and what user? I believe it has to do with file permissions.

答: The error happened because UrlScan was installed on the server and Microsoft.PerformancePoint.Scorecards.WebParts directory contains dots in its name. I modified UrlScan config file to let it allow dots in the URL and it started working again.</p>

ContentLicense: CC BY-SA 2.5


问:
UnexpectedValueException Could not parse version constraint when trying to instal laravelcollective
I am new to laravel and I am trying to install laravelcollective. I am just following to documentation here and I am using this from my project directory:

composer require "laravelcollective/html":"^5.4.0"

Unfortunately, immediately after I press ented I get the following error :

[UnexpectedValueException]
    Could not parse version constraint :5.4.0: Invalid version string ":5.4.0"

I just don't know how to troubleshoot this. I didn't find much on google and this combined with my lack of experience with laravel leaves me stuck.

Can someone help?

答:
You can add it manually in composer.json then use composer update.

Just add "laravelcollective/html": "5.4.*", under the row with "laravel/framework":"5.4.*",

Like this :

```<code>"require": {
        "php": ">=7.0.0",
        "fideloper/proxy": "~3.3",
        "laravel/framework": "5.4.*",
        "laravelcollective/html": "5.4.*", <-- Add this row
        "laravel/tinker": "~1.0"
    },
</code>```

Body:
You can add it manually in composer.json then use composer update.

Just add "laravelcollective/html": "5.4.*", under the row with "laravel/framework":"5.4.*",

Like this :

"require": {
        "php": ">=7.0.0",
        "fideloper/proxy": "~3.3",
        "laravel/framework": "5.4.*",
        "laravelcollective/html": "5.4.*", <-- Add this row
        "laravel/tinker": "~1.0"
    },


问:
WildFly console served with nginx
I stuck to configure a simple reverse proxy on AWS.
Since we have one host (reverse proxy nginx) serving the public access I decided to follow the rules and created the following configuration.

```<code>server {
    listen      9990;
    server_name project-wildfly.domain.me;

    access_log  /var/log/nginx/wildfly.access.log;
    error_log   /var/log/nginx/wildfly.error.log;

    proxy_buffers 16 64k;
    proxy_buffer_size 128k;

    root   /var/www/;
    index  index.html index.htm;

    location /console {
        proxy_set_header Host $server_addr:$server_port;
        proxy_set_header X-Forwarded-Proto $scheme;

        add_header Cache-Control "no-cache, no-store";
        proxy_pass http://10.124.1.120:9990/console;
    }

    location /management {
        proxy_set_header Host $server_addr:$server_port;
        proxy_set_header X-Forwarded-Proto $scheme;

        add_header Cache-Control "no-cache, no-store";
        proxy_pass http://10.124.1.120:9990/management;
    }
}
</code>```

This will serve the admin console and I'm able to log in with the user. Then this message appears:

Access Denied

Insufficient privileges to access this interface.

Nothing within the error log. Thanks for any hint!

答:
Maybe you need turn on management module.

Try this:sh standalone.sh -b 0.0.0.0 -bmanagement 0.0.0.0 &

Title: WildFly console served with nginx

Body:
I stuck to configure a simple reverse proxy on AWS.
Since we have one host (reverse proxy nginx) serving the public access I decided to follow the rules and created the following configuration.

server {
    listen      9990;
    server_name project-wildfly.domain.me;

    access_log  /var/log/nginx/wildfly.access.log;
    error_log   /var/log/nginx/wildfly.error.log;

    proxy_buffers 16 64k;
    proxy_buffer_size 128k;

    root   /var/www/;
    index  index.html index.htm;

    location /console {
        proxy_set_header Host $server_addr:$server_port;
        proxy_set_header X-Forwarded-Proto $scheme;

        add_header Cache-Control "no-cache, no-store";
        proxy_pass http://10.124.1.120:9990/console;
    }

    location /management {
        proxy_set_header Host $server_addr:$server_port;
        proxy_set_header X-Forwarded-Proto $scheme;

        add_header Cache-Control "no-cache, no-store";
        proxy_pass http://10.124.1.120:9990/management;
    }
}

This will serve the admin console and I'm able to log in with the user. Then this message appears:

Access Denied

Insufficient privileges to access this interface.

Nothing within the error log. Thanks for any hint!


问:
How to toggle
 in a nested list?
I'm trying to be able to toggle these sub menus one at a time, I'm getting lost in nests and cant quite figure out how to target the correct list item,

I found that I should be using find() instead of children() as it can go deeper in the nest but still no luck in getting it working.

```<code>    <ul>
      <li>Profile</li>
      <li>Edit</li>
      <li class="drop-nav"> <a href="#"> See your products</a>
        <ul>
          <li class="drop-nav"> <a href="#"> Mens </a>
            <ul>
              <li>  <a href="#"> jumpers </a> </li>
              <li>  <a href="#"> t shirts </a> </li>
            </ul>
          </li>
          <li class="drop-nav"> <a href="#">Womens</a>
            <ul>
              <li> <a href="#"> hoodies </a> </li>
              <li> <a href="#"> leggings </a> </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>

 $(".drop-nav").on("click", function(e){
   e.preventDefault();

   });

 li ul{
 display: none;
  }
</code>```

答:
You could use $(this).find('ul').eq(0) to get the ul, but I would delegate the changing of the display to the stylesheet, but use javascript to add a class where applicable. This will give you many more options for the design of your dropdown later.

$(".drop-nav").on("click", function(e) {
  e.preventDefault()
  // don't allow the event to fire horizontally or vertically up the tree
  e.stopImmediatePropagation()
  // switch the active class that you can use to display the child
  $(this).toggleClass('active')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* don't target ll list items in you page, be more specific */
.drop-nav > ul {
  display: none;
}

.drop-nav.active > ul {
  display: block;
}</code>```

Profile

Edit

  See your products

  Mens

  jumpers

  t shirts

 Womens

  hoodies

  leggings

```

Title: How to toggle <li> in a nested list?

Body:
I'm trying to be able to toggle these sub menus one at a time, I'm getting lost in nests and cant quite figure out how to target the correct list item,

I found that I should be using find() instead of children() as it can go deeper in the nest but still no luck in getting it working.

Profile

Edit

  See your products

  Mens

   jumpers

   t shirts

 Womens

  hoodies

  leggings

 $(".drop-nav").on("click", function(e){
   e.preventDefault();

   });

 li ul{
 display: none;
  }

Body:
You could use $(this).find('ul').eq(0) to get the ul, but I would delegate the changing of the display to the stylesheet, but use javascript to add a class where applicable. This will give you many more options for the design of your dropdown later.

$(".drop-nav").on("click", function(e) {
  e.preventDefault()
  // don't allow the event to fire horizontally or vertically up the tree
  e.stopImmediatePropagation()
  // switch the active class that you can use to display the child
  $(this).toggleClass('active')
})

/* don't target ll list items in you page, be more specific */
.drop-nav > ul {
  display: none;
}

.drop-nav.active > ul {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Profile</li>
  <li>Edit</li>
  <li class="drop-nav"> <a href="#"> See your products</a>
    <ul>
      <li class="drop-nav"> <a href="#"> Mens </a>
        <ul>
          <li> <a href="#"> jumpers </a> </li>
          <li> <a href="#"> t shirts </a> </li>
        </ul>
      </li>
      <li class="drop-nav"> <a href="#">Womens</a>
        <ul>
          <li> <a href="#"> hoodies </a> </li>
          <li> <a href="#"> leggings </a> </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>


答:
I would add more descriptive class names in your markup, and make them easier to target with CSS and jQuery.

To toggle the menus you could do something like the following:

$(".dropdown-trigger1").on("click", function() {
  // Toggle the first menu
  $(".dropdown-one").toggleClass("open");
  // Close the submenus
  $(".dropdown-two").removeClass("open");
});

$(".dropdown-trigger2").on("click", function(e) {
  // Prevent a click on a submenu from closing the menu
  e.stopPropagation();
  // Close any open submenu
  $(".dropdown-two").removeClass("open");
  // Open the submenu that has been clicked
  $(this).find(".dropdown-two").toggleClass("open");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li ul {
  display: none;
}

.dropdown-one.open {
  display: block;
}

.dropdown-two.open {
  display: block;
}</code>```

Profile

Edit

  See your products

  Mens

  jumpers

  t shirts

 Womens

  hoodies

  leggings

```

Title: How to toggle <li> in a nested list?

Body:
I would add more descriptive class names in your markup, and make them easier to target with CSS and jQuery.

To toggle the menus you could do something like the following:

$(".dropdown-trigger1").on("click", function() {
  // Toggle the first menu
  $(".dropdown-one").toggleClass("open");
  // Close the submenus
  $(".dropdown-two").removeClass("open");
});

$(".dropdown-trigger2").on("click", function(e) {
  // Prevent a click on a submenu from closing the menu
  e.stopPropagation();
  // Close any open submenu
  $(".dropdown-two").removeClass("open");
  // Open the submenu that has been clicked
  $(this).find(".dropdown-two").toggleClass("open");
});

li ul {
  display: none;
}

.dropdown-one.open {
  display: block;
}

.dropdown-two.open {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Profile</li>
  <li>Edit</li>
  <li class="dropdown-trigger1"> <a href="#"> See your products</a>
    <ul class="dropdown-one">
      <li class="dropdown-trigger2"> <a href="#"> Mens </a>
        <ul class="dropdown-two">
          <li> <a href="#"> jumpers </a> </li>
          <li> <a href="#"> t shirts </a> </li>
        </ul>
      </li>
      <li class="dropdown-trigger2"> <a href="#">Womens</a>
        <ul class="dropdown-two">
          <li> <a href="#"> hoodies </a> </li>
          <li> <a href="#"> leggings </a> </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>


问:
Deletion - Bulk Action - Laravel
I am trying to do a bulk action delete.(deleting multiple items at once). Now with my code below, the selected items are  deleted but  it  still returns alert('Whoops Something went wrong!!');  Why is that happening?

HTML

```<code>    <button style="margin-bottom: 10px" class="btn delete_all" data-url="{{ url('item/deleteAll') }}">Delete All Selected</button>

 <tbody>
    @foreach($items as $item)
    <tr id="{{$item->id}}" >
    <td><input type="checkbox" class="sub_chk" data-id="{{$item->id}}"></td>
    </tr>
    @endforeach
    </tbody>
</code>```

JS

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-confirmation/1.0.5/bootstrap-confirmation.min.js"></script>

    <script type="text/javascript">
    $(document).ready(function () {

        $('#master').on('click', function(e) {
         if($(this).is(':checked',true))
         {
            $(".sub_chk").prop('checked', true);
         } else {
            $(".sub_chk").prop('checked',false);
         }
        });

        $('.delete_all').on('click', function(e) {

            var allVals = [];
            $(".sub_chk:checked").each(function() {
                allVals.push($(this).attr('data-id'));
            });

            if(allVals.length <=0)
            {
                alert("Please select row.");
            }

            else {

                var check = confirm("Are you sure you want to delete this row?");
                if(check == true){

                    var join_selected_values = allVals.join(",");

                    $.ajax({
                        url: $(this).data('url'),
                        type: 'GET',
                        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                        data: 'ids='+join_selected_values,

                        success: function (data) {
                            if (data['success'])
                            {
                                $("#" + data['tr']).slideUp("slow");
                                alert(data['success']);
                            }
                            else if (data['error'])
                            {
                                alert(data['error']);
                            }
                            else
                            {   //this is where the issue is
                                alert('Whoops Something went wrong!!');
                            }
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });

                  $.each(allVals, function( index, value )
                  {
                      $('table tr').filter("[data-row-id='" + value + "']").remove();
                  });
                }
            }
        });

        $('[data-toggle=confirmation]').confirmation({
            rootSelector: '[data-toggle=confirmation]',
            onConfirm: function (event, element) {
                element.trigger('confirm');
            }
        });

        $(document).on('confirm', function (e) {
            var ele = e.target;
            e.preventDefault();

            $.ajax({
                url: ele.href,
                type: 'GET',
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                success: function (data) {
                    if (data['success'])
                    {
                        $("#" + data['tr']).slideUp("slow");
                        alert(data['success']);
                    }
                    else if (data['error']) {
                        alert(data['error']);
                    }
                    else
                    {
                        alert('Whoops Something went wrong!!');
                    }
                },
                error: function (data) {
                    alert(data.responseText);
                }
            });

            return false;
        });
    });
</script>
</code>```

Route

```<code>Route::get('item/deleteAll','controller@deleteAll');
</code>```

Controller

```<code> public function deleteAll(Request $request)
     {
         $ids = $request->ids;
         DB::table("items")->whereIn('id',explode(",",$ids))->delete();
         return redirect('item/all')->with('status','Items Successfully deleted!');

     }
</code>```

答:
Since it's an ajax call, you should return something like

```<code>return ['success' => 1];
</code>```

From you Controller, not the redirect.

An example:

```<code>    public function deleteAll(Request $request)
{
    $ids = $request->ids;
    DB::table("items")->whereIn('id',explode(",",$ids))->delete();

    if(request()->ajax()) {
        return ['success' => 1];
    }

    return redirect('item/all')->with('status','Items Successfully deleted!');
}
</code>```

Title: Deletion - Bulk Action - Laravel

Body:
I am trying to do a bulk action delete.(deleting multiple items at once). Now with my code below, the selected items are  deleted but  it  still returns alert('Whoops Something went wrong!!');  Why is that happening?

HTML

    <button style="margin-bottom: 10px" class="btn delete_all" data-url="{{ url('item/deleteAll') }}">Delete All Selected</button>

    @foreach($items as $item)

id}}" >
    <input type="checkbox" class="sub_chk" data-id="{{$item->id}}">

    @endforeach

JS

Route

Route::get('item/deleteAll','controller@deleteAll');

Controller

 public function deleteAll(Request $request)
     {
         $ids = $request->ids;
         DB::table("items")->whereIn('id',explode(",",$ids))->delete();
         return redirect('item/all')->with('status','Items Successfully deleted!');

     }

Body:
Since it's an ajax call, you should return something like

return ['success' => 1];

From you Controller, not the redirect.

An example:

    public function deleteAll(Request $request)
{
    $ids = $request->ids;
    DB::table("items")->whereIn('id',explode(",",$ids))->delete();

    if(request()->ajax()) {
        return ['success' => 1];
    }

    return redirect('item/all')->with('status','Items Successfully deleted!');
}


问:
Nested Triangle in Python
My assingment

At each level the complete triangle for the previous level is placed into an extra outer triangle. The user should be asked to input the two characters to be used and the width of the innermost triangle, which must be odd. In addition to the test for negative input the function should test whether the supplied number is odd and display an appropriate message if it is not.

I need to print 3 triangles but every one of them includes other. It needs to get printed with two different character(like *-) and the user have to specify the length of innermost triangle and which has to be an odd number. Example,

Example output for 5 value

Ok, let me explain my way,

Every triangle should be in dictionary.

```<code>tri1 = {1:"*****", 2:"***", 3:"*"}
tri2 = {1:"..........", ...}
</code>```

And couldn't find how I can deal with user input?

If enter 5,

length - 5 unit, height 3 unit

length - 11 unit, height 6 unit

length - 23 unit, height 12 unit.

How can i know? What is the logic?

Ok lets say if I did. I understand I should put a tringle in another triangle with nested loop, can simply iterate it another dictionary but, I need to check second character's position.

Thanks in advance.

My code,

```
    ch1, ch2 = input("Please enter the characters you want to use: ")</p>

```num = int(input("Please specify the length of innermost triangle(only odd number): "))

if (num % 2 == 0) or (num < 3):
  print("Number can not be even, less then 3 and negative")

num2 = (2 * num) + 1
num3 = (2 * num2) +1
tri1 = {}
tri2 = {}
tri3 = {}

for i in range(3):
  tri1[i] = ch1*num
  num -= 2

check = 1
cont = 0
var = 1
for ii in range(6):
  tri2[ii] = ch2*check
  check += 2
  if (ii >= 3):
    tri2[ii] = ch2*var + tri1[cont] + ch2*var
    cont += 1
    var += 2

for i in tri1:
  print('{:^5}'.format(tri1[i]))

for i in tri2:
  print('{:^11}'.format(tri2[i]))
```

<p>```

答:
The dictionary can be created using a simple function:

```<code>def create_tri_dict(tri_chars, tri_height):
    level_str = {0:tri_chars[0]}

    for i in range(1,tri_height):
        level_length = i *2 +1
        tri_char = tri_chars[i%2]
        level_str[i] = level_str[i-1] + '\n' + tri_char * level_length
    return level_str
</code>```

Then the main logic of your program could be:

```<code>tri_chars = input('Input triangle characters: ')
tri_length = int(input('Input triangle base length: '))
tri_height = (tri_length + 1)//2
if tri_length %2 == 0:
    raise Exception('Triangle base length not odd')
tri_dict = create_tri_dict(tri_chars, tri_length)
</code>```

Then to print the final 3(?) triangles:

```<code>print(tri_dict[tri_height-2])
print(tri_dict[tri_height-1])
print(tri_dict[tri_height])
</code>```

Title: Nested Triangle in Python

Body:
My assingment

At each level the complete triangle for the previous level is placed into an extra outer triangle. The user should be asked to input the two characters to be used and the width of the innermost triangle, which must be odd. In addition to the test for negative input the function should test whether the supplied number is odd and display an appropriate message if it is not.

I need to print 3 triangles but every one of them includes other. It needs to get printed with two different character(like *-) and the user have to specify the length of innermost triangle and which has to be an odd number. Example,

Example output for 5 value

Ok, let me explain my way,

Every triangle should be in dictionary.

tri1 = {1:"*****", 2:"***", 3:"*"}
tri2 = {1:"..........", ...}

And couldn't find how I can deal with user input?

If enter 5,

length - 5 unit, height 3 unit

length - 11 unit, height 6 unit

length - 23 unit, height 12 unit.

How can i know? What is the logic?

Ok lets say if I did. I understand I should put a tringle in another triangle with nested loop, can simply iterate it another dictionary but, I need to check second character's position.

Thanks in advance.

My code,

    ch1, ch2 = input("Please enter the characters you want to use: ")

num = int(input("Please specify the length of innermost triangle(only odd number): "))

if (num % 2 == 0) or (num < 3):
  print("Number can not be even, less then 3 and negative")

num2 = (2 * num) + 1
num3 = (2 * num2) +1
tri1 = {}
tri2 = {}
tri3 = {}

for i in range(3):
  tri1[i] = ch1*num
  num -= 2

check = 1
cont = 0
var = 1
for ii in range(6):
  tri2[ii] = ch2*check
  check += 2
  if (ii >= 3):
    tri2[ii] = ch2*var + tri1[cont] + ch2*var
    cont += 1
    var += 2

for i in tri1:
  print('{:^5}'.format(tri1[i]))

for i in tri2:
  print('{:^11}'.format(tri2[i]))

Body:
The dictionary can be created using a simple function:

def create_tri_dict(tri_chars, tri_height):
    level_str = {0:tri_chars[0]}

    for i in range(1,tri_height):
        level_length = i *2 +1
        tri_char = tri_chars[i%2]
        level_str[i] = level_str[i-1] + '\n' + tri_char * level_length
    return level_str

Then the main logic of your program could be:

tri_chars = input('Input triangle characters: ')
tri_length = int(input('Input triangle base length: '))
tri_height = (tri_length + 1)//2
if tri_length %2 == 0:
    raise Exception('Triangle base length not odd')
tri_dict = create_tri_dict(tri_chars, tri_length)

Then to print the final 3(?) triangles:

print(tri_dict[tri_height-2])
print(tri_dict[tri_height-1])
print(tri_dict[tri_height])


问:
Importing modules with Swift package manager
I am trying to use Swift's package manager to import external modules in my project. My first module come from the Vapor project. I cannot seem to get it working. I start with

```<code>swift package init
swift package generate-xcodeproj
</code>```

My Package.swift looks like this:

```<code>import PackageDescription

let package = Package(
    name: "OpenTools",
    products: [
        .library(
            name: "OpenTools",
            targets: ["OpenTools"]),
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/json.git", from: "2.0.0")
    ],
    targets: [
        .target(name: "OpenTools", dependencies: ["JSON"]),
    ]
)
</code>```

I then run

```<code>swift package update
swift package generate-xcodeproj # to regenerate with dependencies
</code>```

and then try to import the JSON package in my main file

```<code>import JSON
</code>```

The modules are there as shown below but the import gets back with an No such module 'JSON' error.

Any thoughts?

答:
Probably the problem lies within Xcode, as it does not know yet that JSON exists, because it was not built yet. This can easily be solved by just building your project (with cmd-B). With the generated xcodeproj, Xcode should know that it first needs to build JSON and then the rest, because JSON is marked as a dependency for your target.

You can check this, by navigating in Xcode to your target (when you click on the project description file) and afterwards to "Build Phases". Under Target Dependencies you should find your JSON module.

In addition you should find a JSON module under your targets, which compiles the sources you gathered from github.

Your project should also build when executing swift build in your project root.

Body:
I am trying to use Swift's package manager to import external modules in my project. My first module come from the Vapor project. I cannot seem to get it working. I start with

swift package init
swift package generate-xcodeproj

My Package.swift looks like this:

import PackageDescription

let package = Package(
    name: "OpenTools",
    products: [
        .library(
            name: "OpenTools",
            targets: ["OpenTools"]),
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/json.git", from: "2.0.0")
    ],
    targets: [
        .target(name: "OpenTools", dependencies: ["JSON"]),
    ]
)

I then run

swift package update
swift package generate-xcodeproj # to regenerate with dependencies

and then try to import the JSON package in my main file

import JSON

The modules are there as shown below but the import gets back with an No such module 'JSON' error.

Any thoughts?


问:
Quicksort: Why wrong output
I want to sort the given array using quicksort.
So I wrote this code in c for quicksort algorithm but its not giving me correct answer.Its giving me the same output as the input.
 eg: If i give input as
 3
 2
 1
then it is giving
Output:
3
2
1
Please help and tell me where is the mistake.</p>

```<code>#include<stdio.h>
void quicksort(int a[],int p,int r);
int partition(int a[],int p,int r);
void swap(int a,int b);
int main()
{
    int n,i,p,r;
    printf("ENter no of elements");
    scanf("%d",&n);
    int a[n];
    printf("ENter the elements");
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    p=1;
    r=n;
    quicksort(a,1,n);
    printf("\n");
    for(i=1;i<=n;i++)
    {
        printf("%d\n",a[i]);
    }
    return 0;
}
void quicksort(int a[],int p,int r)
{
    int q;
    if(p<r)
    {
    q = partition(a,p,r);
    quicksort(a,p,q-1);
    quicksort(a,q+1,r);
    }

}
int partition(int a[],int p,int r)
{
    int x,i,j;
    x=a[r];
    i=p-1;
    for(j=p;j<=r-1;j++)
    {
        if(a[j]<=x)
        {
            i=i+1;
            swap(a[i],a[j]);
        }
    }
    swap(a[i+1],a[r]);

    return (i+1);
}
    void swap(int a,int b)
{
    int t;
    t=a;
    a=b;
    b=t;
}
</code>```

答:
```<code>void swap(int a,int b)
</code>```

This line is taking the two parameters as copies of the values. The swapping is done on he copies.

```<code>void swap(int* a, int* b)
</code>```

This is the C-style of passing parameters by reference. You need to pass the references then:

```<code>swap(&a[i], &a[j]);
</code>```

Title: Quicksort: Why wrong output

Body:
I want to sort the given array using quicksort.
So I wrote this code in c for quicksort algorithm but its not giving me correct answer.Its giving me the same output as the input.
 eg: If i give input as
 3
 2
 1
then it is giving
Output:
3
2
1
Please help and tell me where is the mistake.

#include<stdio.h>
void quicksort(int a[],int p,int r);
int partition(int a[],int p,int r);
void swap(int a,int b);
int main()
{
    int n,i,p,r;
    printf("ENter no of elements");
    scanf("%d",&n);
    int a[n];
    printf("ENter the elements");
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    p=1;
    r=n;
    quicksort(a,1,n);
    printf("\n");
    for(i=1;i<=n;i++)
    {
        printf("%d\n",a[i]);
    }
    return 0;
}
void quicksort(int a[],int p,int r)
{
    int q;
    if(p<r)
    {
    q = partition(a,p,r);
    quicksort(a,p,q-1);
    quicksort(a,q+1,r);
    }

}
int partition(int a[],int p,int r)
{
    int x,i,j;
    x=a[r];
    i=p-1;
    for(j=p;j<=r-1;j++)
    {
        if(a[j]<=x)
        {
            i=i+1;
            swap(a[i],a[j]);
        }
    }
    swap(a[i+1],a[r]);

    return (i+1);
}
    void swap(int a,int b)
{
    int t;
    t=a;
    a=b;
    b=t;
}

Body:
void swap(int a,int b)

This line is taking the two parameters as copies of the values. The swapping is done on he copies.

void swap(int* a, int* b)

This is the C-style of passing parameters by reference. You need to pass the references then:

swap(&a[i], &a[j]);


问:
How do I pass some extra string arguments to a spark udf for each row?
I am using Spark 1.5 CDH5.5

My requirement is I need to read each optional column from a dataframe and check if the length of that column is greater than the maxLimit,
if it is greater that maxLimit then i need to apply a substring on that column

if the value of  description is greater than 33 then i need to apply substring(0,33)
If the value of emr_id is greater than 34 then i need to apply substring(0,34)

To achieve this , I need to pass some extra string arguments to a spark udf, It throws the below error

I am calling a udf for each column as below

Please help me on what went wrong?

```<code> scala> updatedDF.printSchema
root
 |-- data_id: string (nullable = true)
 |-- description: string (nullable = true)
 |-- emr_id: string (nullable = true)

val METADATA_ATTRIBUTES_SIZE_SCHEMA =  List(
("data_id","data_id","string","mandatory","40"),
("description","description","string","optional","33"),
("emr_id","emr_id","string","optional","34")
)

 updatedDF = updatedDF.formatMetaData(METADATA_ATTRIBUTES_SIZE_SCHEMA)
</code>```

I have  the below trait which has lots of methods that can be directly invoked by any dataframe

```<code>trait MetaDataOperations {

val df: DataFrame

 def formatMetaData(schema: List  [(String,String,String,String,String)]) :DataFrame = {
var formattedDF = df
val getFormattedMetaData= udf(getFormattedMetaDataUdf _)
for(column <- formattedDF.columns){
  val schemaList = schema.filter(tuple => tuple._1.equals(column))
  val attributeDataType = schemaList.head._3.toString
  val attributeConformance = schemaList.head._4.toString
  val attributeMaxSize = schemaList.head._5.toString
  formattedDF = formattedDF.withColumn(column, getFormattedMetaData(formattedDF(column),lit(attributeDataType),lit(attributeConformance),lit(attributeMaxSize)))
}
formattedDF
 }

  def getFormattedMetaDataUdf (colValue:String,attributeDataType:String,attributeConformance:String,attributeMaxSize:String): String = {
   var maxLength = 0
   var formattedColValue = attributeConformance match {
   case "optional" => {
    if (attributeDataType == "string") {
      maxLength = attributeMaxSize.toInt
    }

    if (colValue.length > maxLength) {
      colValue.substring(0, maxLength) + "..."
    }
    else {
      colValue
    }
  }
  case _ => colValue
}
formattedColValue
}

 }
</code>```

I am getting the below error

```<code>java.lang.ClassCastException: $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1 cannot be cast to scala.Function4
    at org.apache.spark.sql.catalyst.expressions.ScalaUDF.<init>(ScalaUDF.scala:107)
    at org.apache.spark.sql.UserDefinedFunction.apply(UserDefinedFunction.scala:50)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:60)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:55)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:108)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:55)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:66)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:68)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:70)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:72)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:74)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:76)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:78)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:80)
    at $iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:82)
    at $iwC$$iwC$$iwC$$iwC.<init>(<console>:84)
    at $iwC$$iwC$$iwC.<init>(<console>:86)
    at $iwC$$iwC.<init>(<console>:88)
    at $iwC.<init>(<console>:90)
    at <init>(<console>:92)
    at .<init>(<console>:96)
    at .<clinit>(<console>)
    at .<init>(<console>:7)
    at .<clinit>(<console>)
    at $print(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)
</code>```

答:
getFormattedMetaDataUdf is not and UDF. It is a standard Scala Function4. You have to use udf wrapper

```<code> val  getFormattedMetaDataUdf = udf(getFormattedMetaData _)
</code>```

Body:
I am using Spark 1.5 CDH5.5

My requirement is I need to read each optional column from a dataframe and check if the length of that column is greater than the maxLimit,
if it is greater that maxLimit then i need to apply a substring on that column

if the value of  description is greater than 33 then i need to apply substring(0,33)
If the value of emr_id is greater than 34 then i need to apply substring(0,34)

To achieve this , I need to pass some extra string arguments to a spark udf, It throws the below error

I am calling a udf for each column as below

Please help me on what went wrong?

 scala> updatedDF.printSchema
root
 |-- data_id: string (nullable = true)
 |-- description: string (nullable = true)
 |-- emr_id: string (nullable = true)

val METADATA_ATTRIBUTES_SIZE_SCHEMA =  List(
("data_id","data_id","string","mandatory","40"),
("description","description","string","optional","33"),
("emr_id","emr_id","string","optional","34")
)

 updatedDF = updatedDF.formatMetaData(METADATA_ATTRIBUTES_SIZE_SCHEMA)

I have  the below trait which has lots of methods that can be directly invoked by any dataframe

trait MetaDataOperations {

val df: DataFrame

 def formatMetaData(schema: List  [(String,String,String,String,String)]) :DataFrame = {
var formattedDF = df
val getFormattedMetaData= udf(getFormattedMetaDataUdf _)
for(column <- formattedDF.columns){
  val schemaList = schema.filter(tuple => tuple._1.equals(column))
  val attributeDataType = schemaList.head._3.toString
  val attributeConformance = schemaList.head._4.toString
  val attributeMaxSize = schemaList.head._5.toString
  formattedDF = formattedDF.withColumn(column, getFormattedMetaData(formattedDF(column),lit(attributeDataType),lit(attributeConformance),lit(attributeMaxSize)))
}
formattedDF
 }

  def getFormattedMetaDataUdf (colValue:String,attributeDataType:String,attributeConformance:String,attributeMaxSize:String): String = {
   var maxLength = 0
   var formattedColValue = attributeConformance match {
   case "optional" => {
    if (attributeDataType == "string") {
      maxLength = attributeMaxSize.toInt
    }

    if (colValue.length > maxLength) {
      colValue.substring(0, maxLength) + "..."
    }
    else {
      colValue
    }
  }
  case _ => colValue
}
formattedColValue
}

 }

I am getting the below error

java.lang.ClassCastException: $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1 cannot be cast to scala.Function4
    at org.apache.spark.sql.catalyst.expressions.ScalaUDF.<init>(ScalaUDF.scala:107)
    at org.apache.spark.sql.UserDefinedFunction.apply(UserDefinedFunction.scala:50)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:60)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:55)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:108)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:55)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:66)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:68)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:70)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:72)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:74)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:76)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:78)
    at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:80)
    at $iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:82)
    at $iwC$$iwC$$iwC$$iwC.<init>(<console>:84)
    at $iwC$$iwC$$iwC.<init>(<console>:86)
    at $iwC$$iwC.<init>(<console>:88)
    at $iwC.<init>(<console>:90)
    at <init>(<console>:92)
    at .<init>(<console>:96)
    at .<clinit>(<console>)
    at .<init>(<console>:7)
    at .<clinit>(<console>)
    at $print(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)

Body:
getFormattedMetaDataUdf is not and UDF. It is a standard Scala Function4. You have to use udf wrapper

 val  getFormattedMetaDataUdf = udf(getFormattedMetaData _)


问:
Slider skips one slide while clicking next/prev
I have two challenges building my own carousel.

1 When you click to the next or previous button (in my case it's the black box) it skips one slide.

Please check this fiddle: https://fiddle.jshell.net/k1ea93xt/3/

Simply, when you click next or prev only, it works good, but when you change your mind and hit the other one, the problem occurs.

Generally, I think I know what is the cause. I add class "out" to the next slider to launch the animation

```<code>$('.nxt').addClass('out');
</code>```

and "in" - reversed animation to the previous slider

```<code>$('.prv').addClass('in');
</code>```

Both "in" and "out" remains in the current slider which destroys the translateX value.

2 Second issue is I change sliders by changing classes nxt, prv and current (my js skills are limited)

```<code>$('.nxt').addClass('out');
$('.current').removeClass('out');
$('.prv').removeClass('out');

$('.t1').removeClass('current');
$('.t2').removeClass('nxt');
$('.t3').removeClass('prv');

$('.t1').addClass('prv');
$('.t2').addClass('current');
$('.t3').addClass('nxt');

$('.current').removeClass('t2');
$('.prv').removeClass('t1');
$('.nxt').removeClass('t3');

$('.current').addClass('t1');
$('.nxt').addClass('t2');
$('.prv').addClass('t3');

$('.t1').removeClass('in');
$('.t2').removeClass('in');
$('.t3').removeClass('in');
</code>```

The problem is I can't have more than 3 slides in the carousel. Is there a simple way to assign classes current, prv and nxt automatically?
Thx in advance.

答:
I have updated your jQuery and created a function to find next and previous slides and added some setTimeout(). this will allow you to have as many slides as you want.

I have also moved the slider buttons outside of the slider as the function look for elements inside .main-slider

    var interval = undefined;
$(document).ready(function () {
    interval = setInterval(getNext, 1000); // milliseconds
    $('.next').on('click', getNext);
    $('.previous').on('click', getPrev);
});
//Get next slide
function getNext() {
    var $curr = $('.main-slider .slide.current'),
        $next = ($curr.next().length) ? $curr.next() : $('.main-slider .slide').first();
    transitionOut($curr, $next);
}

// get previous
function getPrev() {
    var $curr = $('.main-slider .slide.current'),
        $next = ($curr.prev().length) ? $curr.prev() : $('.main-slider .slide').last();
    transitionIn($curr, $next);
}
//slide in
function transitionIn($curr, $next) {
    clearInterval(interval);
        $curr.css('z-index', 0).removeClass('current');
        $next.show().css('z-index', 1).addClass('in').addClass('current');
        $next.children().addClass('in');
          setTimeout(function(){
            $curr.hide();
            $next.removeClass('in');
            $next.children().removeClass('in');
          },1000)

}
//slide out
function transitionOut($curr, $next) {
    clearInterval(interval);
        $curr.css('z-index', 1).addClass('out').removeClass('current');
        $next.show().css('z-index', 0).addClass('current');
        $curr.children().addClass('out');
         setTimeout(function(){
            $curr.hide();
            $curr.removeClass('out');
            $curr.children().removeClass('out');
          },1000)
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body, html {
    margin:0;
    height:100%;
    }
/*slider*/
.main-slider {
    height: 100%;
    position: relative;
    margin: 0 auto;
    overflow: hidden;
}
.main-slider .cover {
    object-fit: cover;
    width: 100% !important;
    height: 100%;
    left: 0;
}
.main-slider img {
    top: -9999px;
    bottom: -9999px;
    right: 0;
    margin: auto;
    position: absolute !important;
    display: block;
    float: left;
    text-align: left;
    overflow-x: hidden;
}
.slide {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100%;
    overflow: hidden;
    display: none;
}

.cropped-image{
    height: 100%;
    margin: 0;
}
.slide.in {
  z-index: 3;
    transform: translateX(-0%);
    -webkit-animation-duration: 1000ms;
    animation-duration: 1000ms;
    animation-name: slide-in;
    -webkit-animation-direction: alternate-reverse;
    -webkit-animation-timing-function: cubic-bezier(.82,0,.19,1); /* Safari 4.0 - 8.0 */
    animation-timing-function: cubic-bezier(.82,0,.19,1);
}
.cropped-image.in {
    transform: translateX(0%);
    -webkit-animation-duration: 1000ms;
    animation-duration: 1000ms;
    -webkit-animation-name: slide-in-b;
    animation-name: slide-in-b;
    -webkit-animation-direction: alternate-reverse;
    -webkit-animation-timing-function: cubic-bezier(.82,0,.19,1); /* Safari 4.0 - 8.0 */
    animation-timing-function: cubic-bezier(.82,0,.19,1);

}

.slide.out {
    transform: translateX(-0%);
    -webkit-animation-duration: 1000ms;
    animation-duration: 1000ms;
    animation-name: slide-in;
    -webkit-animation-direction: alternate;
    -webkit-animation-fill-mode: forwards;
    -webkit-animation-timing-function: cubic-bezier(.82,0,.19,1); /* Safari 4.0 - 8.0 */
    animation-timing-function: cubic-bezier(.82,0,.19,1);
}
.cropped-image.out {
    transform: translateX(0%);
    -webkit-animation-duration: 1000ms;
    animation-duration: 1000ms;
    -webkit-animation-name: slide-in-b;
    animation-name: slide-in-b;
    -webkit-animation-direction: alternate;
    -webkit-animation-fill-mode: forwards;
    -webkit-animation-timing-function: cubic-bezier(.82,0,.19,1); /* Safari 4.0 - 8.0 */
    animation-timing-function: cubic-bezier(.82,0,.19,1);
}
@keyframes slide-in {
    0%   {transform: translateX(-0%);}
    100%  {transform: translateX(-100%);}
}

@keyframes slide-in-b {
    0%   {transform: translateX(0%);}
    100%  {transform: translateX(100%);}
}
.next {
    position: absolute;
    height: 80px;
    background: #141212;
    width: 80px;
    right: 0;
    bottom: 50%;
    z-index: 9;
}
.previous {
    position: absolute;
    height: 80px;
    background: #141212;
    width: 80px;
    left: 0;
    bottom: 50%;
    z-index: 9;
}
/* end of slider*/</code>```

```

Hope this helps

Body:
I have two challenges building my own carousel.

1 When you click to the next or previous button (in my case it's the black box) it skips one slide.

Please check this fiddle: https://fiddle.jshell.net/k1ea93xt/3/

Simply, when you click next or prev only, it works good, but when you change your mind and hit the other one, the problem occurs.

Generally, I think I know what is the cause. I add class "out" to the next slider to launch the animation

$('.nxt').addClass('out');

and "in" - reversed animation to the previous slider

$('.prv').addClass('in');

Both "in" and "out" remains in the current slider which destroys the translateX value.

2 Second issue is I change sliders by changing classes nxt, prv and current (my js skills are limited)

$('.nxt').addClass('out');
$('.current').removeClass('out');
$('.prv').removeClass('out');

$('.t1').removeClass('current');
$('.t2').removeClass('nxt');
$('.t3').removeClass('prv');

$('.t1').addClass('prv');
$('.t2').addClass('current');
$('.t3').addClass('nxt');

$('.current').removeClass('t2');
$('.prv').removeClass('t1');
$('.nxt').removeClass('t3');

$('.current').addClass('t1');
$('.nxt').addClass('t2');
$('.prv').addClass('t3');

$('.t1').removeClass('in');
$('.t2').removeClass('in');
$('.t3').removeClass('in');

The problem is I can't have more than 3 slides in the carousel. Is there a simple way to assign classes current, prv and nxt automatically?
Thx in advance.

Body:
I have updated your jQuery and created a function to find next and previous slides and added some setTimeout(). this will allow you to have as many slides as you want.

I have also moved the slider buttons outside of the slider as the function look for elements inside .main-slider

    var interval = undefined;
$(document).ready(function () {
    interval = setInterval(getNext, 1000); // milliseconds
    $('.next').on('click', getNext);
    $('.previous').on('click', getPrev);
});
//Get next slide
function getNext() {
    var $curr = $('.main-slider .slide.current'),
        $next = ($curr.next().length) ? $curr.next() : $('.main-slider .slide').first();
    transitionOut($curr, $next);
}

// get previous
function getPrev() {
    var $curr = $('.main-slider .slide.current'),
        $next = ($curr.prev().length) ? $curr.prev() : $('.main-slider .slide').last();
    transitionIn($curr, $next);
}
//slide in
function transitionIn($curr, $next) {
    clearInterval(interval);
        $curr.css('z-index', 0).removeClass('current');
        $next.show().css('z-index', 1).addClass('in').addClass('current');
        $next.children().addClass('in');
          setTimeout(function(){
            $curr.hide();
            $next.removeClass('in');
            $next.children().removeClass('in');
          },1000)

}
//slide out
function transitionOut($curr, $next) {
    clearInterval(interval);
        $curr.css('z-index', 1).addClass('out').removeClass('current');
        $next.show().css('z-index', 0).addClass('current');
        $curr.children().addClass('out');
         setTimeout(function(){
            $curr.hide();
            $curr.removeClass('out');
            $curr.children().removeClass('out');
          },1000)
    }

body, html {
    margin:0;
    height:100%;
    }
/*slider*/
.main-slider {
    height: 100%;
    position: relative;
    margin: 0 auto;
    overflow: hidden;
}
.main-slider .cover {
    object-fit: cover;
    width: 100% !important;
    height: 100%;
    left: 0;
}
.main-slider img {
    top: -9999px;
    bottom: -9999px;
    right: 0;
    margin: auto;
    position: absolute !important;
    display: block;
    float: left;
    text-align: left;
    overflow-x: hidden;
}
.slide {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100%;
    overflow: hidden;
    display: none;
}

.cropped-image{
    height: 100%;
    margin: 0;
}
.slide.in {
  z-index: 3;
    transform: translateX(-0%);
    -webkit-animation-duration: 1000ms;
    animation-duration: 1000ms;
    animation-name: slide-in;
    -webkit-animation-direction: alternate-reverse;
    -webkit-animation-timing-function: cubic-bezier(.82,0,.19,1); /* Safari 4.0 - 8.0 */
    animation-timing-function: cubic-bezier(.82,0,.19,1);
}
.cropped-image.in {
    transform: translateX(0%);
    -webkit-animation-duration: 1000ms;
    animation-duration: 1000ms;
    -webkit-animation-name: slide-in-b;
    animation-name: slide-in-b;
    -webkit-animation-direction: alternate-reverse;
    -webkit-animation-timing-function: cubic-bezier(.82,0,.19,1); /* Safari 4.0 - 8.0 */
    animation-timing-function: cubic-bezier(.82,0,.19,1);

}

.slide.out {
    transform: translateX(-0%);
    -webkit-animation-duration: 1000ms;
    animation-duration: 1000ms;
    animation-name: slide-in;
    -webkit-animation-direction: alternate;
    -webkit-animation-fill-mode: forwards;
    -webkit-animation-timing-function: cubic-bezier(.82,0,.19,1); /* Safari 4.0 - 8.0 */
    animation-timing-function: cubic-bezier(.82,0,.19,1);
}
.cropped-image.out {
    transform: translateX(0%);
    -webkit-animation-duration: 1000ms;
    animation-duration: 1000ms;
    -webkit-animation-name: slide-in-b;
    animation-name: slide-in-b;
    -webkit-animation-direction: alternate;
    -webkit-animation-fill-mode: forwards;
    -webkit-animation-timing-function: cubic-bezier(.82,0,.19,1); /* Safari 4.0 - 8.0 */
    animation-timing-function: cubic-bezier(.82,0,.19,1);
}
@keyframes slide-in {
    0%   {transform: translateX(-0%);}
    100%  {transform: translateX(-100%);}
}

@keyframes slide-in-b {
    0%   {transform: translateX(0%);}
    100%  {transform: translateX(100%);}
}
.next {
    position: absolute;
    height: 80px;
    background: #141212;
    width: 80px;
    right: 0;
    bottom: 50%;
    z-index: 9;
}
.previous {
    position: absolute;
    height: 80px;
    background: #141212;
    width: 80px;
    left: 0;
    bottom: 50%;
    z-index: 9;
}
/* end of slider*/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="next"></div>
    <div class="previous"></div>
<div class="main-slider">
    <div class="slide">
      <figure class="cropped-image">
        <img src="https://images.unsplash.com/photo-1508108712903-49b7ef9b1df8?auto=format&fit=crop&w=2250&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D" class="cover">
      </figure>
    </div>
    <div class="slide">
      <figure class="cropped-image">
        <img src="https://images.unsplash.com/photo-1507980668227-a52aa457699b?auto=format&fit=crop&w=2250&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D" class="cover">
      </figure>
    </div>
    <div class="slide">
      <figure class="cropped-image">
        <img src="https://images.unsplash.com/photo-1497030855747-0fc424f89a4b?auto=format&fit=crop&w=2250&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D" class="cover">
      </figure>
    </div>
    </div>

Hope this helps


问:
How to allocate a remote pty using Net::SSH::Connection::Channel#request_pty
I am building a raspberry-pi clients manager, where those clients are connected to a server through SSH reverse tunnels. I am using for this the Sinatra framework and the net-ssh library. For single commands this is obvious, I used server-side events where I send the commands to a given url. At That action, the command is pushed to a queue, and get executed asynchronously, then the results get pushed to the event-stream connection whenever data is available, here is the pseudo code of the command runner:

```<code> require 'net/ssh'
 # start a separate thread avoid blocking the main thread of the server.
 Thread.start do
      sess = Net::SSH.start(HOST, USER, :password => 'pass', :port => 'port')
      # once a command is pushed to the queue on the dedecated sinatra action
      # the command get executed, once the execution ends this will start listening
      # again
    loop{
      sess.exec! (queue.pop()) do|ch, stream, data|
      #this is the server-sent events stream, here the data is pushed to the client
      #EventSource
      stream_event_connection << data
      end
    }
 end
</code>```

for single commands this is ok, for example a command like 'ls /root'. But what I need is to open a live terminal(Interective shell), where the user enters commands and gets results like if its on a real ssh terminal.I though migh be opening a pty on the remote Respberry-PI client, and by using the expect library, this will be possible.
For requesting a pty their is the Net::SSH::Connection::Channel#request_pty method, but I cannot find any example on how to use it. any ideas?

答:
I believe what you're looking for can be done like:

```<code>shell = sess.shell.open(:pty => true)
...
shell.exec! queue.pop ...
</code>```

Hope that helps

Body:
I am building a raspberry-pi clients manager, where those clients are connected to a server through SSH reverse tunnels. I am using for this the Sinatra framework and the net-ssh library. For single commands this is obvious, I used server-side events where I send the commands to a given url. At That action, the command is pushed to a queue, and get executed asynchronously, then the results get pushed to the event-stream connection whenever data is available, here is the pseudo code of the command runner:

 require 'net/ssh'
 # start a separate thread avoid blocking the main thread of the server.
 Thread.start do
      sess = Net::SSH.start(HOST, USER, :password => 'pass', :port => 'port')
      # once a command is pushed to the queue on the dedecated sinatra action
      # the command get executed, once the execution ends this will start listening
      # again
    loop{
      sess.exec! (queue.pop()) do|ch, stream, data|
      #this is the server-sent events stream, here the data is pushed to the client
      #EventSource
      stream_event_connection << data
      end
    }
 end

for single commands this is ok, for example a command like 'ls /root'. But what I need is to open a live terminal(Interective shell), where the user enters commands and gets results like if its on a real ssh terminal.I though migh be opening a pty on the remote Respberry-PI client, and by using the expect library, this will be possible.
For requesting a pty their is the Net::SSH::Connection::Channel#request_pty method, but I cannot find any example on how to use it. any ideas?

Body:
I believe what you're looking for can be done like:

shell = sess.shell.open(:pty => true)
...
shell.exec! queue.pop ...

Hope that helps


问:
Angular change route params without changing children route
Here is a router configuration :

```<code>export const routes: Routes = [
  {
    path: 'atc/:atcId',
    component: AtcComponent,
    resolve: {
      atcList: 'atcList',
    },
    children: [
      {path: '', redirectTo: 'goal', pathMatch: 'full'},
      {
        path: 'goal',
        component: GoalComponent
      },
      {
        path: 'visit',
        component: VisitComponent
      },
    ]
  }
];
</code>```

I want to navigate to a "brother" page. So if i'm in /atc/1/goal, it want to go to /atc/2/goal. If i'm in /atc/1/visit, I want to go to /atc/2/visit.

Let's suppose my current route is /atc/1/visit
I want to navigate to atc of id 2.

I'm inside AtcComponent. For this parent component POV, my current route is /atc/1. It know nothing of 'goal' or 'visit'.
I do something like this :

```<code>this.router.navigate(['../', '2'], {relativeTo: this.route});
</code>```

But when I do this, it resolve it as /atc/2. It remove the 'visit' or 'goal' part. It is then redirected to /atc/2/goal because of route.

Did I miss something in the API or is there a way not too hacky to keep children route as it is ?

Thank you

Edit : Here is a stackblitz to better explain this case : https://stackblitz.com/edit/angular-keep-children-route

答:
You should redirect in this way:</p>

```<code>this.router.navigate(['../', '2', 'visit'], {relativeTo: this.route});
</code>```

Body:
Here is a router configuration :

export const routes: Routes = [
  {
    path: 'atc/:atcId',
    component: AtcComponent,
    resolve: {
      atcList: 'atcList',
    },
    children: [
      {path: '', redirectTo: 'goal', pathMatch: 'full'},
      {
        path: 'goal',
        component: GoalComponent
      },
      {
        path: 'visit',
        component: VisitComponent
      },
    ]
  }
];

I want to navigate to a "brother" page. So if i'm in /atc/1/goal, it want to go to /atc/2/goal. If i'm in /atc/1/visit, I want to go to /atc/2/visit.

Let's suppose my current route is /atc/1/visit
I want to navigate to atc of id 2.

I'm inside AtcComponent. For this parent component POV, my current route is /atc/1. It know nothing of 'goal' or 'visit'.
I do something like this :

this.router.navigate(['../', '2'], {relativeTo: this.route});

But when I do this, it resolve it as /atc/2. It remove the 'visit' or 'goal' part. It is then redirected to /atc/2/goal because of route.

Did I miss something in the API or is there a way not too hacky to keep children route as it is ?

Thank you

Edit : Here is a stackblitz to better explain this case : https://stackblitz.com/edit/angular-keep-children-route

Body:
You should redirect in this way:

this.router.navigate(['../', '2', 'visit'], {relativeTo: this.route});


问:
Tensorflow: read raw file with uint8 and float32
It's easy to read raw file consists values of single type, uint8 or int32, etc.

```<code>record = tf.reshape(tf.decode_raw(data, tf.uint8), [record_bytes])
</code>```

Now if the each record consists of uint8 data and float32 labels, how to read it correctly?

Ex: format of each record is:

```<code>data         label
2048 uint8   8 floats
total bytes of each record = 2048 + 8*4 = 2072
</code>```

答:
You can use the tf.substr() operation to select the appropriate ranges of bytes from the record, then use tf.decode_raw() twice with the different types. For example, assuming your raw data is in a tf.string tensor called data:

```<code>features = tf.decode_raw(tf.substr(data, 0, 2048), tf.uint8)
label = tf.decode_raw(tf.substr(data, 2048, 32), tf.float32)
</code>```

Body:
It's easy to read raw file consists values of single type, uint8 or int32, etc.

record = tf.reshape(tf.decode_raw(data, tf.uint8), [record_bytes])

Now if the each record consists of uint8 data and float32 labels, how to read it correctly?

Ex: format of each record is:

data         label
2048 uint8   8 floats
total bytes of each record = 2048 + 8*4 = 2072

Body:
You can use the tf.substr() operation to select the appropriate ranges of bytes from the record, then use tf.decode_raw() twice with the different types. For example, assuming your raw data is in a tf.string tensor called data:

features = tf.decode_raw(tf.substr(data, 0, 2048), tf.uint8)
label = tf.decode_raw(tf.substr(data, 2048, 32), tf.float32)


问:
Boost upgrade_lock and DCLP (double-checked locking pattern)
Suppose we have the following (pseudo) code:

```<code>using UpgradeLock = boost::upgrade_lock<boost::shared_mutex>;
using UpgradeToUniqueLock = boost::upgrade_to_unique_lock<boost::shared_mutex>;

boost::shared_mutex mtx;

void DeleteTable(<tbl>) {
  UpgradeLock lock(mtx);
  if (<the table exists>) {
    UpgradeToUniqueLock up(lock); // (!)
    // delete the table
  }
}
</code>```

And suppose two threads have just entered into this function and both reached the statement, marked with (!).

I can't figure out what will happen then. I have the following options:

One thread cannot acquire exclusive access until the second one releases its UpgradeLock, but it cannot until it gets exclusive access too. Deadlock.

One thread acquires exclusive access, while another one is being suspended at the line with mark (!).

I guess the second option is what probably will happen, but in this case it comes out, that even having locked environment, we have to recheck that our data hasn't been changed "outside", i.e. we have to use the notorious DCLP. Am I right?

I haven't found any plausible info about it, so don't blame me a lot :)

答:
If I correctly understand you, then the number 2 is going to happen.

If you are using Reader/Writer Locks you must stick to the protocol which assumes, that as long as multiple readers share the lock, they are only allowed to do read access. If they need to acquire some writing privileges, they must upgrade the lock.

Now in you case it can happen that multiple threads enter the if-statement and wait for lock acquisition. That's true and they will all get the lock one after the other. The problem is that right after the lock acquisition it might happen that another thread already delete-ed the table.

That's why you might need the double-checked locking pattern.

From here you have multiple options:

option 1:
check if table is pointing to NULL and do nothing

option 2:
just call delete again, if the pointer is set to NULL or nullptr after you call delete C++ is fine with that (if delete comes from the standard lib) => and will just do nothing. Just for reference read:

http://en.cppreference.com/w/cpp/language/delete

if expression evaluates to a null pointer value, no destructors are called, and the deallocation function is not called.

```<code>  UpgradeLock lock(mtx);

  if (<the table exists>)
  {
     UpgradeToUniqueLock up(lock); // (!)
     if(<table still exists>)
     {
       // delete the table
       // and set the pointer to nullptr
     }
   }
</code>```

but according to option 2 the following snippet is just fine if delete is implemented by STL:
      UpgradeLock lock(mtx);

```<code>  if (<the table exists>)
  {
     UpgradeToUniqueLock up(lock); // (!)
     // delete the table
     // and set the pointer to nullptr

  }
</code>```

option 3:
Use std::shared_ptr or boost::shared_ptr instead. They are synchronized. So you even don't need locks, just call ptr.reset() from multiple threads and that's it.

Body:
Suppose we have the following (pseudo) code:

using UpgradeLock = boost::upgrade_lock<boost::shared_mutex>;
using UpgradeToUniqueLock = boost::upgrade_to_unique_lock<boost::shared_mutex>;

boost::shared_mutex mtx;

void DeleteTable(<tbl>) {
  UpgradeLock lock(mtx);
  if (<the table exists>) {
    UpgradeToUniqueLock up(lock); // (!)
    // delete the table
  }
}

And suppose two threads have just entered into this function and both reached the statement, marked with (!).

I can't figure out what will happen then. I have the following options:

One thread cannot acquire exclusive access until the second one releases its UpgradeLock, but it cannot until it gets exclusive access too. Deadlock.

One thread acquires exclusive access, while another one is being suspended at the line with mark (!).

I guess the second option is what probably will happen, but in this case it comes out, that even having locked environment, we have to recheck that our data hasn't been changed "outside", i.e. we have to use the notorious DCLP. Am I right?

I haven't found any plausible info about it, so don't blame me a lot :)

Body:
If I correctly understand you, then the number 2 is going to happen.

If you are using Reader/Writer Locks you must stick to the protocol which assumes, that as long as multiple readers share the lock, they are only allowed to do read access. If they need to acquire some writing privileges, they must upgrade the lock.

Now in you case it can happen that multiple threads enter the if-statement and wait for lock acquisition. That's true and they will all get the lock one after the other. The problem is that right after the lock acquisition it might happen that another thread already delete-ed the table.

That's why you might need the double-checked locking pattern.

From here you have multiple options:

option 1:
check if table is pointing to NULL and do nothing

option 2:
just call delete again, if the pointer is set to NULL or nullptr after you call delete C++ is fine with that (if delete comes from the standard lib) => and will just do nothing. Just for reference read:

http://en.cppreference.com/w/cpp/language/delete

if expression evaluates to a null pointer value, no destructors are called, and the deallocation function is not called.

  UpgradeLock lock(mtx);

  if (<the table exists>)
  {
     UpgradeToUniqueLock up(lock); // (!)
     if(<table still exists>)
     {
       // delete the table
       // and set the pointer to nullptr
     }
   }

but according to option 2 the following snippet is just fine if delete is implemented by STL:
      UpgradeLock lock(mtx);

  if (<the table exists>)
  {
     UpgradeToUniqueLock up(lock); // (!)
     // delete the table
     // and set the pointer to nullptr

  }

option 3:
Use std::shared_ptr or boost::shared_ptr instead. They are synchronized. So you even don't need locks, just call ptr.reset() from multiple threads and that's it.


问:
Can I host my own database in Commercetools platform?
It is possible in magento where I can set my inhouse database at localhost. Can I do the same with commercetools?

I do not like to share my data with commercetools, but I still want to use it.

答:
The commercetools platform is a PaaS. There is no way for clients to install the database on their localhost. You cannot make use of the platform's commerce features if you don't provide the platform with data.

What is your concern with sharing your data with commercetools? Although the commercetools platform is a multi-tenant PaaS, your project's data is well isolated from any other project on the platform. The access to your data is protected by OAuth2.


问:
dropdown menu item in css positioning
I want to make a dropdown menu in CSS ... I already have a menu with "fixed" position(this first menu has to be fixed and nothing else)
but when I try to design my dropdown menu, items in it don't go to the position I want and always align to the first menu...
plz, tell how to do it correctly....

#menu {
            overflow: hidden;
            position: fixed;
            top: 0;
            width: 50%;
            margin-left: 25%;
            background-color: #333;
            color: #f2f2f2;
        }
        .menu-content {
            float: left;
            display: block;
            text-decoration: none;
            padding: 25px 20px;
            font-size: 17px;
        }
        #products {
            padding-top: 25px;
            font-size: 22px;
        }
        .dropdown {
            float: left;
            overflow: hidden;
        }
        .dropdown .dropdown-btn {
            font-size: 16px;
            border: none;
            outline: none;
            color: white;
            padding: 14px 16px;
            background-color: inherit;
        }
        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 160px;
            z-index: 1;
        }
        .dropdown-content a {
            float: none;
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
            text-align: center ;
        }
        .dropdown:hover .dropdown-content {
            display: block;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div id="menu">
        <div class="dropdown">
            <button id="products" class="dropdown-btn menu-content"> <i class="fa fa-bars"></i> products  </button>
            <div class="dropdown-content">
                <a> speaker </a>
            </div>
        </div>
    </div
</body></code>```

this is the result I get:
enter image description here

答:
a way to fix it is to change the positioning from absolute to relative. also add a way to position it</p>

```<code>    .dropdown-content {
        display: none;
        position: absolute;<-- change to relative-->
        background-color: #f9f9f9;
        min-width: 160px;
        z-index: 1;
</code>```

Title: dropdown menu item in css positioning

Body:
I want to make a dropdown menu in CSS ... I already have a menu with "fixed" position(this first menu has to be fixed and nothing else)
but when I try to design my dropdown menu, items in it don't go to the position I want and always align to the first menu...
plz, tell how to do it correctly....

#menu {
            overflow: hidden;
            position: fixed;
            top: 0;
            width: 50%;
            margin-left: 25%;
            background-color: #333;
            color: #f2f2f2;
        }
        .menu-content {
            float: left;
            display: block;
            text-decoration: none;
            padding: 25px 20px;
            font-size: 17px;
        }
        #products {
            padding-top: 25px;
            font-size: 22px;
        }
        .dropdown {
            float: left;
            overflow: hidden;
        }
        .dropdown .dropdown-btn {
            font-size: 16px;
            border: none;
            outline: none;
            color: white;
            padding: 14px 16px;
            background-color: inherit;
        }
        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 160px;
            z-index: 1;
        }
        .dropdown-content a {
            float: none;
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
            text-align: center ;
        }
        .dropdown:hover .dropdown-content {
            display: block;
        }

            <button id="products" class="dropdown-btn menu-content">  products  </button>

                 speaker

    </div

this is the result I get:
enter image description here

Body:
a way to fix it is to change the positioning from absolute to relative. also add a way to position it

    .dropdown-content {
        display: none;
        position: absolute;<-- change to relative-->
        background-color: #f9f9f9;
        min-width: 160px;
        z-index: 1;


问:
Change column names used to save timestamp
When storing or editing data in a table by laravel it creates a timestamp that uses the fields created_at and updated_at.

But I have to store the data in a table shared with another system, and it uses another nomenclature to store this data.

Without being the solution to set the timestamp = false and at the time of storing myself add the timestamp there.

In the model itself do I have to set the created_at and updated_at data to be saved in other columns?

答:
As Eloquent documentation says, you can override consts on your models</p>

```<code>const CREATED_AT = 'created_at_column_name';
const UPDATED_AT = 'updated_at_column_name';
</code>```

Body:
As Eloquent documentation says, you can override consts on your models

const CREATED_AT = 'created_at_column_name';
const UPDATED_AT = 'updated_at_column_name';